<?php

namespace app\model\project;

use app\api\service\UtilService;
use app\model\project\User as UserModel;
use think\Model;
use think\model\concern\SoftDelete;

class UserWithdrawal extends Model
{
    // 设置当前模型对应的完整数据表名称
    protected $table = 'fj_user_withdrawal';

    // 自动时间戳
    protected $autoWriteTimestamp = true;
    protected $createTime = 'createtime';
    protected $updateTime = false;

    use SoftDelete;

    protected $deleteTime = 'deletetime';

    // 提现状态常量
    const SH_STATUS_PENDING = 0; // 待审核
    const SH_STATUS_FAILED = 1;  // 审核失败
    const SH_STATUS_SUCCESS = 2; // 审核成功

    const DK_STATUS_UNPAID = 0;  // 未打款
    const DK_STATUS_PROCESSING = 1; // 打款中
    const DK_STATUS_FAILED = 2;  // 打款失败
    const DK_STATUS_PAID = 3;    // 已打款

    // 账号类型常量
    const ACCOUNT_TYPE_ALIPAY = 0; // 支付宝

    /**
     * 用户提现申请
     * @param int $userId 用户ID
     * @param float $amount 提现金额
     * @param int $accountType 账号类型
     * @param string $account 提现账号
     * @param string $realName 真实姓名
     * @param float $commissionRate 手续费率(0-1)
     * @param float $front_money 用户当前余额
     * @return array
     */
    public function applyWithdrawal($userId, $amount, $accountType, $account, $realName, $commissionRate = 0, $front_money = 0)
    {
        // 验证提现金额
        if ($amount <= 0) {
            return ['status' => false, 'msg' => '提现金额必须大于0'];
        }

        // 验证账号信息
        if (empty($account) || empty($realName)) {
            return ['status' => false, 'msg' => '提现账号和真实姓名不能为空'];
        }

        // 计算手续费和实际到账金额
        $commission = bcmul($amount, $commissionRate, 2);
        $actualAmount = bcsub($amount, $commission, 2);

        // 生成提现单号
        $withdrawalSn = UtilService::generateCompactOrderNo($userId, 'tx');

        try {
            // 开启事务
            $this->startTrans();

            // 创建提现记录
            $withdrawalId = $this->insertGetId([
                'user_id' => $userId,
                'sn' => $withdrawalSn,
                'tx_money' => $amount,
                'tx_commission' => $commission,
                'tx_sj_money' => $actualAmount,
                'sh_status' => self::SH_STATUS_PENDING,
                'dk_status' => self::DK_STATUS_UNPAID,
                'account_type' => $accountType,
                'account' => $account,
                'account_realname' => $realName,
                'createtime' => time()
            ]);

            UserModel::where(['id' => $userId, 'is_del' => 0])->dec('money', $amount)->save();

            UserMoneyLog::addUserMoneyLog($userId, '-' . $amount, $front_money, 1, '用户提现', $withdrawalId);

            // 提交事务
            $this->commit();

            return [
                'status' => true,
                'msg' => '提现申请提交成功',
                'data' => [
                    'sn' => $withdrawalSn,
                    'amount' => $amount,
                    'actual_amount' => $actualAmount,
                    'commission' => $commission
                ]
            ];
        } catch (\Exception $e) {
            // 回滚事务
            $this->rollback();
            return ['status' => false, 'msg' => '提现申请失败: ' . $e->getMessage()];
        }
    }

    //用户信息
    public function getuserdata()
    {
        return $this->belongsTo(User::class, 'user_id')
            ->field('username,mobile,id');
    }

    public function getShStatusTextAttr($value, $data)
    {
        switch ($data['sh_status']) {
            case self::SH_STATUS_FAILED:
                $statustxt = '审核失败';
                break;
            case self::SH_STATUS_SUCCESS:
                $statustxt = '审核成功';
                break;
            default:
                $statustxt = '待审核';
        }

        return $statustxt;
    }

    public function getDkStatusTextAttr($value, $data)
    {
        switch ($data['dk_status']) {
            case self::DK_STATUS_PROCESSING:
                $statustxt = '打款中';
                break;
            case self::DK_STATUS_FAILED:
                $statustxt = '打款失败';
                break;
            case self::DK_STATUS_PAID:
                $statustxt = '已打款';
                break;
            default:
                $statustxt = '等待审核';
        }

        return $statustxt;
    }

}