<?php

namespace app\jinqiao\controller;

use fastphp\base\Controller;
use app\jinqiao\model\User as UserModel;
use app\jinqiao\model\Package as PackageModel;
use app\jinqiao\model\Order as OrderModel;
use app\user\model\UserScore as UserScore;
use app\jinqiao\model\Key as KeyModel;
use extend\wechatpay\Wxpay;
use extend\alipay\Alipay;

class Index extends Controller
{
    //获取用户余额
    public function get_init() {
        $user_model = new UserModel;
        $package_model = new PackageModel;

        $package_list = $package_model->getList();

        $user_balance = $user_model->getUserBalance($this->userinfo['UserId']);

        echo json_encode([
            'code' => 1,
            'data' => [
                'balance' => $user_balance,
                'package_list' => $package_list,
            ],
        ]);
    }

    //生成订单
    public function create_order() {
        $request_data = json_decode(file_get_contents("php://input"),true)['data'];
        $user_model = new UserModel;
        $package_model = new PackageModel;
        $order_model = new OrderModel;

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

        $order_info = [];
        
        $return_data['code'] = 0;

        $package = $package_model->getOne(['id' => $request_data['package_id']]);

        $money = $package['price'];

        //判断价格是否正确
        if ($money !=  round(abs($request_data['price']),2)) {
            $return_data['code'] = -1;
            $return_data['msg'] = "价格有误，请联系客服！";
        }
        
        //判断余额是否足够支付
        if ($request_data['pay_type'] == 10 && $user_info['RestAmount'] < $money) {
            $return_data['code'] = -1;
            $return_data['msg'] = "余额不足！";
        }
        
        if ($return_data['code'] == -1) {
            echo json_encode($return_data);
            die;
        }

        $order_no = "jinqiao".time().rand(100,999);

        $order_info = [
            'user_id' => $this->userinfo['UserId'],
            'package_id' => $request_data['package_id'],
            'status' => 0,
            'pay_type' => $request_data['pay_type'],
            'order_no' => $order_no,
            'money' => $money,
        ];

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

        if ($request_data['pay_type'] == 10) {
            //判断余额是否足够
            if ($old_balance < $money) {
                $return_data['code'] = -1;
                $return_data['msg'] = "余额不足！";
                echo json_encode($return_data);
                die;
            } else {
                $rest_money -= $money;
                $rest_data = [
                    'RestAmount' => $rest_money
                ];
                if ($user_model->updateOne(['Id'=>$this->userinfo['UserId'],'RestAmount'=>$old_balance],$rest_data)) {
                    $score_model = new UserScore;
                    $score_data = [
                        'TenantId'=>0,
                        'UserId' => $this->userinfo['UserId'],
                        'ScoreType' => '6',
                        'ScoreTypeName' => '购买金桥投屏',
                        'ScoreValue' => $money,
                        '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['status'] = 1;
                    //添加订单
                    $order_model->add($order_info);
                    
                    $key_model = new KeyModel();
                    $key_model->where(['package_id' => $order_info['package_id'],'isused' =>0])->limit(1)->update(['isused' => 1,'user_id' => $order_info['user_id']]);
                    $return_data['code'] = 1;
                    $return_data['msg'] = "兑换码已购买！";

                    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'] == 100) {
            $param = [
                'out_trade_no' => $order_info['order_no'],
                'total_amount' => $money,
                'subject' => '购买金桥投屏',
                'product_code' => 'FAST_INSTANT_TRADE_PAY',
                'timeout_express' => '30m',
            ];
            //添加订单
            $order_model->add($order_info);
    
    
            $pay_html = Alipay::pay_jinqiao($param);
            $info = [
                'code'=>2,
                'data' => $pay_html
            ];
            echo json_encode($info);
        } else if($request_data['pay_type'] == 70) {
            
            $order_model->add($order_info);
            //微信支付
            $wxpay = new Wxpay();
            //添加订单

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

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

    }

    public function get_key() {
        $key_model = new KeyModel();

        $list = $key_model->getList(['user_id' => $this->userinfo['UserId']]);

        $package_model = new PackageModel;

        $package_list = $package_model->getList();

        $package_id_info_list = [];

        foreach ($package_list as $package) {
            $package_id_info_list[$package['id']] = $package;
        }
        foreach ($list as &$info) {
            $info['package_name'] = $package_id_info_list[$info['package_id']]['name'];
            
        }

        
        echo json_encode([
            'code'=>1,
            'data' => $list
        ]);
    }

    public function get_order_list() {
        $page = 0;

        if (isset($get_data['PageIndex'])) {
            $page = ($get_data['PageIndex'] - 1) * 50;
        }
        $order_model = new OrderModel;
        $package_model = new PackageModel;
        $user_model = new UserModel;

        $package_list = $package_model->getList();

        $package_id_info_list = [];

        foreach ($package_list as $package) {
            $package_id_info_list[$package['id']] = $package;
        }

        $list = $order_model->getListPage(['status' => 1], '*', 'id desc', "$page,50");

        $user_id_list = [];

        foreach ($list as &$info) {
            $info['package_name'] = $package_id_info_list[$info['package_id']]['name'];
            $user_id_list[] = $info['user_id'];
        }

        $user_info = $user_model->getList(['Id' => ['IN',$user_id_list]],'Id,LoginCode');

        $user_phone_list = [];
        foreach($user_info as $user) {
            $user_phone_list[$user['Id']] = $user['LoginCode'];
        }

        $pay_type = [
            10 => '余额',
            70 => '微信',
            100 => '支付宝',
        ];
        foreach ($list as &$info) {
            $info['username'] = $user_phone_list[$info['user_id']];
            $info['pay_type'] = $pay_type[$info['pay_type']];
        }

        $data = [
            'Code' => 30000,
            'Data' => $list,
            'Message' => '',
            'TotalCount' => (int)$order_model->getCount(['status' => 1])['count'],
        ];
        echo json_encode($data);
    }
}