<?php
namespace app\home\service;

use app\model\RechargeApplyModel;
use app\model\UserWithdrawalModel;
use think\facade\Log;


/**
 * 处理团队佣金业务
 */
class MoPayService extends BaseHomeService
{

    public $key="kcub8otfk3quj9tz1mew9y5qilw2yelr";
    public $merchant="10300";
    public $bankcode='927';//945
    public $pay_url="https://mopay.cyou/Pay_Index.html";//代收
    public $app_url="https://mopay.cyou/Payment_A000000Cash_add.html";//代收
    public function create_order($orderId,$amount)
    {
        $notify_url=env('PAY.NOTIFY_URL');
        $post_data['pay_memberid']=$this->merchant;
        $post_data['pay_orderid']=$orderId;
        $post_data['pay_applydate']=date('Y-m-d H:i:s');
        $post_data['pay_notifyurl']=$notify_url.url('mopay_notify');
        $post_data['pay_callbackurl']=$notify_url.url('mopay_notify');
        $post_data['pay_amount']=$amount;
        $post_data['pay_bankcode']=$this->bankcode;

        $sign=$this->createSign($this->key,$post_data);
        $post_data['pay_md5sign']=$sign;
        $header = array("Content-Type:application/x-www-form-urlencoded");
        $res=$this->curlPost($this->pay_url,$post_data,10,$header);
        $result=json_decode($res,true);
        return $result;
    }
    public function moPayNotify($data){
        Log::info('收到mopay异步回调:'.json_encode($data));
        $sign=$this->createSign($this->key,$data);
        Log::info('收到mopay代付异步回调sign:'.$sign.'====='.$data['sign']);
        if($sign==strtoupper($data['sign'])){
            if($data['returncode']=='00'){
                $order_info=RechargeApplyModel::getOrderByNo([
                    'order_no'=>$data['orderid']
                ]);
                if($order_info && $data['amount']==$order_info['total_amount']){
                    if($order_info['status']==0){
                        return (new PayService())->dealPayNotify($order_info);
                    }
                }else{
                    Log::info('mopay支付订单不存在:'.json_encode($data));
                }
            }else{
                Log::info('mopay支付订单支付失败:'.json_encode($data));
            }
        }else{
            Log::info('mopay签名校验失败:'.$sign.json_encode($data));
        }
    }
    public function apply_pay($orderId,$amount,$bank_code,$bank_account,$nike_name,$moblie,$ifsc)
    {
        $notify_url=env('PAY.NOTIFY_URL');
        $post_data['mchid']=$this->merchant;
        $post_data['out_trade_no']=$orderId;
        $post_data['money']=round($amount,2);
        $post_data['bank_code']=$bank_code;
        $post_data['bank_account']=$nike_name;
        $post_data['bank_card_no']=$bank_account;
        $post_data['mobile']=$moblie;
        $post_data['ifsc']=$ifsc;
        $post_data['notifyurl']=$notify_url.'/bs/mopay_anotify';

        $sign=$this->createSign($this->key,$post_data);
        $post_data['pay_md5sign']=$sign;
        Log::info('mopay post:'.json_encode($post_data));
        $header = array("Content-Type:application/x-www-form-urlencoded");
        $res=$this->curlPost($this->app_url,$post_data,10,$header);
        $result=json_decode($res,true);
        Log::info('mopay post结果:'.$res);
        if(strtolower($result['status'])=='success'){
            return [
                'code'=>200,
                'msg'=>'ok',
                'order_idx'=>$result['transaction_id'],
                'content'=>$res
            ];
        }else{
            return [
                'code'=>300,
                'msg'=>$result['msg'],
                'order_idx'=>'',
                'content'=>$res
            ];
        }
    }
    public function moPayApplyNotify($data){
        Log::info('收到mopay代付异步回调:'.json_encode($data));

        $sign=$this->createSign($this->key,$data);

        if($sign==strtoupper($data['sign'])){
            if($data['returncode']=='00'){
                $order_info=UserWithdrawalModel::getUserDrawalInfo([
                    'order_no'=>$data['orderid']
                ]);
                if($order_info && $order_info['status']==3){
                    UserWithdrawalModel::where([
                        'id'=>$order_info['id']
                    ])->update([
                        'order_idx'=>$data['transaction_id'],
                        'status'=>4,
                        'deal_time'=>date('Y-m-d H:i:s')
                    ]);
                    Log::info('mopay代付支付成功:'.json_encode($data));
                }else{
                    Log::info('mopay代付订单不存在:'.json_encode($data));
                }
            }else{
                UserWithdrawalModel::where([
                    'order_no'=>$data['orderid']
                ])->update([
                    'status'=>1,
                ]);
                Log::info('mopay代付失败:'.json_encode($data));
            }
        }else{
            Log::info('mopay代付签名校验失败:'.json_encode($data));
        }
    }
    public function getBalance()
    {
        $post_data['merchant']=$this->merchant;
        $sign=$this->generateQueryString($post_data,$this->key);
        $post_data['sign']=$sign;
        $header = array("Content-Type:application/x-www-form-urlencoded");
        $res=$this->curlPost($this->bla_url,$post_data,10,$header);
        $result=json_decode($res,true);
        if($result['code']==200){
            return [
                'amount'=>$result['data']['balanceUsable']
            ];
        }else{
            return [
                'amount'=>0
            ];
        }
    }

    private function curlPost($url, $post_data = array(), $timeout = 5, $header = "", $data_type = "") {
        $header = empty($header) ? '' : $header;
        //支持json数据数据提交
        if($data_type == 'json'){
            $post_string = json_encode($post_data);
        }elseif($data_type == 'array') {
            $post_string = $post_data;
        }elseif(is_array($post_data)){
            $post_string = http_build_query($post_data, '', '&');
        }

        $ch = curl_init();    // 启动一个CURL会话
        curl_setopt($ch, CURLOPT_URL, $url);     // 要访问的地址
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);  // 对认证证书来源的检查   // https请求 不验证证书和hosts
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);  // 从证书中检查SSL加密算法是否存在
        curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
        //curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        //curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        curl_setopt($ch, CURLOPT_POST, true); // 发送一个常规的Post请求
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);     // Post提交的数据包
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);     // 设置超时限制防止死循环
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        //curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);     // 获取的信息以文件流的形式返回
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header); //模拟的header头
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }
    /**
     * 创建签名
     * @param $Md5key
     * @param $list
     * @return string
     */
    protected function createSign($Md5key, $list)
    {
        ksort($list);
        $md5str = "";
        foreach ($list as $key => $val) {
            if (!empty($val) &&  !in_array($key,['sign','pay_md5sign'])) {
                $md5str = $md5str . $key . "=" . $val . "&";
            }
        }
        // 去除末尾的 '&'
        $sign_str=$md5str . "key=" . $Md5key;
        Log::info('mopay代付签名串:'.$sign_str);
        $sign = strtoupper(md5($sign_str));
        return $sign;
    }



}