<?php

namespace app\repository;

use app\exception\RepositoryException;

use app\model\Account;
use app\service\Repository;
use app\traits\account\ApplyStaffTrait;
use app\traits\account\BusinessFlowTrait;
use app\traits\CommentTrait;
use app\traits\CouponBillTrait;
use app\traits\CouponTrait;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Model;

/**
 * 账户域 相关操作(客户账号)
 *
 * Class AccountRepository
 * @package app\repository
 * @method self getInstance(Model $model = null) static
 */
class AccountRepository extends Repository
{
    use CommentTrait;
    use BusinessFlowTrait;
    use CouponTrait;
    use CouponBillTrait;
    use ApplyStaffTrait;
    /**
     * 获取指定账户记录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);
    }


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

}