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

namespace app\api\controller\fenxiao;

use app\api\controller\Base;
use think\Db;
use app\common\model\bbfxshop\User;


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

    public function list(){
        global $_W;
        $params = $this->param();
        
        $base = $_W['base'];
        
        $list = Db::name("bbfx_withdrawal_log")->where(["uniacid"=>UNIACID,"user_id"=>$this->user['id'],'withdrawal_type'=>2])->field("info",true)->order('createtime 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;
        User::checkStatus($user);
        User::checkTxdateLimit(2);
        $set = $_W['base'];
        $fenxiao = $set['fenxiao'];
        
        $money = round($params['money'],2);
        
        $result = User::checkPayPassword($user['id'],$params['pay_password']);
        if($result['code'] != 1){
            __result($result);
        }
        
        if($money <= 0 || empty($money)){
            __error("请输入大于0的金额");
        }
        $type = intval($params['type']);
        if(!$type){
            __error("请选择提现方式");
        }
        
        if(!in_array($type,$fenxiao['withdrawal_type'])){
            __error("该提现方式未开启");
        }
        
        if($fenxiao['is_withdrawal_limit'] == 1){
            // 商品激活提现
            if($user['is_tixian_activate'] == 0){
                if(empty($fenxiao['withdrawal_unlimit_buygoods'])){
                    __error("您的提现还未激活，请购买激活商品激活。");
                }
                else{
                    $goods = Db::name("bbfx_goods")->where(['uniacid'=>UNIACID,'status'=>1,'id'=>['in',$fenxiao['withdrawal_unlimit_buygoods']]])->order("price asc")->field("id,title")->find();
                    if(empty($goods)){
                        __error("您的提现还未激活，请购买激活商品激活。");
                    }
                    __error("提现未激活，请购买【".$goods['title']."】激活提现。");
                }
            }
        }
        else if($fenxiao['is_withdrawal_limit'] == 2){
            // 消费复购金、积分激活
            $score = Db::name("bbfx_money_log")->where(['uniacid'=>UNIACID,'type'=>2,'item_type'=>['not in',[3]],'user_id'=>$this->user['id'],'money'=>['<',0]])->sum("money");
            $score_refund = Db::name("bbfx_money_log")->where(['uniacid'=>UNIACID,'type'=>2,'item_type'=>['in',[4]],'user_id'=>$this->user['id'],'money'=>['>',0]])->sum("money");
            $score = abs($score) - $score_refund;
            $score = max(0,round($score,2));
            
            
            $repurchase_currency = Db::name("bbfx_money_log")->where(['uniacid'=>UNIACID,'type'=>4,'user_id'=>$this->user['id'],'money'=>['<',0]])->sum("money");
            $repurchase_currency_refund = Db::name("bbfx_money_log")->where(['uniacid'=>UNIACID,'type'=>4,'item_type'=>4,'user_id'=>$this->user['id'],'money'=>['>',0]])->sum("money");
            $repurchase_currency = abs($repurchase_currency) - $repurchase_currency_refund;
            $repurchase_currency = max(0,round($repurchase_currency,2));
            
            // 最多可累计提现佣金
            $withdrawal_ok = round($repurchase_currency + $score,2);
            
            $withdrawal_total = Db::name("bbfx_withdrawal_log")->where(['uniacid'=>UNIACID,'user_id'=>$this->user['id'],'withdrawal_type'=>2,'status'=>['in',[0,1]]])->sum("money");
            // print_r($repurchase_currency);die;
            if($withdrawal_ok < ($withdrawal_total + $money)){
                $min = max(0,$withdrawal_ok - $withdrawal_total);
                if($min == 0){
                    __error("提现未激活，请消费积分或复购金激活提升可提现金额。");
                }
                else{
                    __error("您最多可提现￥{$min}，可消费积分或复购金提升可提现金额。");
                }
            }
        }
        
        $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 == 1 || $type == 2 || $type == 6){
            if($money >= 2000 &&  $type == 2){
                if(!$params['realname']){
                    __error("请填写姓名");
                }
                $data = array(
                    "realname"=>$params['realname']
                );
                $withdrawal_info['realname'] = $params['realname'];
            }
        }
        else if($type == 5){
            if(!$params['skqrcode']){
                __error("请上传收款码");
            }
            $data = array(
                "skqrcode"=>replaceSiteroot($params['skqrcode'])
            );
            $withdrawal_info['skqrcode'] = replaceSiteroot($params['skqrcode']);
        }
        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;
        $withdrawal_limit = max(0,floatval($fenxiao['withdrawal_limit']));
        $max_withdrawal = floatval($fenxiao['max_withdrawal']);
        if($money < $withdrawal_limit){
            __error("最低提现".$withdrawal_limit.$fenxiao['texts']['yuan']);
        }
        if($max_withdrawal > 0 && $money > $max_withdrawal){
            __error("最高提现".$max_withdrawal.$fenxiao['texts']['yuan']);
        }
        
        if($user['commission_ok'] < $money){
            __error($fenxiao['texts']['commission']."不足");
        }
        
        $integer = intval($fenxiao['withdrawal_integer_multiple']);
        if($integer > 0){
            if($money % $integer != 0){
                __error("请输入{$integer}的倍数提现");
            }
        }
        
        $service_charge = max(0,$money * (floatval($fenxiao['service_charge']) / 100));
        $fixed_service_charge = max(0,floatval($fenxiao['fixed_service_charge']));
        $service_charge += $fixed_service_charge;
        if($fenxiao['withdrawal_balance_score_free'] == 1 && ($type == 1 || $type == 6)){
            $service_charge = 0;
            $fixed_service_charge = 0;
        }
        
        $max_money = $money;
        $realmoney = $money - $service_charge;

        if($realmoney <= 0){
            __error("提现金额不足扣除手续费");
        }

        $data['withdrawal_type'] = 2;
        $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();
            
            $id = Db::name("bbfx_withdrawal_log")->insertGetId($data);
            if(empty($id)){
                throw new \Exception("提现失败1");
            }
            
            $data['id'] = $id;
            $log = $data;
            $res = \app\common\model\bbfxshop\FenxiaoJiesuan::setUserCommission($user['id'],0-$money,20,"佣金提现",$data);
            if(empty($res)){
                throw new \Exception("提现失败2");
            }
            
            if($fenxiao['withdrawal_balance_check'] == 1 && ($type == 1 || $type == 6)){
                if($type == 1){
                    $res = User::setUserMoney($data['user_id'],$data['realmoney'],1,9,"佣金提现",$data);
                }
                else if($type == 6){
                    $res = User::setUserMoney($data['user_id'],$data['realmoney'],2,9,"佣金提现",$data);
                }
                if($res){
                    Db::name("bbfx_withdrawal_log")->where(['id'=>$id])->update(['status'=>1,'paytime'=>time()]);
                    \app\common\model\bbfxshop\Txabonus::tixianExtract($id);
                    \app\common\model\bbfxshop\UserTixian::sendNotice($log['id']);
                }
            }

            // 提现到微信零钱免审
            
            $check_max = round($fenxiao['wexin_tx_check_max'],2);
            if($fenxiao['wexin_tx_check'] == 1 && $type == 2 && ($check_max <= 0 || ($check_max > 0 && $check_max >= $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($set['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);
        }
        
        if($fenxiao['is_withdrawal_limit'] == 1 && $user['is_tixian_activate'] == 1){
            $tx_money = Db::name("bbfx_withdrawal_log")->where(['user_id'=>$user['id'],'withdrawal_type'=>2,'status'=>['in',[0,1]],'createtime'=>['>',$user['tixian_activate_time']]])->sum("money");
            if($tx_money >= $fenxiao['withdrawal_limit_amount'] && $fenxiao['withdrawal_limit_amount'] > 0){
                Db::name("bbfx_user")->where(['id'=>$user['id']])->update(['is_tixian_activate'=>0]);
            }
        }
        
        
        $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);
    }
}