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

namespace app\common\model\bbfxshop;

use think\Db;
use think\Model;
use think\Cache;
use app\common\model\bbfxshop\User;

class UserTixian extends Model
{
    public static function task(){
        try {
            self::initWeixinTixian();
            self::autoDakuan();
            self::queryHfbfStatus();
        } catch (\Exception $e) {
            
        }
    }
    public static function initWeixinTixian(){
        $time = time() - 86400;
        $list = Db::name("bbfx_withdrawal_log")->where(['uniacid'=>UNIACID,'status'=>1,'type'=>2,'is_confirm'=>0,'paytime'=>['<',$time]])->field("id,user_id,money,withdrawal_type")->select();
        if(empty($list)){
            return __json(1,"没有微信提现过期记录");
        }

        foreach($list as $key => $log){
            try {
                Db::startTrans();
                
                $res = Db::name("bbfx_withdrawal_log")->where(['id'=>$log['id']])->update(['status'=>2]);
                if(empty($res)){
                    throw new \Exception($log['id']."修改状态失败");
                }
                $remarks = "微信确认收款过期退回";
                $withdrawal_type = $log['withdrawal_type'];
                if($withdrawal_type == 1){
                    $res = User::setUserMoney($log['user_id'],$log['money'],1,6,$remarks,$log);
                }
                else if($withdrawal_type == 2){
                    $res = \app\common\model\bbfxshop\FenxiaoJiesuan::setUserCommission($log['user_id'],$log['money'],21,$remarks,$log);
                }
                else if($withdrawal_type == 3){
                    $res = User::setUserMoney($log['user_id'],$log['money'],2,6,$remarks,$log);
                }
                else if($withdrawal_type == 5){
                    $res = User::setUserMoney($log['user_id'],$log['money'],5,6,$remarks,$log);
                }
                else if($withdrawal_type == 6){
                    $res = User::setUserMoney($log['user_id'],$log['money'],6,6,$remarks,$log);
                }
                else if($withdrawal_type == 7){
                    $res = \app\common\model\bbfxshop\Merchant::setUserMoney($log['user_id'],$log['money'],1,3,$remarks,$log);
                }
                else{
                    throw new \Exception($log['id']."提现类型错误");
                }

                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return __json(0,$e->getMessage());
            }
        }
        
        return __json(1,"操作成功");
    }

    // 查询汇付八方提现状态
    public static function queryHfbfStatus(){

        $huifubafang_query_time = intval(Cache::get("huifubafang_query_time"));
        $page = max(1,intval(Cache::get("huifubafang_query_page")));
        $limit = 50;
        if($huifubafang_query_time > 0 && time() - $huifubafang_query_time < 300){
            return __json(1,"操作成功");
        }

        $newPage = $page + 1;
        Cache::set("huifubafang_query_time",time());
        Cache::set("huifubafang_query_page",$newPage);
        
        $list = Db::name("bbfx_withdrawal_log")->where(['uniacid'=>UNIACID,'type'=>2,'status'=>1,'hfbf_dk'=>1,'dk_status'=>0])->order("id asc")->limit(($page - 1) * $limit,$limit)->select();
        if(empty($list)){
            Cache::set("huifubafang_query_page",1);
            return __json(1,"没有汇付八方提现记录");
        }
        $huifubafang = new \app\common\model\bbfxshop\Huifubafang();

        foreach($list as $log){
            $params = [
                'batch_no' => $log['out_batch_no'],
                'month' => date("Y-m",$log['paytime']) ,
                'order_id' => $log['withdrawal_no'],
            ];
            $res = $huifubafang->wxorderBatchQuery($params);
            if($res['code'] == 1){
                $pay_status = $res['data']['pay_status'];
                if($pay_status == 3){
                    Db::name("bbfx_withdrawal_log")->where(['id'=>$log['id']])->update(["dk_status"=>1,'dk_time'=>time()]);
                }
                else if($pay_status == 4 || $pay_status == -1){
                    $res = Db::name("bbfx_withdrawal_log")->where(['id'=>$log['id']])->update(["status"=>2]);
                    if($res){
                        $remarks = "汇付八方提现失败退回";
                        $withdrawal_type = $log['withdrawal_type'];
                        Db::name("bbfx_withdrawal_log")->where(['id'=>$log['id']])->update(['remarks'=>$remarks]);
                        $log['notes'] = $remarks;
                        if($withdrawal_type == 1){
                            $res = User::setUserMoney($log['user_id'],$log['money'],1,6,$remarks,$log);
                        }
                        else if($withdrawal_type == 2){
                            $res = \app\common\model\bbfxshop\FenxiaoJiesuan::setUserCommission($log['user_id'],$log['money'],21,$remarks,$log);
                        }
                        else if($withdrawal_type == 3){
                            $res = User::setUserMoney($log['user_id'],$log['money'],2,6,$remarks,$log);
                        }
                        else if($withdrawal_type == 5){
                            $res = User::setUserMoney($log['user_id'],$log['money'],5,6,$remarks,$log);
                        }
                        else if($withdrawal_type == 6){
                            $res = User::setUserMoney($log['user_id'],$log['money'],6,6,$remarks,$log);
                        }
                        else if($withdrawal_type == 7){
                            $res = \app\common\model\bbfxshop\Merchant::setUserMoney($log['user_id'],$log['money'],1,3,$remarks,$log);
                        }
                        
                    }
                }
                
            }
        }

        return __json(1,"操作成功");
    }

    // 自动打款
    public static function autoDakuan(){
        $list = Db::name("bbfx_withdrawal_log")->where(['uniacid'=>UNIACID,'type'=>['in',[1,2,4,6]],'status'=>0,'is_auto_dakuan'=>1])->order("id asc")->limit(0,20)->select();
        if(empty($list)){
            return __json(1,"没有自动打款记录");
        }

        foreach($list as $log){
            $result = self::dakuan($log,1);
            // print_r($result);die;
        }

        return __json(1,"操作成功");
    }

    public static function dakuan($log,$status,$is_manual=0,$remarks=''){
        global $_W;
        if(!is_array($log)){
            $log = Db::name("bbfx_withdrawal_log")->where(['id'=>intval($log)])->find();
        }

        if(empty($log)){
            return __json(0,"提现记录不存在");
        }

        if($log['status'] != 0){
            return __json(0,"提现记录已审核");
        }

        if(!in_array($status,[1,2])){
            return __json(0,"提现状态错误");
        }

        $dg_status = 0;
        $success = false;
        $texts = $_W['base']['fenxiao']['texts'];

        try {

            Db::startTrans();
            if(empty($remarks)){
                $remarks = "";
            }
            $res = Db::name("bbfx_withdrawal_log")->where(['id'=>$log['id']])->update(["status"=>$status]);
            if($res){
                if($status == 1){
                    Db::name("bbfx_withdrawal_log")->where(['id'=>$log['id']])->update(["paytime"=>time()]);
                    $predeposit = $texts['predeposit'];
                    if(empty($predeposit)) $predeposit = "预存款";
                    $wtypes = ['1'=>'余额','2'=>'佣金','3'=>'积分','4'=>'','5'=>'红包','6'=>$predeposit,'7'=>'商户','9'=>$texts['contribute_vadded_score']];

                    $wtpye_title = $wtypes[$log['withdrawal_type']];

                    if($log['type'] == 1){
                        // 商城余额
                        User::setUserMoney($log['user_id'],$log['realmoney'],1,5,$wtpye_title."提现打款",$log);
                    }
                    else if($log['type'] == 2){
                        // 微信零钱
                        if($log['withdrawal_type'] == 7){
                            $merchant = Db::name("bbfx_merchant")->where(['id'=>$log['user_id']])->find();
                            $user = User::getUser($merchant['user_id']);
                        }
                        else{
                            $user = User::getUser($log['user_id']);
                        }

                        if(empty($user)){
                            throw new \Exception("用户信息错误");
                        }

                        $openid = $log['openid'];
                        $platform = $log['platform'];
                        if(empty($openid)){
                            if(empty($user['openid'])){
                                if($user['platform'] == 'wxapp' || $user['platform'] == 'WXAPP'){
                                    $openid = $user['wxapp_openid'];
                                }
                                else if($user['platform'] == 'GZH'){
                                    $openid = $user['gzh_openid'];
                                }
                            }
                            else{
                                $openid = $user['openid'];
                            }
                        }
                        
                        if(empty($platform)){
                            $platform = $user['platform'];
                        }
                        
                        if(empty($openid)){
                            throw new \Exception("未查询到用户微信openid");
                        }
                        
                        $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]);
                        }

                        $huifubafang = new \app\common\model\bbfxshop\Huifubafang();
                        if($huifubafang->status == 1 && ($user['platform'] == 'wxapp' || $user['platform'] == 'WXAPP')){
                            $params = [
                                'user_id'=>$user['id'],
                                'out_batch_no'=>$out_batch_no,
                                'money'=>$log['realmoney'],
                                'trade_no'=>$log['withdrawal_no'],
                            ];
                            $res = $huifubafang->wxorderBatchPay($params);
                            if($res['code'] != 1){
                                throw new \Exception($res['message']);
                            }
                            $data = [
                                'batch_id'=>$res['data']['out_batch_no'],
                                'hfbf_dk'=>1
                            ];
                        }
                        else{
                            if($_W['base']['is_merch_transfer_new'] == 1){
                                $res = \app\common\model\bbfxshop\Wxpay::newTransfer($openid,$log['realmoney'],$out_batch_no,$log['realname'],$wtpye_title."提现",$platform);
                                if($res['code'] != 1){
                                    throw new \Exception($res['message']);
                                }
                                $data = [
                                    'batch_id'=>$res['data']['transfer_bill_no']
                                ];
                                if(!empty($res['data']['package_info'])){
                                    $data['package_info'] = $res['data']['package_info'];
                                }
                                $data['is_confirm'] = 0;
                            }
                            else{
                                $res = \app\common\model\bbfxshop\Wxpay::transfer($openid,$log['realmoney'],$out_batch_no,$log['withdrawal_no'],$log['realname'],$wtpye_title."提现",$platform);
                                if(empty($res) || $res['code'] != 1){
                                    throw new \Exception($res['message']);
                                }
                                $data = [
                                    'batch_id'=>$res['data']['batch_id']
                                ];
                            }
                        }
                        
                        Db::name("bbfx_withdrawal_log")->where(['out_batch_no'=>$out_batch_no,'uniacid'=>UNIACID])->update($data);
                    }
                    else if($log['type'] == 3){
                        // 支付宝
                    }
                    else if($log['type'] == 4){
                        // 银行卡
                        $dougong = new \app\common\model\bbfxshop\Dougong();
                        $config = $dougong->getSet();
                        // if($config['status'] == 1){
                        //     $txaccount = iunserializer($log['info']);
                        //     if(empty($txaccount)){
                        //         throw new \Exception("银行卡参数缺失。");
                        //     }
                        //     $params = [
                        //         'cash_amt'=>$log['realmoney'],
                        //         'req_seq_id'=>$log['withdrawal_no'],
                        //         'name'=>$txaccount['name'],
                        //         'cert_no'=>$txaccount['cert_no'],
                        //         'card_no'=>$txaccount['card_no'],
                        //         'prov_id'=>$txaccount['prov_id'],
                        //         'area_id'=>$txaccount['area_id'],
                        //     ];
                        //     $result = $dougong->tixian($params);
                        //     if($result['code'] != 1){
                        //         throw new \Exception($result['message']);
                        //     }
                        //     Db::name("bbfx_withdrawal_log")->where(['id'=>$log['id']])->update(['is_automatic'=>1]);
                        // }
                        if($config['status'] == 1 && $is_manual != 1){
                            $txaccount = iunserializer($log['info']);
                            if(empty($txaccount)){
                                throw new \Exception("提现账户信息缺失。");
                            }
                            if($txaccount['qx_status'] != 1){
                                throw new \Exception("用户的提现账户有误，请让用户重新完善后提现");
                            }
                            // 余额分账
                            $dg_status = 1;

                            $params = [
                                'ord_amt'=>$log['realmoney'],
                                'huifu_id'=>$txaccount['huifu_id'],
                                'req_seq_id'=>$log['withdrawal_no'],
                            ];
                            $result = $dougong->balancePay($params);
                            if($result['code'] != 1){
                                throw new \Exception($result['message']);
                            }
                            
                            if($result['data']['trans_stat'] == 'S' || $result['data']['trans_stat'] == 'C'){
                                $yezf_dk_status = 1;
                            }
                            else if($result['data']['trans_stat'] == 'p'){
                                $yezf_dk_status = 0;
                            }
                            else{
                                $yezf_dk_status = 2;
                            }


                            $dg_qx_no = date('YmdHis').random(8,true);
                            Db::name("bbfx_withdrawal_log")->where(['id'=>$log['id']])->update(['is_automatic'=>1,'yezf_dk'=>1,'dg_qx_no'=>$dg_qx_no,'yezf_dk_status'=>$yezf_dk_status,'dk_status'=>0]);

                            if($yezf_dk_status == 1){
                                try {
                                    // 手动取现
                                    $params = [
                                        'cash_amt'=>$log['realmoney'],
                                        'huifu_id'=>$txaccount['huifu_id'],
                                        'token_no'=>$txaccount['token_no'],
                                        'req_seq_id'=>$dg_qx_no,
                                    ];
                                    $result = $dougong->quxian($params);
                                    if($result['code'] != 1){
                                        Db::name("bbfx_withdrawal_log")->where(['id'=>$log['id']])->update(['dk_status'=>-1]);
                                    }
                                } catch (\Exception $e) {
                                    addFileLog("qx111",$log['id']."=>".$e->getMessage()."\n",FILE_APPEND);
                                    Db::name("bbfx_withdrawal_log")->where(['id'=>$log['id']])->update(['dk_status'=>-1]);
                                }
                            }
                            else if($yezf_dk_status == 0){
                                Db::name("bbfx_withdrawal_log")->where(['id'=>$log['id']])->update(['dk_status'=>-1]);
                            }
                            else{
                                throw new \Exception($result['data']['resp_desc']);
                            }
                            
                        }
                    }
                    else if($log['type'] == 5){
                        // 收款码
                    }
                    else if($log['type'] == 6){
                        // 商城积分
                        User::setUserMoney($log['user_id'],$log['realmoney'],2,9,$wtpye_title."提现打款",$log);
                    }
                }
                else{
                    Db::name("bbfx_withdrawal_log")->where(['id'=>$log['id']])->update(['remarks'=>$remarks]);
                    $log['notes'] = $remarks;
                    if($log['withdrawal_type'] == 1){
                        // 余额提现
                        User::setUserMoney($log['user_id'],$log['money'],1,6,"提现驳回",$log); 
                    }
                    else if($log['withdrawal_type'] == 2){
                        // 佣金提现
                        \app\common\model\bbfxshop\FenxiaoJiesuan::setUserCommission($log['user_id'],$log['money'],21,"提现驳回",$log);
                    }
                    else if($log['withdrawal_type'] == 3){
                        // 积分提现
                        User::setUserMoney($log['user_id'],$log['money'],2,6,"提现驳回",$log);
                    }
                    else if($log['withdrawal_type'] == 4){

                    }
                    else if($log['withdrawal_type'] == 5){
                        // 红包提现
                        User::setUserMoney($log['user_id'],$log['money'],5,6,"提现驳回",$log);
                    }
                    else if($log['withdrawal_type'] == 6){
                        // 预存款提现
                        User::setUserMoney($log['user_id'],$log['money'],6,6,"提现驳回",$log);
                    }
                    else if($log['withdrawal_type'] == 7){
                        // 商户提现
                        \app\common\model\bbfxshop\Merchant::setUserMoney($log['user_id'],$log['money'],1,3,"提现驳回",$log);
                    }
                    else if($log['withdrawal_type'] == 9){
                        // 贡献分提现
                        User::setUserMoney($log['user_id'],$log['contribute_vadded'],15,6,"提现驳回",$log);
                        \app\common\model\bbfxshop\ContributeVadded::setContribute($log['money'],$log['user_id'],100002,"提现驳回",$log);
                    }
                }
                
            }
            else{
                throw new \Exception("操作失败111");
            }
            $success = true;
            Db::commit();
        } 
        catch (\Exception $e) {
            Db::rollback();
            if($dg_status == 1){
                $withdrawal_no = date('YmdHis').random(8,true);
                Db::name("bbfx_withdrawal_log")->where(['id'=>$log['id']])->update(['withdrawal_no'=>$withdrawal_no]);
            }
            return __json(0,$e->getMessage());
        }

        if($success && $status == 1 && $log['withdrawal_type'] == 9){
            \app\common\model\bbfxshop\ContributeVadded::setContribute($log['service_charge'],$log['user_id'],100003,"提现手续费",$log);
        }

        if($success && $status == 1 && $log['withdrawal_type'] == 2){
            \app\common\model\bbfxshop\Txabonus::tixianExtract($log['id']);
        }

        if($success){
            \app\common\model\bbfxshop\UserTixian::sendNotice($log['id']);
        }
        
        \app\common\model\bbfxshop\Sms::sendWithdrawalResultNotice($log);


        return __json(1,"操作成功"); 
    }

    public static function sendNotice($id){
        $log = Db::name("bbfx_withdrawal_log")->where(['id'=>$id])->find();
        if(empty($log)){
            return __json(0,"提现记录不存在");
        }
        if($log['status'] === 0){
            return __json(0,"提现记录未审核");
        }
        if($log['status'] == 1){
            $title = "提现申请已通过";
            $content = "提现已通过，请注意查看收款。";
            if($log['type'] == 2){
                if($log['is_confirm'] == 0){
                    $content = "提现已通过，请前往确认收款，若24小时未确认收款，将进行退回处理。";
                }
            }
            else if($log['type'] == 4){
                if($log['yezf_dk'] == 1 && $log['dk_status'] == 0){
                    $content = "提现已通过，预计明天到账。请注意查看收款。";
                }
            }
            $link = "";
            if(in_array($log['withdrawal_type'],[1,2,3,7]) && $log['type'] == 2 && $log['is_confirm'] >= 0){
                if($log['withdrawal_type'] == 1 || $log['withdrawal_type'] == 3){
                    $link = '/pages/public/withdrawalConfirm?type=1&withdrawal_no='.$log['withdrawal_no'];
                }
                else if($log['withdrawal_type'] == 2 || $log['withdrawal_type'] == 7){
                    $link = '/pages/public/withdrawalConfirm?type=2&withdrawal_no='.$log['withdrawal_no'];
                }
            }
            else{
                $link = '/pages/user/withdrawal/list?type='.$log['withdrawal_type'];
                if($log['withdrawal_type'] == 7){
                    $link = '/pages/user/user';
                }
            }
            
        }
        else{
            $title = "提现申请已拒绝";
            $content = "拒绝原因：".$log['remarks'];
            $link = '/pages/user/withdrawal/list?type='.$log['withdrawal_type'];
            if($log['withdrawal_type'] == 7){
                $link = '/pages/user/user';
            }
        }

        $notice_params = ['title'=>$title,'user_id'=>[$log['user_id']],'type'=>0,'itype'=>9,'content'=>$content,'link'=>$link];

        \app\common\model\bbfxshop\Notice::send($notice_params);

        return __json(1,"操作成功");
    }
}