<?php

namespace app\jinyou\controller;

use fastphp\base\Controller;
use extend\jinyouapi\Jinyoujingtai;
use app\jinyou\model\User as UserModel;
use app\jinyou\model\Product as ProductModel;
use app\jinyou\model\Package as PackageModel;
use app\jinyou\model\PriceScheme as SchemeModel;
use app\jinyou\model\UserPrice as UserPriceModel;
use app\jinyou\model\ProductOrder as ProductOrderModel;
use app\jinyou\model\ProductAccount as ProductAccountModel;
use enum\order\ProductOrder as OrderEnum;
use app\user\model\UserScore as UserScore;
use app\jinyou\model\Account as AccountModel;
use extend\wechatpay\Wxpay;
use extend\alipay\Alipay;
use app\agent\model\AgentUser as AgentModel;
use app\agent\model\ProductPriceScheme;
use app\agent\model\AgentScore as AgentScoreModel;

class Jinyoujt extends Controller
{
    //获取所有套餐
    public function getPackage() {
        $info = $_GET;

        $isset_price= false;
        $discount = 0;
        $user_price = [];

        $user_model = new UserModel;
        $user_info = $user_model->getOne(['Id' => $this->userinfo['UserId']],'Id,discount_id,RestAmount,TestCountLimit,UseTestCount,is_verify');

        if ($user_info['discount_id'] != 0) {
            $isset_price = true;
            if ($user_info['discount_id'] == -1) {
                $user_price_model = new UserPriceModel;
                $user_price_list = $user_price_model->getList(['UserId' => $this->userinfo['UserId'],'ProductId' => 28]);
                foreach ($user_price_list as $infos) {
                    $user_price[$infos['PackageId']] = $infos['UserPrice'];
                }
            } else {
                $scheme_model = new SchemeModel;
                $discount = $scheme_model->getone(['Id' => $user_info['discount_id']])['discount'];
            }
        }

        $package_type = '';
        if ($info['type'] == 1) {
            $package_type = '静态';
        } else if ($info['type'] == 2) {
            $package_type = '固态';
        }
        $package_model = new PackageModel;
        $list = $package_model->get_package($package_type,$isset_price,$discount,$user_price);

        $data = [
            'code' => 1,
            'msg' => '',
            'data' => $list,
        ];

        echo json_encode($data);
    }
    //创建静态订单
    public function create_order() {
        $request_data = json_decode(file_get_contents("php://input"),true)['order_info'];

        $return_data['code'] = 0;

        $request_data['price'] = abs($request_data['price']);

        $user_model = new UserModel;
        $jinyoujingtai = new Jinyoujingtai;
        $package_model = new PackageModel;
        $product_account = new ProductAccountModel;
        $user_update_info = [];

        $user_info = $user_model->getOne(['Id' => $this->userinfo['UserId']]);

        //套餐详情
        $package_info = $package_model->getOne(['Id' => $request_data['package_id']]);

        $user_price_model = new UserPriceModel;
        $package_info['Price'] = $user_price_model->get_user_price($user_info['Id'],$user_info['discount_id'],$package_info);

        //判读测试卡是否需要付钱
        if ($package_info['IsTest'] == 1 && (($user_info['TestCountLimit']!=0 && $user_info['TestCountLimit']<=$user_info['UseTestCount']) || ($user_info['TestCountLimit'] ==0 && $user_info['UseTestCount']>2))) {
            $package_info['Price'] = 1.00;
        } else if($package_info['IsTest'] == 1) {
            $request_data['buy_num'] = 1;
            $account_info['product_info'] = [];
            $user_update_info['UseTestCount'] = $user_info['UseTestCount'] + 1;
            $user_model->updateOne(['Id'=>$this->userinfo['UserId']],$user_update_info);
        }

        //计算实际需要支付的金额
        $OrderAmount = round(abs($package_info['Price'] * $request_data['buy_num']),2);

        //判断价格是否正确
        if ($OrderAmount !=  round(abs($request_data['price']),2)) {
            $return_data['code'] = -1;
            $return_data['msg'] = "价格有误，请联系客服！";
        }

        //判断是否实名
        if ($user_info['is_verify'] != 1) {
            $return_data['code'] = -1;
            $return_data['msg'] = "请前往实名！";
        }

        //判断余额是否足够支付
        if ($request_data['pay_type'] == 1 && $user_info['RestAmount'] < $request_data['price']) {
            $return_data['code'] = -1;
            $return_data['msg'] = "余额不足！";
        }

        //判断账号是否存在
        $timezone = new \DateTimeZone('Asia/Shanghai');
        $datetime = new \DateTime('now', $timezone); // 确保是东八区时间
        $account_result = $product_account->getCount([
            'ProductId' => $package_info['ProductId'],
            'Account' => $request_data['account'],
            'EndTime' => ['>',$datetime->format('Y-m-d H:i:s')]
        ]);
        if($account_result['count'] > 0){
            $return_data['code'] = -1;
            $return_data['msg'] = "账号已经存在！";
            echo json_encode($return_data);
            die;
        }

        $exist = $jinyoujingtai::checkVpnAccountExists($request_data['account'],$request_data['type']);
        if($exist->code != 200){
            $return_data['code'] = -1;
            $return_data['msg'] = "账号已经存在！";
        }

        //判断连接数
        if ($request_data['buy_num'] < 1) {
            $return_data['code'] = -1;
            $return_data['msg'] = "账号数量至少为1！";
        }

        if ($return_data['code'] == -1) {
            echo json_encode($return_data);
            die;
        }

        //获取产品信息
        $product_model = new ProductModel;

        $product_info = $product_model->getOne(['Id' => $package_info['ProductId']]);

        $package_info['ProductName'] = $product_info['Name'];

        $order_no = 'xk'.time().rand(100,999);

        $order_enum = new OrderEnum;

        //判断新开类型
        $OrderType = $order_enum::$New;
        if ($request_data['buy_num'] > 1) {
            $OrderType = $order_enum::$News;
        }

        $OtherPayAmount = 0;
        $AccountPayAmount = 0;

        if ($request_data['pay_type'] == $order_enum::$Balance) {
            $AccountPayAmount = $OrderAmount;
        } else {
            $OtherPayAmount = $OrderAmount;
        }

        $time = date('Y-m-d H:i:s',time());
        $endtime = date("Y-m-d H:i:s",strtotime("+30 day"));

        $order_info = [
            'TenantId' => 0,
            'UserId' => $user_info['Id'],
            'UserName' => $user_info['LoginCode'],
            'ProductId' => $package_info['ProductId'],
            'ProductName' => $product_info['Name'],
            'PackageId' => $package_info['Id'],
            'PackageName' => $package_info['Name'],
            'CouponId' => 0,
            'OrderName' => $package_info['Name'],
            'OrderNo' => $order_no,
            'OrderState' => $order_enum::$NoPay,
            'OrderType' => $OrderType,
            'PayType' => $request_data['pay_type'],
            'PayState' => 0,
            'ConnectCount' => 1,
            'OrderAmount' => $OrderAmount,
            'PaymentAmount' => $OrderAmount,
            'OtherPayAmount' => $OtherPayAmount,
            'AccountPayAmount' => $AccountPayAmount,
            'CouponAmount' => 0,
            'DayPrice' => $package_info['Price'],
            'DayCount' => $package_info['DayCount'],
            'RefundCount' => 0,
            'RefundAmount' => 0,
            'ClientType' => 0,
            'ChannelType' => 0,
            'CreateTime' => $time,
            'UpdateTime' => $time,
            'Accounts' => $request_data['account'],
            'AccountCount' => $request_data['buy_num'],
            'AccountPwd' => $request_data['password'],
            'DeleteTag' => 0,
            'StartTime' => $time,
            'EndTime' => $endtime,
            'IsAutoRefund' => $product_info['AutoRefund'],
            'BackAmount' => 0,
            'agent_id' => $user_info['agent_id'],
            'remark2' => json_encode($request_data)
        ];

        $order_model = new ProductOrderModel;

        //用户余额
        $old_balance = $rest_money = $user_info['RestAmount'];

        if ($request_data['pay_type'] == $order_enum::$Balance) {
            //判断余额是否足够
            if ($old_balance < $OrderAmount) {
                $return_data['code'] = -1;
                $return_data['msg'] = "余额不足！";
                echo json_encode($return_data);
                die;
            } else {
                $rest_money -= $OrderAmount;
                $rest_data = [
                    'RestAmount' => $rest_money
                ];
                if ($user_model->updateOne(['Id'=>$this->userinfo['UserId'],'RestAmount'=>$old_balance],$rest_data) || $OrderAmount == 0) {
                    $score_model = new UserScore;
                    $score_data = [
                        'TenantId'=>0,
                        'UserId' => $this->userinfo['UserId'],
                        'ScoreType' => '6',
                        'ScoreTypeName' => '购买水滴',
                        'ScoreValue' => $OrderAmount,
                        'UserName' => $user_info['Phone'],
                        'OperateUserName' => $user_info['LoginCode'],
                        'RestAmount1' => $old_balance,
                        'RestAmount2' => $rest_money,
                        'DeleteTag'=>0,
                        'CreateTime' => date('Y-m-d H:i:s'),
                        'UpdateTime' => date('Y-m-d H:i:s'),
                    ];
                    $score_model->add($score_data);

                    $order_info['OrderState'] = $order_enum::$Complete;
                    //添加订单
                    $order_model->add($order_info);

                    $account_model = new AccountModel;
                    $return_data = $account_model->open_account($request_data,$user_info,$package_info);

                    //代理计算
                    if($order_info['agent_id'] != 0 && $order_info['PaymentAmount'] != 0.1){

                        $agent_model = new AgentModel();

                        $agent_info = $agent_model->getOne(['id' => $order_info['agent_id']]);

                        //根据折扣设置价格
                        $score_money = 0.00;

                        if($agent_info['discount_id'] != 0){

                            $scheme_model = new ProductPriceScheme();
                           //获取代理折扣
                            $discount  = $scheme_model->getOne(['Id' => $agent_info['discount_id']]);

                            $price = $package_info['LinePrice'] * $discount['discount'] / 100;
                            if ($price < $package_info['MinPrice']) {
                                $price = $package_info['MinPrice'];
                            }
                            $score_money = $order_info['PaymentAmount'] - $order_info['ConnectCount'] * $order_info['AccountCount'] * $price;
                        }


                        $score_model = new AgentScoreModel();

                        $score_data = [
                            'agent_id' => $order_info['agent_id'],
                            'order_id' => isset($order_info['Id'])?$order_info['Id']:0,
                            'score_type' => 1,
                            'score_value' => $score_money,
                            'remark' => "客户购买产品".$order_info['Accounts'],
                            'agent_name' => $agent_info['username'],
                            'op_user' => $order_info['UserName'],
                            'rest_amount1' => $agent_info['account'],
                            'rest_amount2' => $agent_info['account'] + $score_money
                        ];

                        $agent_data = ['account' => ($agent_info['account'] + $score_money)];

                        $score_model->add($score_data);

                        $agent_model->updateOne(['id' => $order_info['agent_id']],$agent_data);

                    }

                    echo json_encode($return_data);
                } else {
                    $return_data['code'] = -1;
                    $return_data['msg'] = "余额不足！";
                    echo json_encode($return_data);
                    die;
                }
            }
        } else if($request_data['pay_type'] == $order_enum::$Ali) {
            $param = [
                'out_trade_no' => $order_info['OrderNo'],
                'total_amount' => $OrderAmount,
                'subject' => '购买水滴',
                'product_code' => 'FAST_INSTANT_TRADE_PAY',
                'timeout_express' => '30m',
            ];
            //添加订单
            $order_model->add($order_info);


            $pay_html = Alipay::pay_jinyou($param);
            $info = [
                'code'=>2,
                'data' => $pay_html
            ];
            echo json_encode($info);
        } else if($request_data['pay_type'] == $order_enum::$Wechat) {

            $order_model->add($order_info);
            //微信支付
            $wxpay = new Wxpay();
            //添加订单

            $param = [
                'username' => $this->userinfo['LoginName'],
                'money' => $OrderAmount*100,
                'order_no' => $order_info['OrderNo'],
            ];
            $url = $wxpay->jinyou_pay($param);

            $info = [
                'code'=>3,
                'data' => $url
            ];
            echo json_encode($info);
        }

    }

    //获取剩余的节点
    public function address_margin(){
        $account_id = json_decode(file_get_contents("php://input"),true)['data'];

        $account_model = new AccountModel;
        $product_shuidi_id = 0;
        $game_id = 0;
        $is_unshar  = 0;

        $where = [
            'Id' => $account_id,
        ];

        $account_info = $account_model->getOne($where);

        $game_id = $account_info['game_id'];

        $package_info = explode('-',$account_info['PackageName']);

        if ($package_info[0] == "静态") {
            $product_shuidi_id = 1;
        } else {
            $product_shuidi_id = 2;
        }
        if ($package_info[1] == "线路") {
            $is_unshar = 1;
        } else {
            $is_unshar = 0;
        }

        $jinyoujingtai = new Jinyoujingtai;

        $data = $jinyoujingtai::regionSurplusOuts($product_shuidi_id,$is_unshar,$game_id);

        echo json_encode($data);
    }

    //获取可切换的ip
    public function change_ip_list() {
        $info = json_decode(file_get_contents("php://input"),true)['data'];
        $jinyoujingtai = new Jinyoujingtai;

        $data = $jinyoujingtai::switchIpList(121,$info['account'],$info['type']);

        echo json_encode($data);

    }


    //切换的ip
    public function change_ip() {
        $info = json_decode(file_get_contents("php://input"),true)['data'];
        $jinyoujingtai = new Jinyoujingtai;

        $account_model = new AccountModel;
        $where = [
            'ProductId' => 28,
            'Account' => $info['chinge_addr']['account'],
            'Status' => 1,
            'DeleteTag' => 0,
        ];

        if ($info['chinge_addr']['rid'] != 0 ) {
            $data = $jinyoujingtai::changeRegion(121,$info['chinge_addr']['province_id'],$info['chinge_addr']['rid'],$info['chinge_addr']['account'],$info['chinge_addr']['type']);
        }

        if ($info['chinge_ip']['ip_id'] != 0 ) {
            $data = $jinyoujingtai::saveSwitchIp(121,$info['chinge_ip']['account'],$info['chinge_ip']['type'],$info['chinge_ip']['ip_id']);
        }

        $shuidi_account_data = $jinyoujingtai::accountInfo(121,$info['chinge_ip']['account'],$info['chinge_ip']['type']);

        $update_data = [
            'Remark' => $shuidi_account_data->data->region.$shuidi_account_data->data->address,
            'Raw' => $shuidi_account_data->data->inlet_website,
        ];
        $account_model->updateOne($where,$update_data);

        echo json_encode(['code' => 1]);

    }

    //解除屏蔽
    public function openTxLimit(){
        $data = json_decode(file_get_contents("php://input"),true);
        if(!$data){
            die;
        }
        $package = explode("-",$data['PackageName']);
        $type = 1;

        if ($package[0] == '静态') {
            $type = 0;
        }

        $where = [
            'ProductId' => $data['productId'],
            'DeleteTag' => 0,
            'Account' => $data['account']
        ];

        $account_model = new AccountModel;

        $im_now = $account_model->getOne($where);

        $im = 1;
        if ($im_now['im']) {
            $im = 0;
        }

        $account_model->updateOne($where, ['im' => $im]);

        $jinyou = new Jinyoujingtai();
        $status = $jinyou::setFirewallStatus($data['account'],$type,121);
        echo  json_encode(['Code'=>30000,]);
    }

}
