<?php
/*
 本代码由 焕岱科技 创建
 技术支持 WX：15285007200
 严禁反编译、逆向等任何形式的侵权行为，违者将追究法律责任
*/

namespace app\api\controller\user;

use app\api\controller\Base;
use think\Db;


class Withdrawal extends Base
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];
    
    public $model = null;
    public function _initialize(){
        parent::_initialize();
        $this->model = new \app\common\model\bbfxshop\User;
    }

    public function list(){
        global $_W;
        $params = $this->param();
        
        $base = $_W['base'];
        
        $withdrawal_type = max(1,intval($params['withdrawal_type']));
        
        $list = Db::name("bbfx_withdrawal_log")->where(["uniacid"=>UNIACID,"user_id"=>$this->user['id'],'withdrawal_type'=>$withdrawal_type])->field("info",true)->order("id desc")->select();
        foreach ($list as &$val){
            $val['createtime'] = date("Y-m-d H:i:s",$val['createtime']);
        }
        unset($val);
        
        $title = $base['fenxiao']['texts']['withdrawal_log'];
        
        __success("success",array("list"=>$list,"title"=>$title));
    }
     
    public function submit(){
        global $_W;
        $params = $this->param();
        $user = $this->user;
        $this->model->checkStatus($user);
        $base = $_W['base']; 
        $fenxiao = $base['fenxiao'];
        
        $withdrawal_type = max(1,intval($params['withdrawal_type']));
        $money = round($params['money'],2);
        $type = intval($params['type']);

        $this->model->checkTxdateLimit($withdrawal_type);
        
        $result = $this->model->checkPayPassword($user['id'],$params['pay_password']);
        if($result['code'] != 1){
            __result($result);
        }
        
        if($money <= 0 || empty($money)){
            __error("请输入大于0的金额");
        }
        
        if(!$type){
            __error("请选择提现方式");
        }
        
        if($withdrawal_type == 3){
            if($base['withdrawal']['score'] != 1){
                __error("该提现未开启");
            }
            if(!in_array($type,$base['withdrawal']['score_type'])){
                __error("该提现方式未开启");
            }
        }
        else if($withdrawal_type == 1){
            if($base['withdrawal']['balance'] != 1){
                __error("该提现未开启");
            }
            if(!in_array($type,$base['withdrawal']['balance_type'])){
                __error("该提现方式未开启");
            }
        }
        else if($withdrawal_type == 5){
            if($base['dynamic_redpacket']['status'] != 1){
                __error("该提现未开启");
            }
            // if(!in_array($type,$base['withdrawal']['balance_type'])){
            //     __error("该提现方式未开启");
            // }
        }
        else if($withdrawal_type == 6){
            if($base['deposit_release']['status'] != 1 || $base['deposit_release']['withdrawal']['status'] != 1){
                __error("该提现未开启");
            }
            if(!in_array($type,$base['deposit_release']['withdrawal']['type'])){
                __error("该提现方式未开启");
            }
            
            $unfreeze_day = intval($base['deposit_release']['withdrawal']['unfreeze_day']);
            if($unfreeze_day > 0){
                $ctime = time() - $unfreeze_day * 24 * 60 * 60;
                $deposit_money_total = Db::name("bbfx_money_log")->where(['uniacid'=>UNIACID,'type'=>6,'money'=>['>',0],'item_type'=>['in',[4,32]],'createtime'=>['>',$ctime]])->sum("money");
                
                $deposit_money_use = Db::name("bbfx_money_log")->where(['uniacid'=>UNIACID,'type'=>6,'money'=>['<',0],'item_type'=>['not in',[5,6]],'createtime'=>['>',$ctime]])->sum("money");
                
                
                $deposit_money_total += $deposit_money_use;
                
                
                $deposit_money = $user['deposit_money'] - $deposit_money_total;
                
                if($deposit_money < 0){
                    $deposit_money = 0;
                }
                
                if($deposit_money < $money){
                    
                    if($user['deposit_money'] > $deposit_money_total){
                        $freeze_money = $deposit_money_total;
                    }
                    else{
                        $freeze_money = $user['deposit_money'];
                    }
                    
                    __error("您有{$freeze_money}元处于冻结中，请解冻后再来提现！");
                }
            }
        }
        else if($withdrawal_type == 9){
            if($base['contribute_vadded']['withdrawal']['status'] != 1){
                __error("该提现未开启");
            }
        }
        else{
            __error("提现类型错误");
        }
        $withdrawal_info = [];
        if($type == 3){
            if(!$params['realname']){
                __error("请填写姓名");
            }
            if(!$params['alipay']){
                __error("请填写支付宝账号");
            }
            if($params['alipay'] != $params['realipay']){
                __error("两次输入的账号不一致");
            }
            
            $data = array(
                "realname"=>$params['realname'],
                "alipay"=>$params['alipay']
            );
            
            $withdrawal_info['zfb_realname'] = $params['realname'];
            $withdrawal_info['zfb'] = $params['alipay'];
        }
        else if($type == 4){
            $dg_status = Db::name("platform")->where(['id'=>UNIACID])->value("dg_status");
            if($dg_status == 1){
                $txaccount = Db::name("bbfx_user_txaccount")->where(['uniacid'=>UNIACID,'user_id'=>$this->user['id']])->find();
                if(!empty($txaccount)){
                    if($txaccount['qx_status'] != 1){
                        __error("您的提现账户有误，请重新完善");
                    }
                    $data = array(
                        "realname"=>$txaccount['name'],
                        "bankname"=>$txaccount['bankname'],
                        "bankopen"=>$txaccount['bankopen'],
                        "bankcard"=>$txaccount['card_no'],
                        "info"=>iserializer($txaccount)
                    );
                    $data['info'] = iserializer($txaccount);
                }
                else{
                    __error("请先完善提现账户");
                }
            }
            else{
                if(!$params['realname']){
                    __error("请填写姓名");
                }
                if(!$params['bankname']){
                    __error("请选择银行");
                }
                if(!$params['bankopen']){
                    __error("请填写开户行支行");
                }
                if(!$params['bankcard']){
                    __error("请填写银行卡号");
                }
                if($params['bankcard'] != $params['rebankcard']){
                    __error("两次输入的卡号不一致");
                }
                
                $data = array(
                    "realname"=>$params['realname'],
                    "bankname"=>$params['bankname'],
                    "bankopen"=>$params['bankopen'],
                    "bankcard"=>$params['bankcard']
                );

                $withdrawal_info['bank_realname'] = $params['realname'];
                $withdrawal_info['bankname'] = $params['bankname'];
                $withdrawal_info['bankopen'] = $params['bankopen'];
                $withdrawal_info['bankcard'] = $params['bankcard'];

                if(empty($user['bankcard'])){
                    $udata = [
                        'bank_realname'=>$params['realname'],
                        'bankname'=>$params['bankname'],
                        'bankcard'=>$params['bankcard'],
                        'bankopen'=>$params['bankopen'],
                    ];
                    Db::name("bbfx_user")->where(['id'=>$user['id']])->update($udata);
                }
            }
        }
        else if($type == 5){
            if(!$params['skqrcode']){
                __error("请上传收款码");
            }
            
            $data = array(
                "skqrcode"=>$params['skqrcode'],
            );
            
        }
        else if($type == 1 || $type == 2){
            if($money >= 2000 &&  $type == 2){
                if(!$params['realname']){
                    __error("请填写姓名");
                }
                $data = array(
                    "realname"=>$params['realname']
                );
                $withdrawal_info['realname'] = $params['realname'];
            }
        }
        else{
            __error("提现方式错误");
        }
        
        $openid = $this->param("openid/s");
        $platform = $this->param("platform/s");
        if($type == 2){
            if(empty($openid)){
                __error("openid缺失，无法提现到微信零钱");
            }
            $data['openid'] = $openid;
        }
        
        $data['openid'] = $openid;
        $data['platform'] = $platform;
        
        $data['type'] = $type;
        
        
        $unit = $fenxiao['texts']['yuan'];
        $integer = 0;
        $fixed_service_charge = 0;
        if($withdrawal_type == 3){
            $unit = $base['texts']['score_unit'];
            
            $withdrawal_limit = max(0,floatval($base['withdrawal']['min_score']));
            $max_withdrawal = floatval($base['withdrawal']['max_score']);
            
            $service_charge_rate = floatval($base['withdrawal']['score_service_charge']);
            
            $withdrawal_score_ratio = floatval($base['withdrawal']['withdrawal_score_ratio']);
            $withdrawal_score_ratio = max(1,$withdrawal_score_ratio);
            
            $realscore = floatval($money / $withdrawal_score_ratio);
            
            $service_charge = max(0,$realscore * ($service_charge_rate / 100));
            
            $fixed_service_charge = max(0,floatval($base['withdrawal']['score_fixed_service_charge']));
            
            
            $integer = intval($base['withdrawal']['score_integer']);
        }
        else if($withdrawal_type == 1){
            $unit = $base['texts']['balance_unit'];
            $withdrawal_limit = max(0,floatval($base['withdrawal']['min_balance']));
            $max_withdrawal = floatval($base['withdrawal']['max_balance']);
            
            $service_charge_rate = floatval($base['withdrawal']['balance_service_charge']);
            $service_charge = max(0,$money * ($service_charge_rate / 100));
            $fixed_service_charge = max(0,floatval($base['withdrawal']['balance_fixed_service_charge']));
            
            $integer = intval($base['withdrawal']['balance_integer']);
        }
        else if($withdrawal_type == 5){
            $unit = "元";
            $withdrawal_limit = max(0,floatval($base['withdrawal']['min_score']));
            $max_withdrawal = floatval($base['withdrawal']['max_score']);
            
            $service_charge_rate = floatval($base['withdrawal']['score_service_charge']);
            $service_charge = max(0,$money * ($service_charge_rate / 100));
            $fixed_service_charge = max(0,floatval($base['withdrawal']['score_fixed_service_charge']));
            
            $integer = intval($base['withdrawal']['score_integer']);
        }
        else if($withdrawal_type == 6){
            $unit = $base['texts']['balance_unit'];
            $withdrawal_limit = max(0,floatval($base['deposit_release']['withdrawal']['min']));
            $max_withdrawal = floatval($base['deposit_release']['withdrawal']['max']);
            
            $service_charge_rate = floatval($base['deposit_release']['withdrawal']['service_charge']);
            $service_charge = max(0,$money * ($service_charge_rate / 100));
            
            
            $integer = intval($base['deposit_release']['withdrawal']['integer_multiple']);
            
        }
        else if($withdrawal_type == 9){
            $unit = $base['texts']['balance_unit'];
            $withdrawal_limit = max(0,floatval($base['contribute_vadded']['withdrawal']['min']));
            $max_withdrawal = floatval($base['contribute_vadded']['withdrawal']['max']);
            
            $service_charge_rate = floatval($base['contribute_vadded']['withdrawal']['service_charge']);
            $fixed_service_charge = max(0,floatval($base['contribute_vadded']['withdrawal']['fixed_service_charge']));
            $service_charge = max(0,$money * ($service_charge_rate / 100));
            
            
            $integer = intval($base['contribute_vadded']['withdrawal']['integer_multiple']);
        }
        else{
            __error("提现类型错误");
        }

        $service_charge += $fixed_service_charge;

        $realmoney = $money - $service_charge;
        if($realmoney <= 0){
            __error("提现金额不足扣除手续费");
        }
        
        if($money < $withdrawal_limit){
            __error("最低提现".$withdrawal_limit.$unit);
        }
        
        if($max_withdrawal > 0 && $money > $max_withdrawal){
            __error("最高提现".$max_withdrawal.$unit);
        }
        
        if($integer > 0){
            if($money % $integer != 0){
                __error("请输入{$integer}的倍数提现");
            }
        }
        
        $currency = 0;
        if($withdrawal_type == 3){
            $currency = floatval($user['score']);
        }
        else if($withdrawal_type == 1){
            $currency = floatval($user['balance']);
        }
        else if($withdrawal_type == 5){
            $currency = floatval($user['redpacket_money']);
        }
        else if($withdrawal_type == 6){
            $currency = floatval($user['deposit_money']);
        }
        else if($withdrawal_type == 9){
            $currency = floatval($user['contribute_vadded']);
        }
        
        if($currency < $money){
            $bb = $fenxiao['texts']['commission'];
            if($withdrawal_type == 3){
                $bb = $base['texts']['score'];
            }
            else if($withdrawal_type == 1){
                $bb = $base['texts']['balance'];
            }
            else if($withdrawal_type == 5){
                $bb = "红包金额";
            }
            else if($withdrawal_type == 6){
                $bb = $base['fenxiao']['texts']['predeposit'];
            }
            else if($withdrawal_type == 9){
                $bb = $fenxiao['texts']['contribute_vadded_score'];
            }
            __error($bb."不足");
        }
        
        
        $max_money = round($realmoney + $service_charge,2);
        $data['withdrawal_type'] = $withdrawal_type;
        $data['service_charge'] = $service_charge;
        $data['realmoney'] = $realmoney;
        $data['money'] = $money;
        $data['user_id'] = $user['id']; 
        $data['uniacid'] = UNIACID;
        $data['withdrawal_no'] = date('YmdHis').random(8,true);  
        $data['createtime'] = time();
        // __error("请选择提现方式666");
        try {
            Db::startTrans();
            
            $user = Db::name("bbfx_user")->lock(true)->where(['id'=>$user['id']])->find();
            if($withdrawal_type == 9){
                $ContributeVadded_result = \app\common\model\bbfxshop\ContributeVadded::latestData();
                if(empty($ContributeVadded_result)){
                    throw new \Exception($fenxiao['texts']['contribute_vadded_score']."信息错误");
                }
                $current_price = floatval($ContributeVadded_result['current_price']);
                $data['contribute_vadded'] = $money;
                $new_money = round($money * $current_price,6);
                if($new_money < 0){
                    throw new \Exception($fenxiao['texts']['contribute_vadded_score']."价格错误");
                }
                $service_charge = max(0,$new_money * ($service_charge_rate / 100)) + $fixed_service_charge;
                $realmoney = $new_money - $service_charge;
                if($realmoney <= 0){
                    throw new \Exception("提现金额不足扣除手续费");
                }
                $data['service_charge'] = $service_charge;
                $data['realmoney'] = $realmoney;
                $data['money'] = $new_money;
            }


            $id = Db::name("bbfx_withdrawal_log")->insertGetId($data);
            if(empty($id)){
                throw new \Exception("提现失败1");
            }
            
            $data['id'] = $id;
            $log = $data;
            if($withdrawal_type == 1){
                $res = $this->model->setUserMoney($user['id'],0-$money,1,5,"余额提现",$data);
            }
            else if($withdrawal_type == 2){
                $res = \app\common\model\bbfxshop\FenxiaoJiesuan::setUserCommission($user['id'],0-$money,20,"佣金提现",$data);
            }
            else if($withdrawal_type == 3){
                $res = $this->model->setUserMoney($user['id'],0-$money,2,5,"积分提现",$data);
            }
            else if($withdrawal_type == 5){
                $res = $this->model->setUserMoney($user['id'],0-$money,5,5,"红包提现",$data);
            }
            else if($withdrawal_type == 6){
                $res = $this->model->setUserMoney($user['id'],0-$money,6,5,$fenxiao['texts']['predeposit']."提现",$data);
            }
            else if($withdrawal_type == 9){
                $res = $this->model->setUserMoney($user['id'],0-$money,15,5,$fenxiao['texts']['contribute_vadded_score']."提现",$data);
                if($res){
                    $res = \app\common\model\bbfxshop\ContributeVadded::setContribute(0-$data['money'],$user['id'],100001,"提现扣除",$data);
                }
            }
            
            if(empty($res)){
                throw new \Exception("提现失败");
            }
            
            // 积分提现 提现到余额免审
            if($base['withdrawal']['score_withdrawal_balance_check'] == 1 && $type == 1 && $withdrawal_type == 3){
                $res = $this->model->setUserMoney($data['user_id'],$data['realmoney'],1,5,"积分提现打款",$data);;
                if($res){
                    Db::name("bbfx_withdrawal_log")->where(['id'=>$id])->update(['status'=>1,'paytime'=>time()]);
                    \app\common\model\bbfxshop\UserTixian::sendNotice($log['id']);
                }
            }
            if($base['deposit_release']['withdrawal']['withdrawal_balance_check'] == 1 && $type == 1 && $withdrawal_type == 6){
                $res = $this->model->setUserMoney($data['user_id'],$data['realmoney'],1,5,$fenxiao['texts']['predeposit']."提现打款",$data);
                if($res){
                    Db::name("bbfx_withdrawal_log")->where(['id'=>$id])->update(['status'=>1,'paytime'=>time()]);
                    \app\common\model\bbfxshop\UserTixian::sendNotice($log['id']);
                }
            }

            // 余额提现、积分提现 提现到微信零钱免审
            
            $check_max1 = round($base['withdrawal']['balance_wx_check_max'],2);
            $check_max3 = round($base['withdrawal']['score_wx_check_max'],2);
            if(($base['withdrawal']['balance_wx_check'] == 1 && $type == 2 && $withdrawal_type == 1 && ($check_max1 <= 0 || ($check_max1 > 0 && $check_max1 >= $max_money))) || ($base['withdrawal']['score_wx_check'] == 1 && $type == 2 && $withdrawal_type == 3 && ($check_max3 <= 0 || ($check_max3 > 0 && $check_max3 >= $max_money)))){
                $out_batch_no = $log['out_batch_no'];
                if(empty($out_batch_no)){
                    $out_batch_no = date("YmdHis").random(8,true);
                    Db::name("bbfx_withdrawal_log")->where(['id'=>$log['id']])->update(['out_batch_no'=>$out_batch_no]);
                }
                
                $udata = [];
                if($base['is_merch_transfer_new'] == 1){
                    $res = \app\common\model\bbfxshop\Wxpay::newTransfer($openid,$log['realmoney'],$out_batch_no,$log['realname'],"余额提现",$platform);
                    if($res['code'] == 1){
                        $udata = [
                            'batch_id'=>$res['data']['transfer_bill_no']
                        ];
                        if(!empty($res['data']['package_info'])){
                            $udata['package_info'] = $res['data']['package_info'];
                        }
                        $udata['is_confirm'] = 0;
                        $udata['status'] = 1;
                        $udata['paytime'] = time();
                    }
                    
                }
                else{
                    $res = \app\common\model\bbfxshop\Wxpay::transfer($openid,$log['realmoney'],$out_batch_no,$log['withdrawal_no'],$log['realname'],"余额提现",$platform);
                    if($res['code'] == 1){
                        $udata['batch_id'] = $res['data']['batch_id'];
                        $udata['status'] = 1;
                        $udata['paytime'] = time();
                    }
                    
                }

                if($res['code'] == 1 && !empty($udata)){
                    Db::name("bbfx_withdrawal_log")->where(['out_batch_no'=>$out_batch_no,'uniacid'=>UNIACID])->update($udata);
                    \app\common\model\bbfxshop\UserTixian::sendNotice($log['id']);
                }
                
            }
            
            Db::commit();
        } 
        catch (\Exception $e) {
            Db::rollback();
        	$msg = $e->getMessage();
        	__error($msg);
        }
        
        if(!empty($withdrawal_info)){
            Db::name("bbfx_user")->where(['id'=>$user['id']])->update($withdrawal_info);
        }
        
        $log = Db::name("bbfx_withdrawal_log")->where(['id'=>$id])->find();
        \app\common\model\bbfxshop\Sms::sendWithdrawalNotice($log);
        
        __success("提交成功，请等待审核");
        
    }
    
    public function confirm(){
        $withdrawal_no = $this->param("withdrawal_no/s");
        $log = Db::name("bbfx_withdrawal_log")->where(["uniacid"=>UNIACID,"user_id"=>$this->user['id'],'withdrawal_no'=>$withdrawal_no])->find();
        if(empty($log)){
            __error("未查询到提现记录");
        }
        if($log['type'] != 2){
            __error("提现类型错误");
        }
        if($log['status'] != 1){
            __error("提现未审核通过");
        }
        
        if($log['is_confirm'] == -1){
            __error("不是新版商家转账到零钱");
        }
        if($log['is_confirm'] == 1){
            __error("已确认收款");
        }

        $openid = $this->param("openid/s");
        $platform = $this->param("platform/s");
        if(!empty($log['platform']) && $log['platform'] != $platform){
            if($log['platform'] == 'GZH'){
                __error("请在公众号网页端确认收款");
            }
            else{
                __error("请在小程序端确认收款");
            }
        }
        
        $result = \app\common\model\bbfxshop\Wxpay::queryNewTransfer($log['out_batch_no'],$platform);
        if($result['code'] != 1){
            if($result['message'] == '记录不存在'){
                $result['message'] = '记录已过期或不存在';
            }
            __result($result);
        }
        
        $state = $result['data']['state'];
        if($state == 'SUCCESS'){
            Db::name("bbfx_withdrawal_log")->where(['id'=>$log['id']])->update(['is_confirm'=>1,'confirmtime'=>time()]);
            
            __success("操作成功");
        }
        
        __error("您还未确认收款成功");
    }
    
    public function queryWaitInfo(){
        $withdrawal_no = $this->param("withdrawal_no/s");
        $log = Db::name("bbfx_withdrawal_log")->where(["uniacid"=>UNIACID,"user_id"=>$this->user['id'],'withdrawal_no'=>$withdrawal_no])->find();
        if(empty($log)){
            __error("未查询到提现记录");
        }
        
        // __error("未查询到提现记录");
        if($log['type'] != 2){
            __error(-2,"提现类型错误");
        }
        if($log['status'] != 1){
            __error(-2,"提现未审核通过");
        }
        if($log['is_confirm'] == 1){
            __error(-2,"已确认收款");
        }

        $openid = $this->param("openid/s");
        $platform = $this->param("platform/s");
        if(!empty($log['platform']) && $log['platform'] != $platform){
            if($log['platform'] == 'GZH'){
                __error("请在公众号网页端确认收款");
            }
            else{
                __error("请在小程序端确认收款");
            }
        }
        
        $result = \app\common\model\bbfxshop\Wxpay::queryNewTransfer($log['out_batch_no'],$platform);
        if($result['code'] != 1){
            if($result['message'] == '记录不存在'){
                $result['message'] = '记录已过期或不存在';
            }
            __result($result);
        }
        
        $state = $result['data']['state'];
        
        if($state == 'SUCCESS'){
            Db::name("bbfx_withdrawal_log")->where(['id'=>$log['id']])->update(['is_confirm'=>1,'confirmtime'=>time()]);
            __error(-2,"您已收款成功");
        }
        
        
        if($state != 'WAIT_USER_CONFIRM' && $state != 'TRANSFERING'){
            
            $out_batch_no = date("YmdHis").random(8,true);
            Db::name("bbfx_withdrawal_log")->where(['id'=>$log['id']])->update(['out_batch_no'=>$out_batch_no]);
            $log['out_batch_no'] = $out_batch_no;
            $transfer_remark = "余额提现";
            $remarks = ['1'=>'余额提现','2'=>'佣金提现','3'=>'积分提现','5'=>'红包提现','6'=>'预存款提现','7'=>'商户提现'];
            $transfer_remark = $remarks[$log['withdrawal_type']];
            
            $res = \app\common\model\bbfxshop\Wxpay::newTransfer($openid,$log['realmoney'],$out_batch_no,$log['realname'],$transfer_remark,$platform);
            if($res['code'] != 1){
                __result($res);
            }
            
            $data = [
                'batch_id'=>$res['data']['transfer_bill_no'],
                'package_info'=>''
            ];
            if(!empty($res['data']['package_info'])){
                $data['package_info'] = $res['data']['package_info'];
                $log['package_info'] = $res['data']['package_info'];
            }
            
            Db::name("bbfx_withdrawal_log")->where(['id'=>$log['id']])->update($data);
            
        }
        
        
        $set = \app\common\model\bbfxshop\Wxpay::getSet($platform);
        
        $result = [
            "mchId"=>$set['mchid'],
            "appId"=>$set['appid'],
            "package"=>$log['package_info'],
        ];
        
        __success("操作成功",$result);
    }
}