<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\PayOrderModel;
use app\common\model\Wallet;
use app\utils\CurlUtil;
use think\Db;
use addons\epay\library\Service;

/**
 * 充值配置与充值订单
 */
class Pay extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

    // VIP套餐
    public function vip_config()
    {
        $user_id = $this->auth->id;
        $list = Db::name('vip_config')->field(['id','name','image','price','color','is_try','coupon_ids'])->where('status',1)->order('weigh desc,id asc')->select();

        foreach ($list as $key => $val) {
            $coupon_ids = explode(',',$val['coupon_ids']);
            $list[$key]['image'] = cdnurl($val['image']);

            // 如果是试用会员,则需要判断是否使用过了
            if ($val['is_try'] == 1){
                // 是否购买过,1已购买
                $list[$key]['is_buy'] = Db::name('vip_order')->where(['user_id' => $user_id,'vip_id' => $val['id'],'status'=>1])->value('id') > 0 ? 1 : 0;
            }

            // 查询套餐信息
            $coupon_list = Db::name('vip_coupon')->whereIn('id',$coupon_ids)->where('status',1)->select();
            foreach ($coupon_list as $k => $v) {
                $list[$key]['coupon_list'][$k] = [
                    'id' => $v['id'],
                    'image' => cdnurl($v['image']),
                    'content' => "【{$v['name']}】【{$v['end_days']}日内使用有效】 \n {$v['info']}",
                ];
            }
        }
        $this->success('success', $list);
    }

    //vip用的,创建订单
    public function vip_recharge()
    {
        $user_id = $this->auth->id;
        $params = $this->request->param();
        if (empty($params['vip_id'])) {
            return $this->error('参数缺失');
        }
        if (empty($params['pay_type']) || empty($params['platform'])) {
            return $this->error('请选择支付方式');
        }

        if (!$vip_config = Db::name('vip_config')->where('id', $params['vip_id'])->where('status',1)->find()){
            return $this->error('套餐不存在或已下架');
        }

        // 判断是否使用过
        if ($vip_config['is_try'] == 1 && Db::name('vip_order')->where(['user_id' => $user_id,'vip_id' => $params['vip_id'],'status'=>1])->value('id') > 0){
            return $this->error('您已经试用过了');
        }

        if ($vip_config['is_try'] != 1 && $vip_config['price'] <= 0){
            return $this->error('套餐价格不能为0');
        }

        // 查询套餐信息
        $coupon_ids = explode(',',$vip_config['coupon_ids']);
        $coupon_list = Db::name('vip_coupon')->whereIn('id',$coupon_ids)->where('status',1)->select();

        //赋值money
        $pay_amount = $vip_config['is_try'] != 1 ? $vip_config['price'] : '0.00';
        $nowTime    = time();
        $data       = [
            'user_id'     => $user_id,
            'vip_id'      => $params['vip_id'],
            'order_no'    => createUniqueNo('E', $user_id),
            'pay_amount'  => $pay_amount,
            'pay_time'    => $vip_config['is_try'] != 1 ? 0 : $nowTime,
            'status'      => $vip_config['is_try'] != 1 ? 0 : 1,// 如果是试用会员 则无需支付
            'create_time' => $nowTime
        ];
        Db::startTrans();
        if (!$order_id = Db::name('vip_order')->insertGetId($data)) {
            Db::rollback();
            return $this->error('订单创建失败');
        }
        $user_vip_coupon = [];
        foreach ($coupon_list as $k => $v) {
            for ($i = 0;$i < $v['num'];$i++){
                $user_vip_coupon[] = [
                    'coupon_id'           => $v['id'],
                    'user_id'             => $user_id,
                    'order_id'            => $order_id,
                    'coupon_no'           => \app\utils\Common::createNo('C0',8),
                    'type'                => $v['type'],
                    'name'                => $v['name'],
                    'info'                => $v['info'],
                    'end_time'            => strtotime('+' . $v['end_days'] . ' day'),
                    'use_frequency_day'   => $v['use_frequency_day'],
                    'use_frequency_times' => $v['use_frequency_times'],
                    'status' => $vip_config['is_try'] != 1 ? 0 : 1,
                    'create_time' => $nowTime,
                ];
            }
        }
        if (!Db::name('vip_coupon_user')->insertAll($user_vip_coupon)) {
            Db::rollback();
            return $this->error('订单创建失败');
        }
        Db::commit();

        if ($vip_config['is_try'] != 1){
            // 创建支付订单
            $remark    = 'VIP套餐购买';
            $orderData = [
                'user_id'      => $user_id,
                'out_trade_no' => $data['order_no'],
                'order_amount' => $data['pay_amount'],
                'pay_type'     => $params['pay_type'],
                'platform'     => $params['platform'],
                'table_name'   => 'university_event_apply',
                'table_id'     => $order_id,
                'createtime'   => time(),
                'args'         => json_encode([
                    'table_id' => $order_id,
                    'remark'   => $remark
                ], JSON_UNESCAPED_UNICODE),
            ];
            if (!Db::name('pay_order')->insert($orderData)) {
                return $this->error('订单创建失败');
            }

            // 拉起支付 余额支付
            if ($params['pay_type'] == 'wallet') {
                Db::startTrans();
                //钱包更新
                $walletService = new Wallet();
                if (!$walletService->change($user_id, -$orderData['order_amount'], 'money', 20, $remark, $orderData['table_name'], $orderData['table_id'])) {
                    Db::rollback();
                    return $this->error($walletService->getMessage());
                }
                // 支付成功,更改支付金额
                [$res,$msg] = PayOrderModel::vip($orderData['out_trade_no']);
                if (!$res){
                    Db::rollback();
                    return $this->error($msg);
                }
                Db::commit();
                return $this->success('支付成功');
            }

            // 第三方支付下单
            $params = [
                'type'      => $orderData['pay_type'],
                'orderid'   => $orderData['out_trade_no'],
                'title'     => $remark,
                'amount'    => $orderData['order_amount'],
                'method'    => $orderData['platform'],
                'notifyurl' => CurlUtil::getHttp("/api/notify/university_event_{$params['pay_type']}"),
                'returnurl' => '',
            ];
            // 如果是小程序则需要添加 openid
            if ($params['pay_type'] == 'wechat' && $params['platform'] == 'miniapp') {
                $params['openid'] = $this->auth->mini_openid;
            }
            $res = Service::submitOrder($params);
            if ($params['pay_type'] == 'wechat') {
                $this->success('下单成功', json_decode($res, true));
            } else {
                $this->success('下单成功', $res);
            }
        }

        return $this->success('试用成功');
    }

    //人民币充值
    public function money_config()
    {
        $data['balance'] = (new Wallet())->getWallet($this->auth->id);
        $data['recharge_explain'] = config('site.recharge_explain');
        $list           = Db::name('paymoney_config')->order('weigh asc,id asc')->where('is_show', 1)->select();
        $data['config'] = $list;
        $this->success('success', $data);
    }

    //人民币充值 创建订单
    public function money_recharge()
    {
        $rc_id      = input('rc_id', 0);
        $pay_type   = input('pay_type', 'wechat');
        $platform   = input('platform', 'app');
        $free_money = input('free_money', 0);
        $user_id        = $this->auth->id;
        if (!$rc_id && !$free_money) {
            $this->error('请选择或填写充值金额');
        }

        if ($rc_id) {
            //赋值money
            $recharge_config = Db::name('paymoney_config')->where('id', $rc_id)->find();
            $money           = $recharge_config['money'] ?: 0;
        } else {
            //自由输入覆盖
            $money = floatval($free_money);
        }

        if ($money <= 0) {
            $this->error('支付金额必须大于0');
        }
        if ($money > 100000) {
            $this->error('支付金额太大');
        }

        // 创建支付订单
        $remark    = '充值订单';
        $orderData = [
            'user_id'      => $user_id,
            'out_trade_no' => createUniqueNo('M', $user_id),
            'order_amount' => $money,
            'pay_type'     => $pay_type,
            'platform'     => $platform,
            'table_name'   => 'money_recharge',
            'table_id'     => 0,
            'createtime'   => time(),
            'args'         => json_encode([
                'table_id' => 0,
                'money'    => $money,
                'remark'   => $remark
            ], JSON_UNESCAPED_UNICODE),
        ];
        if (!Db::name('pay_order')->insert($orderData)) {
            return $this->error('订单创建失败');
        }

        // 第三方支付下单
        $params = [
            'type'      => $orderData['pay_type'],
            'orderid'   => $orderData['out_trade_no'],
            'title'     => $remark,
            'amount'    => $orderData['order_amount'],
            'method'    => $orderData['platform'],
            'notifyurl' => CurlUtil::getHttp("/api/notify/recharge/pay_type/{$pay_type}"),
            'returnurl' => '',
        ];
        // 如果是小程序则需要添加 openid
        if ($pay_type == 'wechat' && $platform == 'miniapp') {
            $params['openid'] = $this->auth->mini_openid;
        }
        $res = Service::submitOrder($params);
        if ($pay_type == 'wechat') {
            $this->success('success', json_decode($res, true));
        } else {
            $this->success('success', $res);
        }
    }
}