<?php

namespace addons\epay\controller;

use addons\epay\library\QRCode;
use addons\epay\library\Service;

use addons\epay\library\Wechat;
use addons\third\model\Third;
use app\api\model\Delivery;
use app\api\model\DeliveryTrade;
use app\common\library\Auth;
use think\addons\Controller;
use think\Response;
use think\Session;
use Yansongda\Pay\Exceptions\GatewayException;
use Yansongda\Pay\Pay;


use app\api\model\Banner;
use app\api\model\Category;
use app\api\model\CoinRecord;
use app\api\model\Detail;
use app\api\model\Goods;
use app\api\model\MoneyRecord;
use app\api\model\Order;
use app\api\model\PriceRange;
use app\api\model\Prizerecord;
use app\api\model\RechargeList;
use app\api\model\RechargeOrder;
use app\api\model\SearchHistory;
use app\api\model\Setting;
use app\api\model\Box;
use app\api\model\Star;
use app\api\model\Text;

//use app\common\controller\Api;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\exception\DbException;
use app\api\library\Retail;


/**
 * API接口控制器
 *
 * @package addons\epay\controller
 */
class Api extends Controller
{

    protected $layout = 'default';
    protected $config = [];

    /**
     * 默认方法
     */
    public function index()
    {
        return;
    }

    /**
     * 外部提交
     */
    public function submit()
    {
        $this->request->filter('trim');
        $out_trade_no = $this->request->request("out_trade_no");
        $title = $this->request->request("title");
        $amount = $this->request->request('amount');
        $type = $this->request->request('type');
        $method = $this->request->request('method', 'web');
        $openid = $this->request->request('openid', '');
        $auth_code = $this->request->request('auth_code', '');
        $notifyurl = $this->request->request('notifyurl', '');
        $returnurl = $this->request->request('returnurl', '');

        if (!$amount || $amount < 0) {
            $this->error("支付金额必须大于0");
        }

        if (!$type || !in_array($type, ['alipay', 'wechat'])) {
            $this->error("支付类型错误");
        }

        $params = [
            'type' => $type,
            'out_trade_no' => $out_trade_no,
            'title' => $title,
            'amount' => $amount,
            'method' => $method,
            'openid' => $openid,
            'auth_code' => $auth_code,
            'notifyurl' => $notifyurl,
            'returnurl' => $returnurl,
        ];
        return Service::submitOrder($params);
    }

    /**
     * 微信支付(公众号支付&PC扫码支付)
     * @return string
     */
    public function wechat()
    {
        $config = Service::getConfig('wechat');

        $isWechat = stripos($this->request->server('HTTP_USER_AGENT'), 'MicroMessenger') !== false;
        $isMobile = $this->request->isMobile();
        $this->view->assign("isWechat", $isWechat);
        $this->view->assign("isMobile", $isMobile);

        //发起PC支付(Scan支付)(PC扫码模式)
        if ($this->request->isAjax()) {
            $pay = Pay::wechat($config);
            $orderid = $this->request->post("orderid");
            try {
                $result = $pay->find($orderid);
                if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
                    $this->success("", "", ['status' => $result['trade_state']]);
                } else {
                    $this->error("查询失败");
                }
            } catch (GatewayException $e) {
                $this->error("查询失败");
            }
        }

        $orderData = Session::get("wechatorderdata");
        if (!$orderData) {
            $this->error("请求参数错误");
        }
        if ($isWechat) {
            //发起公众号(jsapi支付),openid必须

            //如果没有openid,则自动去获取openid
            if (!isset($orderData['openid']) || !$orderData['openid']) {
                $orderData['openid'] = Service::getOpenid();
            }

            $orderData['method'] = 'mp';
            $type = 'jsapi';
            $payData = Service::submitOrder($orderData);
            if (!isset($payData['paySign'])) {
                $this->error("创建订单失败,请返回重试", "");
            }
        } else {
            $orderData['method'] = 'scan';
            $type = 'pc';
            $payData = Service::submitOrder($orderData);
            if (!isset($payData['code_url'])) {
                $this->error("创建订单失败,请返回重试", "");
            }
        }
        $this->view->assign("orderData", $orderData);
        $this->view->assign("payData", $payData);
        $this->view->assign("type", $type);

        $this->view->assign("title", "微信支付");
        return $this->view->fetch();
    }

    /**
     * 支付宝支付(PC扫码支付)
     * @return string
     */
    public function alipay()
    {
        $config = Service::getConfig('alipay');

        $isWechat = stripos($this->request->server('HTTP_USER_AGENT'), 'MicroMessenger') !== false;
        $isMobile = $this->request->isMobile();
        $this->view->assign("isWechat", $isWechat);
        $this->view->assign("isMobile", $isMobile);

        if ($this->request->isAjax()) {
            $orderid = $this->request->post("orderid");
            $pay = Pay::alipay($config);
            try {
                $result = $pay->find($orderid);
                if ($result['code'] == '10000' && $result['trade_status'] == 'TRADE_SUCCESS') {
                    $this->success("", "", ['status' => $result['trade_status']]);
                } else {
                    $this->error("查询失败");
                }
            } catch (GatewayException $e) {
                $this->error("查询失败");
            }
        }

        //发起PC支付(Scan支付)(PC扫码模式)
        $orderData = Session::get("alipayorderdata");
        if (!$orderData) {
            $this->error("请求参数错误");
        }

        $orderData['method'] = 'scan';
        $payData = Service::submitOrder($orderData);
        if (!isset($payData['qr_code'])) {
            $this->error("创建订单失败,请返回重试");
        }

        $type = 'pc';
        $this->view->assign("orderData", $orderData);
        $this->view->assign("payData", $payData);
        $this->view->assign("type", $type);
        $this->view->assign("title", "支付宝支付");
        return $this->view->fetch();
    }

    /**
     * 支付成功回调
     */
    public function notifyx()
    {
        $type = $this->request->param('type');
        if (!Service::checkNotify($type)) {
            echo '签名错误';
            return;
        }

        //你可以在这里你的业务处理逻辑,比如处理你的订单状态、给会员加余额等等功能
        //下面这句必须要执行,且在此之前不能有任何输出
        echo "success";
        return;
    }

    /**
     * 支付成功返回
     */
    public function returnx()
    {
        $type = $this->request->param('type');
        if (Service::checkReturn($type)) {
            echo '签名错误';
            return;
        }

        //你可以在这里定义你的提示信息,但切记不可在此编写逻辑
        $this->success("恭喜你!支付成功!", addon_url("epay/index/index"));

        return;
    }

// 支付盲盒订单的异步
    function notifyx212313()
    {
        $res = $this->request->param();
// //   $order_id=$this->request->param('out_trade_no');
// //   file_put_contents('./12347.txt',json_encode($data));

//   $data = '{"pid":"1019","trade_no":"Y2022012921422516786","out_trade_no":"202201292233419043907","type":"wxpay","name":"# 202201292142221315781 \u5728\u7ebf\u652f\u4ed8","money":"25.00","trade_status":"TRADE_SUCCESS","sign":"1a1a9836c134ad3234b81e67ab3d7a54","sign_type":"MD5","addon":"epay","controller":"api","action":"notifyx212313"}';

//   $res = json_decode($data,true);

        $order = Db::table('box_order')->where('out_trade_no', $res['out_trade_no'])->find();

// print_r($order);die;
        // Db::table('box_order') ->where('out_trade_no', $res['out_trade_no'])->setField('status','unused');
        if ($order && $order['status'] == 'unpay') {

            if ($res['trade_status'] == 'TRADE_SUCCESS') {
                Db::table('box_order')->where('out_trade_no', $res['out_trade_no'])->setField('status', 'unused');
                $user = Db::table('box_user')->where('id', $order['user_id'])->find();


                $users = Db::table('box_user')->where('id', $user['pid'])->find();

                $lou = Db::table('box_setting')->where('id', 1)->find();


                $kou = $lou['kou'];
                if ($users['recharnum'] == 1) {
                    Db::table('box_user')->where('id', $users['id'])->setInc("recharnum", 1);
                    Retail::giveMoneys($order);

                } else {
                    Db::table('box_user')->where('id', $users['id'])->setInc("recharnum", 1);
                    $userarr = Db::table('box_user')->where('id', $users['id'])->find();
                    if (bcmod($userarr['recharnum'], $kou) == 0) {

                    } else {


                        Retail::giveMoneys($order);
                    };
                }


                echo "success";
            }
        }


    }

    /**
     * 支付成功回调
     */
    public function notifyx2()
    {
        /*  $type = $this->request->param('type');
          if (!Service::checkNotify($type)) {
              echo '签名错误';
              return;
          }

          */
        $pay = $this->request->param();
//        file_put_contents('./5.txt', json_encode($pay));


        $p = $this->request->param();
        $order_id = $this->request->param();
        $xml = simplexml_load_string(file_get_contents("php://input"), 'SimpleXMLElement', LIBXML_NOCDATA);

        foreach ($xml as $k => $v) {
            $data[(string) $k] = (string) $v;
        }


        //  print_r($order_id);
        $u = Db::table('box_recharge_order')->where('out_trade_no', $data['out_trade_no'])->find();

        //  print_r($u);

        $order = Db::table('box_recharge_order')->where('out_trade_no', $data['out_trade_no'])->find();
//        file_put_contents('./5.txt', json_encode($order));

        if ($order && $order['status'] == 'unpay') {

            if ($data['return_code'] == 'SUCCESS') {

                //   echo 'zfcg';


                $user = Db::table('box_user')->where('id', $order['user_id'])->find();

                if ($user) {


                    $lou = Db::table('box_setting')->where('id', 1)->find();

                    //  print_r($user);


                    $yq = $user['coin'];

                    $jq = $order['coin_amount'] * $lou['one_rmb_to_coin_num'];

                    $hq = $yq + $jq;


                    //加钱

                    Db::table('box_user')->where(['id' => $user['id']])->setField('coin', $hq);

                    Db::table('box_recharge_order')->where(['id' => $order['id']])->setField('status', 'paid');


                    //加记录

                    Db::table('box_coin_record')->insertGetId([
                        'user_id' => $user['id'],
                        'coin' => $jq,
                        'before' => $yq,
                        'after' => $hq,
                        'type' => 'recharge',
                        'create_time' => time()
                    ]);

                    Db::table('box_user_score_log')->insertGetId([
                        'user_id' => $user['id'],
                        'score' => $jq,
                        'before' => $yq,
                        'after' => $hq,
                        'memo' => '前台充值',
                        'createtime' => time()
                    ]);

                    //  $kou = $lou['kou'];
                    //  //加已充值成功次数
                    //  Db::table('box_user') ->where('id', $order['user_id'])->setInc("recharnum", 1);
                    //   $users= Db::table('box_user') ->where('id', $order['user_id'])->find();
                    //   if($users['recharnum']<=$kou){
                    //       Retail::giveMoney($order);
                    //   }

                    // 发放分销佣金

                    echo "success";
                } else {
                    echo 'fail';

                }


            } else {

                echo 'fail';
            }


        } else {


            echo 'fail';


        }


        //   print_r($p);


        //你可以在这里你的业务处理逻辑,比如处理你的订单状态、给会员加余额等等功能
        //下面这句必须要执行,且在此之前不能有任何输出

        return;
    }


    public function notifyx22()
    {

        file_put_contents('./xu.txt', json_encode($this->request->param()));
        $p = $this->request->param('trade_status');
        $order_id = $this->request->param('out_trade_no');
        $order = Db::table('box_delivery_trade')->where('out_trade_no', $order_id)->find();
        if ($order && $order['status'] == 'unpay') {
            if ($p == 'TRADE_SUCCESS') {
                $user = Db::table('box_user')->where('id', $order['user_id'])->find();

                if ($user) {
                    $yq = $user['coin'];

                    $jq = $order['coin_amount'];

                    $hq = $yq + $jq;
                    //   先将支付订单变更为 已支付
                    Db::table('box_delivery_trade')->where(['id' => $order['id']])->setField('status', 'paid');
                    Db::table('box_user_score_log')->insertGetId([
                        'user_id' => $user['id'],
                        'score' => $jq,
                        'before' => $yq,
                        'after' => $hq,
                        'memo' => '商品发货',
                        'createtime' => time()
                    ]);

                    $resarr = Db::table('box_delivery_order')->where(['delivery_trade_id' => $order['id']])->select();

                    Db::table('box_delivery_order')->where(['delivery_trade_id' => $order['id']])->setField('status', 'undelivered');

                    foreach ($resarr as $v) {

                        Db::table('box_prize_record')->where(['id' => $v['prize_id']])->setField('status', 'delivery');
                    }


// Db::table('box_prize_record')->wherein(['id'=>$resarr['prize_id']])->setField('status','delivery');            
                    echo "success";
                } else {

                    echo 'fail';
                }
            } else {

                echo 'fail';
            }
        } else {
            echo 'fail';
        }
        return;
    }

    /**
     * 支付成功返回
     */
    public function returnx2()
    {

        //  file_put_contents('./345.txt','daozhelile');
        $type = $this->request->param('type');

        $p = $this->request->param('trade_status');
        $order_id = $this->request->param('out_trade_no');
        $data = $this->request->param();

        file_put_contents('./123.txt', json_encode($data));

        /*   if (Service::checkReturn($type)) {
               echo '签名错误';
               return;
           }
   */
        //你可以在这里定义你的提示信息,但切记不可在此编写逻辑?type=0
        //  $this->success("恭喜你!支付成功!", addon_url("epay/index/index"));
        $this->success("恭喜你!支付成功!", "/h5/#?out_trade_no=$order_id&type=$type");

        return;
    }

    public function returnx2222222()
    {


        //你可以在这里定义你的提示信息,但切记不可在此编写逻辑?type=0
        //  $this->success("恭喜你!支付成功!", addon_url("epay/index/index"));
        $this->success("恭喜你!支付成功!", '/h5/#/');

        return;
    }

    public function returnx22()
    {
        $type = $this->request->param('type');

        /*   if (Service::checkReturn($type)) {
               echo '签名错误';
               return;
           }
   */
        //你可以在这里定义你的提示信息,但切记不可在此编写逻辑
        //  $this->success("恭喜你!支付成功!", addon_url("epay/index/index"));
        $this->success("恭喜你!支付成功!", '/h5/#/pages/me/order?type=0');

        return;
    }


    /**
     * 生成二维码
     */
    public function qrcode()
    {
        $text = $this->request->get('text', 'hello world');

        //如果有安装二维码插件,则调用插件的生成方法
        if (class_exists("\addons\qrcode\library\Service") && get_addon_info('qrcode')['state']) {
            $qrCode = \addons\qrcode\library\Service::qrcode(['text' => $text]);
            $response = Response::create()->header("Content-Type", "image/png");

            header('Content-Type: ' . $qrCode->getContentType());
            $response->content($qrCode->writeString());
            return $response;
        } else {
            $qr = QRCode::getMinimumQRCode($text);
            $im = $qr->createImage(8, 5);
            header("Content-type: image/png");
            imagepng($im);
            imagedestroy($im);
            return;
        }
    }



    /**
     * 支付成功回调
     */
    public function notifyxde()
    {
        /*  $type = $this->request->param('type');
          if (!Service::checkNotify($type)) {
              echo '签名错误';
              return;
          }

          */
        $xml = simplexml_load_string(file_get_contents("php://input"), 'SimpleXMLElement', LIBXML_NOCDATA);
        foreach ($xml as $k => $v) {
            $data[(string) $k] = (string) $v;
        }
        //  print_r($order_id);
        $trade = DeliveryTrade::where('out_trade_no', $data['out_trade_no'])->where('status', 'unpay')->find();

        if ($trade) {
            if ($data['return_code'] == 'SUCCESS') {
                // 更发货交易订单状态
                $trade->save([
                    'pay_method' => 'alipay',
                    'pay_rmb' => $data['total_amount'],
                    'alipay_trade_no' => $data['trade_no'],
                    'pay_time' => time(),
                    'status' => 'paid'
                ]);
                // 变更发货订单状态
                $deliveryOrder = Delivery::where('delivery_trade_id', $trade->id)->select();
                $prizeIds = [];
                foreach ($deliveryOrder as $order) {
                    $order->save(['status' => 'undelivered']);
                    $prizeIds[] = $order->prize_id;
                }
                // 变更奖品状态
                Prizerecord::whereIn('id', $prizeIds)->update(['status' => 'delivery', 'delivery_time' => time()]);
            } else {
                echo 'fail';
            }
        } else {
            echo 'fail';
        }
        return;
    }


    public function deliverypaysuccess()
    {
        $this->success("恭喜你!支付成功!", '/h5/#/');
    }

}