<?php

namespace Home\Controller;
use Org\WeixinSDK\Weixin;
use function PHPSTORM_META\type;
use QRcode;

/**
 * 平台币管理-平台币充值(代币下发到对应推广员账户下)
 */
class CoinOrderController extends BaseController
{
    const LV = 2;//平台币充值手续费
    public function page_show($model,$map,$p=1)
    {
        if (isset($_REQUEST['row'])) {
            $row = $_REQUEST['row'];
        } else {
            $row = 10;
        }
        $this->meta_title = "平台币充值";
        $page = $p ? $p : 1; //默认显示第一页数据
        $data = M($model, 'tab_')
            ->where($map)
            ->order('id DESC')
            ->page($page, $row)
            ->select();

        $count = M($model, "tab_")->where($map)->count();
        $parameter = $map;
        $parameter['p'] = I('get.p', 1);
        $parameter['row'] = I('get.row');
        $page = set_pagination($count, $row, $parameter);
        if ($page) {
            $this->assign('_page', $page);
        }
        $this->assign("data_list", $data);
        $this->display();
    }

    //订单列表
    public function order_list($p=0){
        if(IS_DELETE){
            $order_id = I("trade_no");
            if(empty($order_id)){
                $this->ajaxReturn(['status'=>0,'info'=>'订单号错误'.var_export($order_id,1),'time'=>1000],"JSON");
            }
            $order_info = M("coin_pay_order","tab_")->where("order_number='$order_id'")->find();
            if(!$order_info){
                $this->ajaxReturn(['status'=>0,'info'=>'订单不存在','time'=>1000],"JSON");
            }
            if($order_info['pay_type']==1 && $order_info['order_status']!=0){
                $this->ajaxReturn(['status'=>0,'info'=>'线上充值订单为非待付款状态,无法删除!'.var_export($order_info,1),'time'=>1000],"JSON");
            }
            if($order_info['pay_type']==1 && $order_info['order_status']!=0){
                $this->ajaxReturn(['status'=>0,'info'=>'线下充值订单为非待审核状态,无法删除!','time'=>1000],"JSON");
            }
            M("coin_pay_order","tab_")->where("id=".$order_info['id'])->save(array('is_del'=>1));
            $this->ajaxReturn(['status'=>1,'info'=>'删除成功!','time'=>1000],"JSON");
        }else{
            $map = array();
            $map['is_del']=0;
            $map['promote_id'] = get_pid();
            $start_time = strtotime(I('time_start'));
            $end_time = strtotime(I('time_end'));
            $order_number = I("order_number");
            $order_status = I("order_status");
            $pay_type = I("pay_type");

            if (!empty($start_time) && !empty($end_time)) {
                $map['create_time'] = ['BETWEEN', [$start_time, $end_time + 24 * 60 * 60 - 1]];
            } else if (!empty($start_time)) {
                $map['create_time'] = array('gt', $start_time);
            } else if (!empty($end_time)) {
                $map['create_time'] = array('lt', $end_time + 24 * 60 * 60 - 1);
            }
            if(!empty($order_number)){
                $map['order_number'] = $order_number;
            }
            if(!empty($order_status) || $order_status=='0'){
                $map['order_status'] = $order_status;
            }
            if(!empty($pay_type)){
                $map['pay_type'] = $pay_type;
            }
            $this->assign("order_status_desc",array('0'=>'待付款','1'=>'付款成功','2'=>'待审核','3'=>'代发币','4'=>'已发币','-1'=>'审核不通过'));
            $this->page_show('coin_pay_order',$map,$p);
        }
    }

    //创建订单
    public function order_add(){
        $status = $this->promoteCan('recharge');
        if (!$status) {
            if (IS_POST) {
                $this->ajaxReturn(array('status' => 0, 'msg'=>'无权限操作'));
            } else {
                $this->error('无权限操作');
            }
        }
        $this->assign("LV",self::LV);
        if(IS_POST){
            SafeFilter($_POST);
            $coin_num = I("coin_num");
            $pay_type = I("pay_type");
            if(!is_numeric($coin_num) || $coin_num <0){
                $this->ajaxReturn(['status'=>0,'info'=>'请填写正确的数量','time'=>1000],"JSON");
            }
            $order_no = "AG_" . date('Ymd') . date('His') . sp_random_string(4);
            $data['coin_num']=$coin_num;
            $data['real_amount'] = $coin_num;
            $data['pay_type'] = $pay_type;
            $data['order_number'] = $order_no;
            $data['promote_id'] = get_pid();
            $data['promote_account'] = $_SESSION['onethink_home']['promote_auth']['account'];
            $data['create_time'] = time();
            $data['discount'] = "0";
            if($pay_type==1){ // 在线转账
                $free = sprintf("%.2f",$coin_num*(self::LV/100));
                $free = $free<'0.1' ? '0.1':$free;
                $data['pay_amount'] = bcadd($coin_num,$free,2);
                $data['order_status'] = 0;
            }else{
                $data['pay_amount'] = $coin_num;
                $collection_account = I("collection_account","");
                $pay_order_number = I("pay_order_number");
                /*if($collection_account==''){
                    $this->ajaxReturn(['status'=>0,'info'=>'请选择汇入银行','time'=>1000],"JSON");
                }*/
                if($pay_order_number==''){
                    $this->ajaxReturn(['status'=>0,'info'=>'请输入支付凭证','time'=>1000],"JSON");
                }
                $is_order = M("coin_pay_order","tab_")
                    ->where(
                    array('pay_order_number'=>$pay_order_number,
                        'is_del'=>0
                    ))->find();
                if($is_order){
                    $this->ajaxReturn(['status'=>0,'info'=>'系统已存在支付凭证,请核实~','time'=>1000],"JSON");
                }
                //$res = $this->upload();
                $res = $this->uploadPicture();
                if($res['status']==0){
                    $this->ajaxReturn(['status'=>0,'info'=>'请选择支付截图','time'=>1000],"JSON");
                }
                if($res['error']==1){
                    $this->ajaxReturn(['status'=>0,'info'=>$res['msg'],'time'=>1000],"JSON");
                }
                $data['collection_account'] = $collection_account;
                $data['pay_order_number'] = $pay_order_number;
                $data['remark'] = I("remark");
                $data['voucher_img'] = $res['id'];
                $data['order_status'] = 2;
                $data['pay_way'] = 3;
            }
            M("coin_pay_order", 'tab_')->add($data);
            recordPromoteLogs('平台币管理','提交充值订单');
            $this->ajaxReturn(['status'=>1,'info'=>'充值提交成功','pay_type'=>$pay_type,'trade_no'=>$order_no,'time'=>1000],"JSON");
        }else{
            $account = $_SESSION['onethink_home']['promote_auth']['account'];
            $bank_list = M("bank","tab_")->select();
            $this->meta_title = "平台币充值";
            $this->assign("account",$account);
            $this->assign("bank_list",$bank_list);
            $this->assign("discount","0");
            $this->display();
        }
    }

    //订单明细
    public function order_detail(){
        $trade_no= I("trade_no");
        $order_info = M("coin_pay_order","tab_")->where("order_number='$trade_no'")->find();
        $this->meta_title = "平台币充值信息";
        $this->assign("order_info",$order_info);
        $this->assign("order_status_desc",array('0'=>'待付款','1'=>'付款成功','2'=>'待审核','3'=>'代发币','4'=>'已发币','-1'=>'审核不通过'));
        $this->display();
    }

    //支付中心
    public function pay_center(){
        $trade_no = I("trade_no");
        $order = M("coin_pay_order","tab_")->where("order_number='$trade_no'")->find();
        if ($order['order_status'] == 1) {
            return $this->error("该订单已经付款成功,请重新发起一笔订单!", U("CoinOrder/order_add"));
        }
        $this->assign("data",$order);
        /*if($order && $order['pay_amount']>='5000'){
            $this->do_sq_pay($trade_no,$order);
        }else{
            $this->display();
        }*/
        $this->display();
    }

    //支付业务(微信/支付宝)
    public function do_pay(){
        $pay_way = I("pay_way");
        $order_id = I("trade_no");
        if($order_id){
            $order_info = M("coin_pay_order", "tab_")->where("order_number='$order_id'")->find();
            if ($order_info['order_status'] == 1) {
                return $this->error("该订单已经付款成功,请重新发起一笔订单!", U("CoinOrder/order_add"));
            }
            $pay_amount = $order_info['pay_amount'];
            if(get_pid()==138 || get_pid()==165){
                $pay_amount = 0.01;
            }
            //$pay_amount = 0.01;
            if($pay_way=='alipay') {
                M("coin_pay_order", "tab_")->where("order_number='$order_id'")->save(array("pay_time" => time()));
                Vendor('Alipay.aop.AopClient');
                Vendor('Alipay.aop.request.AlipayTradePagePayRequest');

                //请求
                $c = new \AopClient();
                $c->gatewayUrl = "https://openapi.alipay.com/gateway.do";
                $c->appId = '2019091067222198';
                $c->rsaPrivateKey = file_get_contents("./Application/Home/SecretKey/alipay/rsa2_private_key.txt");
                $c->alipayrsaPublicKey = file_get_contents("./Application/Home/SecretKey/alipay/alipay2_public_key.txt");
                $c->format = "json";
                $c->charset = "UTF-8";
                $c->signType = "RSA2";
                $request = new \AlipayTradePagePayRequest();
                $request->setNotifyUrl("https://" . $_SERVER['HTTP_HOST'] . "/callback.php/Notify3/alipay_notify");
                $request->setReturnUrl("https://" . $_SERVER['HTTP_HOST'] . "/index.php?s=/Home/CoinOrder/order_list.html");
                //$request->setNotifyUrl("http://zm.free.idcfengye.com/callback.php/Notify3/alipay_notify");
                //$request->setReturnUrl("http://zm.free.idcfengye.com/index.php?s=/Home/CoinOrder/order_list.html");
                $request->setBizContent("{" .
                    "    \"product_code\":\"FAST_INSTANT_TRADE_PAY\"," .
                    "    \"subject\":\"平台币线上充值\"," .
                    "    \"out_trade_no\":\"$order_id\"," .
                    "    \"total_amount\":\"$pay_amount\"," .
                    "    \"body\":\"\"" .
                    "  }");

                $result = $c->pageExecute($request);
                //输出
                echo $result;
            }elseif ($pay_way=='wechat'){
                M("coin_pay_order", "tab_")->where("order_number='$order_id'")->save(array("pay_time" => time()));
                $is_pay = json_decode($this->weixin_pay("余额充值", $order_id,$pay_amount), true);
                if ($is_pay['status'] === 1) {
                    /*include ('phpqrcode.php');
                    $qr = new QRcode();
                    echo '<img src="' + $qr->png($is_pay['url'],false,0,6) + '">';*/
                    $dir =  'Uploads/Picture/'.date('Y-m-d',time());
                    if (!file_exists($dir)){
                        mkdir($dir);
                    }
                    Vendor('phpqrcode/phpqrcode');
                    $qr = new QRcode();
                    $qr_name = $dir.'/'.md5(uniqid(microtime(true),true)).'.png';
                    $qr->png($is_pay['url'],$qr_name,0,6);
                    echo $this->echo_pay_qrcode($order_info['order_number'],$order_info['real_amount'],$order_info['pay_amount'],$qr_name,2);
                }else{
                    echo '充值失败,错误信息:'.$is_pay['return_msg'];
                }
            }else{
                echo '充值失败,错误信息:充值渠道不存在';
            }
        }else{
            echo '充值失败,错误信息:订单信息不存在';
        }
    }


    //微信支付
    public function weixin_pay($title, $order_no, $pay_amount, $trade_type = "NATIVE", $tt = 1)
    {
        //官方
        header("Content-type:text/html;charset=utf-8");
        Vendor("WxPayPubHelper.WxPayPubHelper");
        //$unifiedOrder = new \UnifiedOrder_pub("wx0ba5be5c8bb9f1b7", "1555280551","wDst6e8d0nGUh4hcwBgv8caJmDE1Mxql");
        $unifiedOrder = new \UnifiedOrder_pub(C("wei_xin.email"), C("wei_xin.partner"),C("wei_xin.key"));
        // $des='平台币充值';
        $unifiedOrder->setParameter("body", $title);//商品描述
        //自定义订单号,此处仅作举例
        $timeStamp = time();
        $unifiedOrder->setParameter("out_trade_no", $order_no);//商户订单号
        $unifiedOrder->setParameter("total_fee", $pay_amount * 100);//总金额
        $unifiedOrder->setParameter("notify_url","https://" . $_SERVER['HTTP_HOST'] . "/callback.php/Notify3/wxpay_notify");
        //$unifiedOrder->setParameter("notify_url","http://zm.free.idcfengye.com/callback.php/Notify3/wxpay_notify");
        $unifiedOrder->setParameter("trade_type", $trade_type);//交易类型
        $unifiedOrder->setParameter("product_id", $order_no);//商品ID
        if($trade_type=="MWEB"){
            $scene_info['h5_info']=['type'=>'Wap','wap_url'=>"http://" . $_SERVER['HTTP_HOST'],'wap_name'=>'充值'];
            $unifiedOrder->setParameter("scene_info", json_encode($scene_info));//场景信息
        }
        //获取统一支付接口结果
        $unifiedOrderResult = $unifiedOrder->getResult($tt);
        //商户根据实际情况设置相应的处理流程
        if ($unifiedOrderResult["return_code"] == "FAIL") {
            //商户自行增加处理流程
            // echo base64_encode(json_encode(array('status' => 0, 'return_msg' => $unifiedOrderResult['return_msg'])));
            return json_encode(array('status' => 0, 'return_msg' => $unifiedOrderResult['return_msg']));
        } elseif ($unifiedOrderResult["result_code"] == "FAIL") {
            //商户自行增加处理流程
            // echo "错误代码:".$unifiedOrderResult['err_code']."<br>";
            // echo base64_encode(json_encode(array('status' => 0, 'return_msg' => $unifiedOrderResult['err_code_des'])));
            return json_encode(array('status' => 0, 'return_msg' => $unifiedOrderResult['err_code_des']));
        } elseif ($unifiedOrderResult["code_url"] != NULL) {
            //从统一支付接口获取到code_url
            $code_url = $unifiedOrderResult["code_url"];
            //商户自行增加处理流程
            if ($unifiedOrderResult['return_code'] !== "SUCCESS") {
                \Think\Log::record($unifiedOrderResult['msg']);
                $html = '<div class="d_body">
                    <div class="d_content">
                        <div class="text_center">' . $unifiedOrderResult["return_code"] . '</div>
                    </div>
                    </div>';
            } else {
                return json_encode(array("status" => 1, 'url' => $unifiedOrderResult['code_url']));
            }
        } else {
            file_put_contents(dirname(__FILE__).'/$unifiedOrderResult.txt',json_encode($unifiedOrderResult));
            if ($trade_type == "APP") {
                $app_data['appid'] = $unifiedOrderResult['appid'];
                $app_data['partnerid'] = $unifiedOrderResult['mch_id'];
                $app_data['prepayid'] = $unifiedOrderResult['prepay_id'];
                $app_data['noncestr'] = $unifiedOrder->createNoncestr();
                $app_data['timestamp'] = time();
                $app_data['package'] = "Sign=WXPay";
                $sign = $unifiedOrder->getSign($app_data);
                return json_encode(array("status" => 1, 'appid' => $unifiedOrderResult['appid'], 'mch_id' => $unifiedOrderResult['mch_id'], 'prepay_id' => $unifiedOrderResult['prepay_id'], 'time' => $app_data['timestamp'], 'noncestr' => $app_data['noncestr'], 'sign' => $sign));
            } else if ($trade_type == "MWEB") {
                return json_encode(array("status" => 1,  'mweb_url' => $unifiedOrderResult['mweb_url']));
            }
        }
    }

    //双乾支付业务
    public function do_sq_pay($trade_no,$order){
        $return_url = "https://" . $_SERVER['HTTP_HOST'] . "/index.php?s=/Home/CoinOrder/order_list.html";
        $res = $this->sq_pay_request($trade_no,$order['pay_amount'],$merno="168885",$paymenttype="ZFBZF", $subject="平台币线上支付", $ip=0,$returnurl=$return_url);
        $res = json_decode($res, true);
        if ($res[0]['respMess']=='success' && (string)$res[0]['respCode']=="000000") {
            $dir =  'Uploads/Picture/'.date('Y-m-d',time());
            if (!file_exists($dir)){
                mkdir($dir);
            }
            Vendor('phpqrcode/phpqrcode');
            $qr = new QRcode();
            $qr_name = $dir.'/'.md5(uniqid(microtime(true),true)).'.png';
            $qr->png($res[0]['qrCode'],$qr_name,0,6);
            echo $this->echo_pay_qrcode($order['order_number'],$order['real_amount'],$order['pay_amount'],$qr_name,1);
        }else{
            echo 'SQ_PAY:'.$res[0]['respMess'];
        }
    }

    // 双乾 扫码支付请求
    public function sq_pay_request($order_no,$amount=0.01,$merno="168885",$paymenttype="ZFBZF", $subject="测试产品1", $ip=0,$returnurl=""){
        M("coin_pay_order", "tab_")->where("order_number='$order_no'")->save(array("pay_time" => time()));
        //$returnurl  = empty($returnurl)?"http://".$_SERVER['HTTP_HOST']:$returnurl;//成功跳转
        $notifyurl  = "https://".$_SERVER['HTTP_HOST']."/callback.php/Notify3/sq_alipay_scancode_notify";//通知
        //$notifyurl  = "http://zm.free.idcfengye.com/callback.php/Notify3/sq_alipay_scancode_notify";
        //$ordertime =date("Ymdhms",time());
        // 168885  12345678
        $sign = md5("Amount={$amount}&BillNo={$order_no}&MerNo={$merno}&PayType=SMZF&".strtoupper(md5("12345678")));
        $sign = strtoupper($sign);
        $params=[
            'MerNo' => $merno,
            'isSubMerPay'=>'0',
            'Amount'=>$amount,
            'BillNo'=>$order_no,
            'TranCode'=>"SMZF002",
            'PayType'=> "SMZF",
            'PaymentType'=> $paymenttype,//"UNION","ZFBZF",
            'MerRemark' => 'MerRemark',
            'subject' => $subject,
            'NotifyURL' => $notifyurl,
            'ReturnURL' => $returnurl,
            'clientIp' => $ip,
            // MD5("Amount=0.01&BillNo=1481093236896&MerNo=168885&PayType=SMZF &"+MD5("12345678").toUpperCase()).toUpperCase();
            'MD5info' => $sign,
        ];
        $ret = curl_post("https://scan.95epay.cn/ScanCodePayment.action", $params);
        return $ret;
    }


    public function upload(){
        header("content-type:text/html;charset=utf-8");
        //设置时区
        #date_default_timezone_set('PRC');
        //获取文件名
        $filename = $_FILES['file']['name'];
        if(!$filename){
            return  array("error"=>1,"msg"=>"请选择支付截图");
        }
        //获取文件临时路径
        $temp_name = $_FILES['file']['tmp_name'];
        //获取大小
        $size = $_FILES['file']['size'];
        //获取文件上传码,0代表文件上传成功
        $error = $_FILES['file']['error'];
        //判断文件大小是否超过设置的最大上传限制
        /*if ($size > 2*1024*1024){
            return  array("error"=>1,"msg"=>"文件大小超过2M大小");
        }*/
        //phpinfo函数会以数组的形式返回关于文件路径的信息
        //[dirname]:目录路径[basename]:文件名[extension]:文件后缀名[filename]:不包含后缀的文件名
        $arr = pathinfo($filename);
        //获取文件的后缀名
        $ext_suffix = $arr['extension'];
        //设置允许上传文件的后缀
        $allow_suffix = array('jpg','gif','jpeg','png');
        //判断上传的文件是否在允许的范围内(后缀)==>白名单判断
        if(!in_array($ext_suffix, $allow_suffix)){
            return  array("error"=>1,"msg"=>"上传的文件类型只能是jpg,gif,jpeg,png");
        }
        //检测存放上传文件的路径是否存在,如果不存在则新建目录
        $dir =  'Uploads/Picture/'.date('Y-m-d',time());
        if (!file_exists($dir)){
            mkdir($dir);
        }
        //为上传的文件新起一个名字,保证更加安全
        $new_filename = date('YmdHis',time()).rand(100,1000).'.'.$ext_suffix;
        //将文件从临时路径移动到磁盘
        if (move_uploaded_file($temp_name, $dir."/".$new_filename)){
            return array("error"=>0,"msg"=>"图片上传成功","path"=>$dir."/".$new_filename);
        }else{
            return array("error"=>1,"msg"=>"文件上传失败,错误码:$error");
        }
    }

    /**
     * 上传图片
     * @author huajie <banhuajie@163.com>
     */
    public function uploadPicture(){
        /* 返回标准数据 */
        $result  = array('status' => 1, 'info' => '上传成功', 'data' => '');

        /* 调用文件上传组件上传文件 */
        $Picture = D('Picture');
        $pic_driver = C('PICTURE_UPLOAD_DRIVER');

        $info = $Picture->upload(
            $_FILES,
            C('PICTURE_UPLOAD'),
            C('PICTURE_UPLOAD_DRIVER'),
            C("UPLOAD_{$pic_driver}_CONFIG")
        ); //TODO:上传到远程服务器
        /* 记录图片信息 */
        if($info){
            $result['status'] = 1;
            $result = array_merge($info['voucher_img'], $result);
        } else {
            $result['status'] = 0;
            $result['info']   = $Picture->getError();
        }
        ob_clean();
        return $result;
    }

    public function echo_pay_qrcode($trade_no,$real_amont,$pay_amount,$qrcode_url,$type='1'){
        if($type==1){
            $tips = '请使用支付宝扫描二维码以完成支付';
        }else{
            $tips = '请使用微信扫描二维码以完成支付';
        }
        $html_style = ' <style>'.
            '.payment-body{width: 400px;height: 500px;margin: auto;color: #333}'.
            '.pay-info{margin-top: 100px;font-size:17px }'.
            '.pay-info div{margin: 5px}'.
            '.red{color: red}'.
            'span.label{width: 100px;text-align: right;display: inline-block}'.
            '</style>';
        $html_element  = $html_style.'<div class="payment-body">'.
            '<div class="pay-info">'.
            '<div><span class="label">订单号:</span>'.$trade_no.'</div>'.
            '<div><span class="label">充值金额:</span>本次充值金额<span class="red">'.$real_amont.'</span>元,实际付款<span class="red">'.$pay_amount.'</span>元</div>'.
            '</div>'.
            '<div style="text-align: center;">'.
            '<img src="'.$qrcode_url.'">'.
            '</div>'.
            '<div style="text-align: center">'.$tips.'</div>'.
            '</div>';
        return $html_element;
    }
}