<?php

namespace app\repository;

use app\exception\RepositoryException;
use app\model\Account;
use app\model\AccountDataLog;
use app\model\AccountRecord;
use app\model\AccountWithdrawalCommission;
use app\model\Channel;
use app\model\Message as MessageModel;
use app\model\ShareRegLog;
use app\model\Staff;
use app\service\ExtraConfig;
use app\service\File;
use app\service\Repository;
use app\traits\account\AccountAddressTrait;
use app\traits\account\AccountDataLogTrait;
use app\traits\account\AccountLevelTrait;
use app\traits\account\AccountMessageTrait;
use app\traits\account\AccountRecordTrait;
use app\traits\account\AccountScoreTrait;
use app\traits\account\CouponTrait;
use app\traits\account\TagTrait;
use app\traits\account\FeedbackTrait;
use app\traits\SignTrait;
use Exception;
use GuzzleHttp\Exception\GuzzleException;
use think\Collection;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Db;
use think\Model;

/**
 * 账户域 相关操作(客户账号)
 *
 * Class AccountRepository
 * @package app\repository
 * @method self getInstance(Model $model = null) static
 */
class AccountRepository extends Repository
{
    use AccountRecordTrait;
    use AccountDataLogTrait;
    use CouponTrait;

    public const STATUS_NORMAL  = Account::STATUS_NORMAL; //正常
    public const STATUS_DISABLE = Account::STATUS_DISABLE;//禁用

    /**
     * 获取用户列表
     *
     * @throws RepositoryException
     */
    public function list(): ?array
    {
        return $this->findList();
    }

    /**
     * 获取指定账户记录By手机号
     *
     * @param  string  $phone
     * @param  array  $fields
     * @return Model|null
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function infoByPhone(string $phone, array $fields = []): ?Model
    {
        $where[] = ['mobile', '=', $phone];
        return $this->findOneByWhere($where, $fields);
    }

    /**
     * 获取指定账户记录By用户名
     *
     * @param  string  $username
     * @param  array  $fields
     * @return Model|null
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function infoByUsername(string $username, array $fields = []): ?Model
    {
        $where[] = ['username', '=', $username];
        return $this->findOneByWhere($where, $fields);
    }

    /**
     * 混合查找记录
     *
     * @param  string  $username  混合查询 手机号或用户名
     * @return array|Model|null
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function findByHybrid(string $username)
    {
        return $this->model->whereOr('username', $username)->whereOr('mobile', $username)->find();
    }

    /**
     * 通过微信小程序的openID查询
     *
     * @param  string  $openID
     * @return array|Model|null
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function findByOpenID(string $openID)
    {
        return $this->model->where('openid', $openID)->find();
    }

    /**
     * 通过微信小程序的unionid查询
     *
     * @param  string  $id
     * @return array|Model|null
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function findByUnionId(string $id)
    {
        if (empty($id)) {
            return null;
        }
        return $this->model->whereOr('unionid', $id)->find();
    }

    /**
     * 通过个人邀请码查询用户信息
     *
     * @param  string  $inviteCode
     * @return array|Model|null
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function findByInviteCode(string $inviteCode)
    {
        if (empty($inviteCode)) {
            return null;
        }
        return $this->model->where('invite_code', $inviteCode)->find();
    }

    /**
     * 修改密码
     *
     * @param  int  $accountId
     * @param  string  $oldPwd
     * @param  string  $newPwd
     * @return bool
     * @throws RepositoryException
     */
    public function modifyPwd(int $accountId, string $oldPwd, string $newPwd): bool
    {
        if (!$user = $this->findById($accountId)) {
            throw new RepositoryException('用户不存在');
        }

        if ($user['password'] != md5($oldPwd)) {
            throw new RepositoryException('原密码错误');
        }

        $user->password = md5($newPwd);

        return $user->save();
    }

    /**
     * 修改用户数据
     *
     * @param  int  $accountId
     * @param  array  $fieldsKV  修改内容:键值对
     * @return mixed
     * @throws RepositoryException
     */
    public function accountEditInfo(int $accountId, array $fieldsKV)
    {
        $allowFields = ['headimgurl', 'real_name', 'nickname', 'mobile', 'gender', 'province', 'city', 'county', 'birthday'];
        $fieldsKV    = arrayKeysFilter($fieldsKV, $allowFields);

        if (isset($fieldsKV['mobile']) && !empty($fieldsKV['mobile'])) {
            if (!checkMobile($fieldsKV['mobile'])) {
                throw new RepositoryException('手机号不正确');
            }
        }

        if (!$account = $this->findById($accountId)) {
            throw new RepositoryException('用户信息错误');
        }

        return $account->save($fieldsKV);
    }

    /**
     * 用户行为记录统计
     * 点赞、收藏、分享等
     * @param  string  $type
     * @param  string  $action
     * @param  int  $accountId
     * @return int
     */
    public function countRecordByAction(string $type, string $action, int $accountId = 0): int
    {
        if (!in_array($type, AccountRecord::allowTypes())) {
            return 0;
        }

        if (!in_array($action, AccountRecord::allowActions())) {
            return 0;
        }

        return AccountRecord::countByAction($type, $action, $accountId);
    }

    /**
     * 获取并处理用户列表 【后台用户列表】
     *
     * @param  array  $where
     * @param  array  $field  必传字段coin_total
     * @param  int  $page
     * @param  int  $size
     * @param  callable|null  $call
     * @return array|null
     * @throws RepositoryException
     */
    public function getAndHandleAccountList(array $where, array $field, int $page = 1, int $size = 20, callable $call = null): ?array
    {
        $items = self::findList($where, $field, $page, $size, function ($q) use ($call) {
            if ($call !== null) {
                $q = $call($q);
            }
            return $q->order('id', 'desc');
        });

        $items['list']->each(function ($item) {
            $genderText = '保密';
            if ($item->gender == 1) {
                $genderText = '男';
            }
            if ($item->gender == 2) {
                $genderText = '女';
            }
            $item->gender_text = $genderText;
        });

        return $items;
    }
}