<?php

namespace app\common\model\user\withdrawal;

use app\common\model\BaseModel;
use app\common\model\school\activity\order\SettleLog;
use app\common\model\User;
use think\Model;


class UserwithdrawalLog extends BaseModel
{

    

    

    // 表名
    protected $name = 'user_withdrawal_log';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'status_text',
        'withdrawal_status_text',
        'type_text',
        'paytime_text',
        'examinetime_text'
    ];
    

    
    public function getStatusList()
    {
        return ['1' => __('Status 1'), '2' => __('Status 2'), '3' => __('Status 3')];
    }

    public function getWithdrawalStatusList()
    {
        return ['1' => __('Withdrawal_status 1'), '2' => __('Withdrawal_status 2'), '3' => __('Withdrawal_status 3')];
    }

    public function getTypeList()
    {
        return ['bank' => __('Type bank'), 'wechat' => __('Type wechat'), 'alipay' => __('Type alipay')];
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getWithdrawalStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['withdrawal_status']) ? $data['withdrawal_status'] : '');
        $list = $this->getWithdrawalStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['type']) ? $data['type'] : '');
        $list = $this->getTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getPaytimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['paytime']) ? $data['paytime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getExaminetimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['examinetime']) ? $data['examinetime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setPaytimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setExaminetimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }


    public function user()
    {
        return $this->belongsTo('app\common\model\User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }









    /**得到基础条件
     * @param $status
     * @param null $model
     * @param string $alisa
     */
    public static function getBaseWhere($whereData = [], $model = null, $alisa = '',$with = false)
    {

        if (!$model) {
            $model = new static;
            if ($alisa&&!$with) $model = $model->alias($alisa);
        }
        if ($alisa) $alisa = $alisa . '.';
        $tableFields = (new static)->getTableFields();
        foreach ($tableFields as $fields)
        {
            if(in_array($fields, ['status',"withdrawal_status",'user_id']))continue;
//            if (isset($whereData[$fields]) && $whereData[$fields]) $model = $model->where("{$alisa}{$fields}", '=', $whereData[$fields]);

            if (isset($whereData[$fields]) && $whereData[$fields]){
                if(is_array($whereData[$fields])){
                    $model = $model->where("{$alisa}{$fields}", $whereData[$fields][0], $whereData[$fields][1]);
                }else{
                    $model = $model->where("{$alisa}{$fields}", '=', $whereData[$fields]);
                }
            }

        }
        if (isset($whereData['status'])) $model = $model->where("{$alisa}status", 'in', $whereData['status']);
        if (isset($whereData['not_status'])) $model = $model->where("{$alisa}status", 'not in', $whereData['not_status']);

        if (isset($whereData['withdrawal_status']) && $whereData['withdrawal_status']!=="") $model = $model->where("{$alisa}withdrawal_status", 'in', $whereData['withdrawal_status']);
        if (isset($whereData['not_withdrawal_status'])&&  $whereData['not_withdrawal_status']!=="") $model = $model->where("{$alisa}withdrawal_status", 'not in', $whereData['not_withdrawal_status']);

        if (isset($whereData['keywords'])&&$whereData['keywords']){
            $model = $model->where("{$alisa}reason|{$alisa}bank_name|{$alisa}bank_user_name|user.nickname|user.realname|user.mobile", 'LIKE', "%{$whereData['keywords']}%" );
        }
        if (isset($whereData['time'])&&$whereData['time']){

            $model = $model->time(["{$alisa}createtime",$whereData['time']]);
        }
        if (isset($whereData['user_id']) && $whereData['user_id']) $model = $model->where("{$alisa}user_id", '=', $whereData['user_id']);


        return $model;
    }






    public static function allList($user_id,$page, $limit,$keywords,$status,$withdrawal_status="",$params=[]){
        $with_field = [
            'user'=>['nickname','mobile','avatar','realname'],
            'base'=>['*'],
        ];
        $alisa = (new self)->getWithAlisaName();
        $sort = "{$alisa}.id desc";
        $serch_where = ['status'=>$status,'user_id'=>$user_id,'keywords'=>$keywords,"withdrawal_status"=>$withdrawal_status];
//        if($type)$serch_where['type'] = $type;
        return (new self)->getBaseList(array_merge($serch_where,$params), $page, $limit,$sort,$with_field);
    }




    /** 对近期结算金额发起提现申请
     * @param $user_id
     * @param $trans
     * @return true
     * @throws \Exception
     */
    public function initiateWithdrawal($user_id,$type="bank",$trans=false){

         //判断逻辑
        if($trans){
            self::beginTrans();
        }
        try{

            //实际可提现金额
            $user_info = User::get($user_id);
            if(!$user_info) throw new \Exception(__('User not exist'));
            //统计已入账待提现金额
            $real_price = SettleLog::where("to_user_id",$user_id)->where("status",'2')->lock(true)->sum("settle_price");
            //小于0.01 不提现
            if($real_price<0.01)throw new \Exception("无可提现金额");
            //计算被扣除的手续费
            $fee_price = SettleLog::where("to_user_id",$user_id)->where("status",'2')->lock(true)->sum("fee_price");
            //提现额 = 实际可提现金额 + 手续费
            $price = bcadd($real_price,$fee_price,2);
            $status = '1';

            $min_price  = config("site.withdrawal_min");
            if( $real_price < $min_price)throw new \Exception("最低提现金额为".$min_price);


            //查询是否有提现银行卡信息
            $userWithdrawal = Userwithdrawal::where('user_id',$user_id)->find();
            if(!$userWithdrawal) throw new \Exception("请先去绑定提现银行卡");
            //组装提交数据
            $data = [
                'user_id'=>$user_id,
                'price'=>$price,
                "fee_price" => $fee_price,
                'real_price' => $real_price,
                'type'=>$type,
                'status'=>$status,
                'withdrawal_status'=>'1',
                'name'=>$userWithdrawal['name' ],
                'bank_name'=>$userWithdrawal['bank_name' ],
                'bank_user_name'=>$userWithdrawal['bank_user_name' ],
                'id_number'=>$userWithdrawal['id_number' ],
            ];




            //插入提现数据
            $res = self::create($data);

            //更新结算记录
            SettleLog::where("to_user_id",$user_id)
                ->where("status",'2')
                ->update([
                    'status'=>'3',
                    'withdrawal_log_id'=>$res['id'],
                    'settletime'=>time(),
                ]);

            //调用体现申请事件
            $userwithdrawalLog = self::where('id',$res['id'])->find();

            $data = ['userwithdrawalLog' =>$userwithdrawalLog];
            \think\Hook::listen('user_withdrawal_auth_need_after', $data);

            if($trans){
                self::commitTrans();
            }
        }catch (\Exception $e){
            if($trans){
                self::rollbackTrans();
            }
            throw new \Exception($e->getMessage().$e->getFile().$e->getLine());
        }
        return $res;
    }


    /** 提现审核
     * @param $id
     * @param $status 状态:1=待审核,2=审核通过,3=审核不通过
     * @param $reason 审核不通过原因
     * @param $trans
     * @return true
     * @throws \Exception
     */
    public function withdrawalReview($id,$status,$reason="",$trans=false){

        //找到需要审核的提现记录
        $userwithdrawalLog = self::where('id',$id)->where('status',"=",'1')->find();
        if(!$userwithdrawalLog) throw new \Exception("提现记录不存在");
        if($userwithdrawalLog['status']!='1') throw new \Exception("已经审核的提现记录不能再审核");

        if(!in_array($status,['2','3'])) throw new \Exception("审核状态错误");
        //不通过需要理由
        if($status=='3' && !$reason) throw new \Exception("审核不通过原因不能为空");
//判断逻辑
        if($trans){
            self::beginTrans();
        }
        $res = true;
        try{

            if($status=='2'){
                //审核通过
                //更新状态
                $userwithdrawalLog["status"] = '2';
                $userwithdrawalLog["withdrawal_status"] = '2';
                $userwithdrawalLog["examinetime"] = time();
                $userwithdrawalLog->save();
                //调用事件

                $data = ['userwithdrawalLog' =>$userwithdrawalLog];
                \think\Hook::listen('user_withdrawal_auth_success_after', $data);

            }else{
                //审核不通过
                //更新状态
                $userwithdrawalLog["status"] = '3';
                $userwithdrawalLog["reason"] = $reason;
                $userwithdrawalLog["examinetime"] = time();
                $userwithdrawalLog->save();
                //更新结算记录，回退结算状态
                SettleLog::where('withdrawal_log_id',$id)->update([
                    'status'=>'2',
                    'withdrawal_log_id'=>0,
                    'settletime'=>null,
                ]);
                //调用事件
                $data = ['userwithdrawalLog' =>$userwithdrawalLog];
                \think\Hook::listen('user_withdrawal_auth_fail_after', $data);

            }





            if($trans){
                self::commitTrans();
            }
        }catch (\Exception $e){
            if($trans){
                self::rollbackTrans();
            }
            throw new \Exception($e->getMessage().$e->getFile().$e->getLine());
        }
        return $userwithdrawalLog;
    }




    /** 设置已打款
     * @param $id
     * @param $remark 打款备注
     * @param $trans
     * @return true
     * @throws \Exception
     */
    public function paidAlready($id,$real_have_price,$remark="",$trans=false){

        //找到需要审核的提现记录
        $userwithdrawalLog = self::where('id',$id)
            ->where('status',"=",'2')
            ->where('withdrawal_status',"=",'2')
            ->find();
        if(!$userwithdrawalLog) throw new \Exception("提现记录不存在");
        if($userwithdrawalLog['status']!='2') throw new \Exception("审核通过的订单才能标记打款");
        if(!$remark) throw new \Exception("打款备注不能为空");
        if($real_have_price <= 0) throw new \Exception("请输入正确的打款金额");
        if($real_have_price > $userwithdrawalLog['price']) throw new \Exception("打款金额不能大于提现金额");

        //提现金额 - 实际到账金额 = 实际的手续费
        $real_fee_price = bcsub($userwithdrawalLog['price'],$real_have_price,2);

//判断逻辑
        if($trans){
            self::beginTrans();
        }
        $res = true;
        try{
                //更新状态
                $userwithdrawalLog["withdrawal_status"] = '3';
                $userwithdrawalLog["paytime"] = time();
                $userwithdrawalLog["real_fee_price"] = $real_fee_price;
                $userwithdrawalLog["real_have_price"] = $real_have_price;


                $userwithdrawalLog["remark"] = $remark;
                $userwithdrawalLog->save();
                //调用事件
                $data = ['userwithdrawalLog' =>$userwithdrawalLog];
                \think\Hook::listen('user_withdrawal_success_after', $data);


            if($trans){
                self::commitTrans();
            }
        }catch (\Exception $e){
            if($trans){
                self::rollbackTrans();
            }
            throw new \Exception($e->getMessage().$e->getFile().$e->getLine());
        }
        return $userwithdrawalLog;
    }



}
