<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2023 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件,不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace app\api\model\dealer;

use app\api\model\dealer\User as DealerUserModel;
use app\api\service\User as UserService;
use app\common\model\dealer\Withdraw as WithdrawModel;
use app\common\enum\dealer\withdraw\PayType as PayTypeEnum;
use app\common\enum\dealer\withdraw\ApplyStatus as ApplyStatusEnum;
use cores\exception\BaseException;
use yiovo\captcha\facade\CaptchaApi;
use app\api\model\user\BalanceLog;

/**
 * 分销商提现明细模型
 * Class Withdraw
 * @package app\api\model\dealer
 */
class Withdraw extends WithdrawModel
{
    /**
     * 隐藏字段
     * @var array
     */
    protected $hidden = [
        'store_id',
        'create_time',
        'update_time',
    ];

    /**
     * 获取分销商提现明细
     * @param int $applyStatus 申请状态
     * @return \think\Paginator
     * @throws BaseException
     * @throws \think\db\exception\DbException
     */
    public function getList(int $applyStatus = -1): \think\Paginator
    {
        // 当前用户ID
        $userId = UserService::getCurrentLoginUserId();
        // 构建查询对象
        $query = $this->getNewQuery();
        $applyStatus > -1 && $query->where('apply_status', '=', $applyStatus);
        // 查询列表数据
        return $query->where('user_id', '=', $userId)
            ->order(['create_time' => 'desc'])
            ->paginate(15);
    }

    /**
     * 提交申请
     * @param DealerUserModel $dealer
     * @param array $data
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function submit(DealerUserModel $dealer, array $data): bool
    {
        // 数据验证
        if (!$this->validation($dealer, $data)) {
            return false;
        }
        //手续费
        if (empty($data['is_invoice'])) {
            $commission = \app\api\model\Setting::getFinanceCommission();
            if (!empty($commission)) {
                $data['commission_price'] = bcmath($data['money'], $commission / 100, 2);
            }
        }
        // 事务处理
        $this->transaction(function () use ($dealer, $data) {
            // 新增申请记录
            $this->save(array_merge($data, [
                'user_id' => (int)$dealer['user_id'],
                'apply_status' => ApplyStatusEnum::WAIT,
                'platform' => getPlatform(),
                'store_id' => self::$storeId
            ]));
            // 新增操作记录
            BalanceLog::insert([
                'user_id' => $dealer['user_id'],
                'scene' => 50,
                'money' => -$data['money'],
                'describe' => '分销佣金提现',
                'store_id' => self::$storeId,
                'create_time' => time(),
            ]);
            // 冻结用户资金
            DealerUserModel::freezeMoney((int)$dealer['user_id'], (string)$data['money']);
        });
        return true;
    }

    /**
     * 数据验证
     * @param DealerUserModel $dealer
     * @param array $data
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    private function validation(DealerUserModel $dealer, array $data): bool
    {
        // 结算设置
        $settlement = Setting::getItem('settlement');
        // 最低提现佣金
        if (!is_numeric($data['money']) || $data['money'] <= 0) {
            $this->error = '提现金额不正确';
            return false;
        }
        if ($dealer['money'] <= 0) {
            $this->error = '当前用户没有可提现佣金';
            return false;
        }
        if ($data['money'] > $dealer['money']) {
            $this->error = '提现金额不能大于可提现佣金';
            return false;
        }
        if ($data['money'] < $settlement['min_money']) {
            $this->error = '最低提现金额为' . $settlement['min_money'];
            return false;
        }
        if (!in_array($data['pay_type'], $settlement['pay_type'])) {
            $this->error = '提现方式不正确';
            return false;
        }
        if ($data['pay_type'] == PayTypeEnum::ALIPAY) {
            if (empty($data['alipay_name']) || empty($data['alipay_account'])) {
                $this->error = '请补全提现信息';
                return false;
            }
        } elseif ($data['pay_type'] == PayTypeEnum::BANK_CARD) {
            if (empty($data['bank_name']) || empty($data['bank_account']) || empty($data['bank_card']) || empty($data['bank_user']) || empty($data['bank_phone'])) {
                $this->error = '请补全提现信息';
                return false;
            }
            // 验证短信验证码是否匹配
            try {
                CaptchaApi::checkSms($data['smsCode'], $data['bank_phone']);
            } catch (\Exception $e) {
                $this->error = $e->getMessage() ?? '短信验证码不正确';
                return false;
            }
        }
        if (!empty($data['is_invoice']) && empty($data['invoice_img_id'])) {
            $this->error = '请上传发票信息';
            return false;
        }

        return true;
    }
}