<?php

namespace app\http\controller;

use fastphp\base\Controller;
use app\http\model\User as UserModel;
use app\http\model\Recharge as RechargeModel;
use app\http\model\Order as OrderModel;
use extend\wechatpay\Wxpay;
use extend\alipay\Alipay;
use enum\http\Order as HttpOrderEnum;
use app\http\model\Package as PackageModel;

class Order extends Controller
{
    private $ju_zhengsong = [
        '50' => 50,
        '200' => 210,
        '500' => 550,
        '1000' => 1150,
        '2000' => 2400,
        '5000' => 6250,
        '10000' => 13000,
    ];
    // private $url_root = 'https://sandbox.sgxz.cn';
    private $url_root = 'https://merchant.sgxz.cn';

    private $http_user_info = [];

    public function __construct()
    {
        parent::__construct('','');
        if (empty($this->userinfo['UserId'])) {
            die;
        }

        $user_model = new UserModel;
        $this->http_user_info = $user_model->get_http_user($this->userinfo['UserId']);

        if ($this->http_user_info['is_verify'] == 0) {
            $return_data = [
                'code'=>-1,
                'data' => '非法参数',
                'msg' => '未实名，请先实名！'
            ];
            echo json_encode($return_data);
            die;
        }
    }
    //创建订单
    public function create_order(){
        $data = json_decode(file_get_contents("php://input"),true)['order_info'];
        
        
        $data['money'] = abs($data['money']);
        $return_data = [];
        switch ($data['order_type']) {
            case 1:
                $return_data = $this->recharge($data,HttpOrderEnum::$charge,$this->url_root.'/plan/recharge/place/order');
                break;
            case 2:
                $return_data = $this->dxwxl($data,HttpOrderEnum::$new,$this->url_root.'/plan/unlimited/place/order');
                break;
            case 3:
                $return_data = $this->dxbt($data,HttpOrderEnum::$new,$this->url_root.'/plan/period/place/order');
                break;
            case 4:
                $return_data = $this->dxbl($data);
                break;
            case 5:
                $return_data = $this->game($data,HttpOrderEnum::$new,$this->url_root.'/plan/long/place/order');
                break;
            
        }
        echo json_encode($return_data);
    }

    //续费
    public function rebuy_order(){
        $data = json_decode(file_get_contents("php://input"),true)['order_info'];
        
        $data['money'] = abs($data['money']);
        unset($data['data']['title']);
        
        $return_data = [];
        switch ($data['order_type']) {
            case 2:
                $return_data = $this->dxwxl($data,HttpOrderEnum::$rebuy,$this->url_root.'/user/pack/renew');
                break;
            case 3:
                $return_data = $this->dxbt($data,HttpOrderEnum::$rebuy,$this->url_root.'/user/pack/renew');
                break;
            case 5:
                unset($data['data']['ids']);
                $return_data = $this->game($data,HttpOrderEnum::$rebuy,$this->url_root.'/user/pack/renew');
                break;
            case 6:
                $return_data = $this->game($data,HttpOrderEnum::$rebuy,$this->url_root.'/user/long/ip/renew');
                break;
            
        }
        echo json_encode($return_data);
    }
    //充值
    private function recharge($data) {
        
        $data['money'] = abs($data['money']);
        $recharge_model = new RechargeModel;
        $recharge_data = [];
        $recharge_data['pay_money'] = $data['money'];
        $recharge_data['user_id'] = $this->userinfo['UserId'];

        //判断充值的金额是否在赠送列表里
        if ((!is_float($recharge_data['pay_money'])) && array_key_exists($recharge_data['pay_money'],$this->ju_zhengsong)){
            $recharge_data['ju_money'] = $this->ju_zhengsong[$data['money']];
        } else {
            $recharge_data['ju_money'] = $data['money'];
        }
        $order_no = "http".time().rand(100,999);
        $recharge_data['pay_type'] = $data['pay_type'];
        $recharge_data['order_no'] = $order_no;
        $recharge_data['pay_status'] = 0;

        $recharge_model->add($recharge_data);

        //支付宝
        if ($data['pay_type'] == 2) {   
            $param = [
                'out_trade_no' => $recharge_data['order_no'],
                'total_amount' => $data['money'],
                'subject' => 'HTTP充值',
                'product_code' => 'FAST_INSTANT_TRADE_PAY',
                'timeout_express' => '30m',
            ];
    
    
            $pay_html = Alipay::pay_http($param);
            $info = [
                'code'=>2,
                'data' => $pay_html
            ];
            return $info;
        }   
        //微信
        if ($data['pay_type'] == 3) {   
             //微信支付
            $wxpay = new Wxpay();

            $param = [
                'username' => $this->userinfo['LoginName'],
                'money' => $data['money']*100,
                'order_no' => $recharge_data['order_no'],
            ];
            $url = $wxpay->http_pay($param);

            $info = [
                'code'=>3,
                'data' => $url
            ];
            return $info;
        } 
        $info = [
            'code'=>-1,
            'data' => '非法参数'
        ];
        return $info;
    }

    //短效无限量
    private function dxwxl($data, $order_type=1,$url='') {
        
        $order_data = [
            'user_id' => $this->http_user_info['Id'],
            'order_type' => $order_type,
            'package_type' => HttpOrderEnum::$dxwxl,
            'durationType' => isset($data['data']['durationType'])?$data['data']['durationType']:'',
            'order_status' => HttpOrderEnum::$pay_yes,
            'money' => $data['money']
        ];
        if ($order_type == 2) {
            unset($data['data']['durationType']);
        }
        $request_data = $data['data'];
        $request_data['sgUserId'] = $this->http_user_info['sgUserId'];

        return $this->order_format($data,$order_data,$request_data,$url);
    }

    //短效包天
    private function dxbt($data,$order_type=1,$url='') {
        $order_data = [
            'user_id' => $this->http_user_info['Id'],
            'order_type' => $order_type,
            'package_type' => HttpOrderEnum::$dxbt,
            'durationType' => isset($data['data']['durationType'])?$data['data']['durationType']:'',
            'order_status' => HttpOrderEnum::$pay_yes,
            'money' => $data['money']
        ];
        if ($order_type == 2) {
            unset($data['data']['durationType']);
        }
        $request_data = $data['data'];
        $request_data['sgUserId'] = $this->http_user_info['sgUserId'];
        return $this->order_format($data,$order_data,$request_data,$url);
    }

    //短效包量
    private function dxbl($data) {
        $order_data = [
            'user_id' => $this->http_user_info['Id'],
            'order_type' => HttpOrderEnum::$new,
            'package_type' => HttpOrderEnum::$dxbl,
            'durationType' => $data['data']['durationType'],
            'order_status' => HttpOrderEnum::$pay_yes,
            'money' => $data['money']
        ];
        
        $request_data = $data['data'];
        $request_data['sgUserId'] = $this->http_user_info['sgUserId'];
        return $this->order_format($data,$order_data,$request_data,$this->url_root.'/plan/usage/place/order');
    }

    //长效游戏
    private function game($data,$order_type=1,$url='') {
        if (isset($data['data']['isAbroad'])) {
            if($data['data']['isAbroad'] == '国内') {
                $data['data']['isAbroad'] = 0;
            } else if($data['data']['isAbroad'] == '国外') {
                $data['data']['isAbroad'] = 1;
            } 
        }
        $order_data = [
            'user_id' => $this->http_user_info['Id'],
            'order_type' => $order_type,
            'package_type' => HttpOrderEnum::$cxyx,
            'game_type' => isset($data['data']['isAbroad'])?isset($data['data']['isAbroad']):'',
            'ip_count' => $data['data']['ipAmount'],
            'order_status' => HttpOrderEnum::$pay_yes,
            'money' => $data['money']
        ];
        // if ($order_type == 2) {
            // unset($data['data']['isAbroad']);
            // unset($data['data']['ipAmount']);
        // }
        
        $request_data = $data['data'];
        $request_data['sgUserId'] = $this->http_user_info['sgUserId'];

        return $this->order_format($data,$order_data,$request_data,$url);
    }
    
    //获取更换ip的城市列表
    public function get_change_ip_city() {
        $data = json_decode(file_get_contents("php://input"),true);
        $url = $this->url_root.'/user/long/ip/relate/cities';

        unset($data['cookie']);

        $data['sgUserId'] = $this->http_user_info['sgUserId'];
        $request_data = formatHttpRequert($data);

        echo(linkcurl($url,'POST',$request_data,[],0));
    }
    //更换ip订单
    public function change_ip_order() {
        $data = json_decode(file_get_contents("php://input"),true)['order_info'];
        $url = $this->url_root.'/user/long/ip/switch';
        $package_model = new PackageModel;

        $data['data']['order_type'] = 6;
        
        $price = $package_model->get_price($data['data']);

        $data['money'] = round(($data['data']['data']['periodAmount'] * $price['price'] * $data['data']['data']['ipAmount']),2);
     
        unset($data['data']['data']);
        unset($data['data']['order_type']);
        

        $order_data = [
            'user_id' => $this->http_user_info['Id'],
            'order_type' => HttpOrderEnum::$change_ip,
            'package_type' => HttpOrderEnum::$cxyx,
            'order_status' => HttpOrderEnum::$pay_yes,
            'ip_count' => 1,
            'game_type' => isset($data['data']['isAbroad'])?isset($data['data']['isAbroad']):'',
            'money' => $data['money']
        ];
        unset($data['data']['cookie']);
        unset($data['data']['title']);
        unset($data['data']['isAbroad']);
        
        $request_data = $data['data'];
        $request_data['sgUserId'] = $this->http_user_info['sgUserId'];
        
        $return_data = $this->order_format($data,$order_data,$request_data,$url);
        echo json_encode($return_data);
    }

    private function order_format($data,$order_data,$request_data,$http_url) {
        
        //去掉切换ip的价格计算，在上一步计算
        if ($order_data['order_type'] != HttpOrderEnum::$change_ip) {
        
            $package_model = new PackageModel;
            
            $price = $package_model->get_price($data);

            switch ($data['order_type']) {
                case 2:
                    $peroid = $data['data']['periodAmount'];

                    $whitelist = 0;
                    if (isset($data['renew'])) {
                        
                        $url = $this->url_root . '/user/short/unlimited/whitelist/maxAmount';
                        $req = formatHttpRequert([
                            'sgUserId' => $this->http_user_info['sgUserId'],
                        ]);

                        $resp = json_decode(linkcurl($url, 'POST', $req, [], 0));
                        if ($resp->s < 0) {
                            return [
                                'code'=>-1,
                                'data' => $resp,
                                'msg' => '请求后台失败，请联系客服！'
                            ];
                        }

                        $whitelist = $resp->d->maxAmount;
                    } 
                    else {
                        if (!isset($data['data']['maxWhitelist'])) {
                            return [
                                'code'=>-2,
                                'data' => '',
                                'msg' => '请求后台失败，请联系客服！'
                            ];
                        }

                        $whitelist = $data['data']['maxWhitelist'];
                    }
                    if ($whitelist == 0) {
                        return [
                            'code'=>-3,
                            'data' => '',
                            'msg' => '请求后台失败，请联系客服！'
                        ];
                    }

                    $discount = max(.6, 1 - .1 * ($whitelist -1)); // 每多一个白名单配额就减 1 折，最低 6 折
                    $data['money'] = round($price['price'] * $peroid * $whitelist * $discount, 2);
                    break;
                case 3:
                    $data['money'] = round(($data['data']['periodAmount'] * $price['price'] * $data['data']['ipAmount']),2);
                    break;
                case 5:
                case 6:
                    $data['money'] = round(($data['data']['periodAmount'] * $price['price'] * $data['data']['ipAmount']),2);
                    break;
                
            }
        }
        

        $data['money'] = abs($data['money']);

        if ($this->http_user_info['ju_money'] >= $data['money']) {
            $ju_money = $this->http_user_info['ju_money'] - $data['money'];
            $user_update_data['ju_money'] = $ju_money;

            $where = [
                'Id' => $this->userinfo['UserId'],
                'ju_money' => $this->http_user_info['ju_money']
            ];

            $user_model = new UserModel;
            if($user_model->updateOne($where,$user_update_data)) {
                $order_model = new OrderModel;

                $order_data['order_no'] = md5(time());

                if ($order_model->add($order_data)) {
                    $url = $http_url;

                    if ($url == $this->url_root . '/user/pack/renew') {
                        $request_data = [
                            'sgUserId' => $request_data['sgUserId'],
                            'packId' => $request_data['packId'],
                            'packType' => $request_data['packType'],
                            'periodType' => $request_data['periodType'],
                            'periodAmount' => $request_data['periodAmount'],
                        ];
                    }
                    
                    $request_data = formatHttpRequert($request_data);
                    $http_data = json_decode(linkcurl($url,'POST',$request_data,[],0));
                    
                    if ($http_data->s < 0) {
                        $info = [
                            'code'=>-7,
                            'data' => '非法参数',
                            'msg' => '请求后台失败，请联系客服！'
                        ];
                        return $info;
                    } else {
                        $request_order_data = [
                            'sgUserId' => $this->http_user_info['sgUserId'],
                            'orderId' => $http_data->d->orderId,
                            'orderType' => $http_data->d->orderType,
                        ];
                        
                        //支付订单
                        $order_url = $this->url_root.'/user/order/try/pay';

                        $request_order_data = formatHttpRequert($request_order_data);
                        
                        $http_order_data = json_decode(linkcurl($order_url,'POST',$request_order_data,[],0));
                        
                        if ($http_order_data->s < 0) {
                            $info = [
                                'code'=>-8,
                                'data' => '非法参数',
                                'msg' => '请求后台失败，请联系客服！'
//                                'submsg' => $http_order_data->m
                            ];
                            return $info;
                        } else {
                            $order_update = [
                                'status' => 1,
                                'order_id' => $http_order_data->d->orderId,
                                'serial' => $http_order_data->d->serial,
                                'payCash' => $http_order_data->d->payCash,
                            ];
                            $order_id = $order_model->getNewOne('id')['id'];
                            $order_model->updateOne(['id' => $order_id],$order_update);
                            $info = [
                                'code'=>1,
                                'data' => '',
                                'msg' => '操作成功！'
                            ];
                            return $info;
                        }
                    }
                } else {
                    $info = [
                        'code'=>-6,
                        'data' => '非法参数',
                        'msg' => '请求后台失败，请联系客服！'
                    ];
                    return $info;

                }
            } else {
                $info = [
                    'code'=>-5,
                    'data' => '非法参数',
                    'msg' => '聚币不足！'
                ];
                return $info;
            }

        } else {
            $info = [
                'code'=>-4,
                'data' => '非法参数',
                'msg' => '聚币不足！'
            ];
            return $info;
        }

    }




}
