<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use think\Db;
use addons\epay\library\Service;
class Recharge extends Frontend
{

    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $layout = '';



    public function index()
    {
        $conf_list = Db::name('paygold_webcon')->order('id asc')->select();
        $this->assign('conf_list',$conf_list);
        return $this->view->fetch();
    }

    //创建订单
    public function recharge_pc(){

        $rc_id = input('rc_id',0);
        $pay_type  = input('pay_type','alipay');
        $mobile = input('mobile',0);


        if(!$rc_id){
            $this->error('请选择充值金额');
        }

        if(!$mobile){
            $this->error('请输入用户手机号');
        }

        //查找用户
        $user_info = Db::name('user')->field('id')->where('mobile',$mobile)->find();
        if (empty($user_info)) {
            $this->error('用户信息不存在');
        }

        //赋值money
        $recharge_config = Db::name('paygold_webcon')->where('id',$rc_id)->find();
        if(!$recharge_config){
            $this->error('请选择充值金额');
        }
        $money = $recharge_config['money'];
        $gold = $recharge_config['gold'];

        //创建订单
        $data = [];
        $data['status'] = 0;
        $pay_no = createUniqueNo('P',$user_info['id']);
        $data['pay_no'] = $pay_no;
        $data['money'] = $money;
        $data['payment_class'] = $pay_type;
        $data['user_id'] = $user_info['id'];
        $data['ext_info'] =  json_encode(['subject'=>'充值金币支付']);
        $data['memo'] =  '充值金币支付';
        $data['createtime'] = time();
        $data['payment'] = $pay_type == 'alipay' ? 'web' : 'scan';
        $orderid = Db::name('pay_order')->insertGetId($data);

        //创建回调
        $even_data = [];
        $even_data['event'] = 'success';
        $even_data['class'] = 'app\common\model\Recharge';
        $even_data['method'] = 'rechargepaysucc';
        $even_data['args'] = json_encode(['user_id'=>$user_info['id'],'gold'=>$gold,'money'=>$money,'pg_id'=>$rc_id]);
        $even_data['pay_no'] = $pay_no;
        Db::name('pay_event')->insertGetId($even_data);


        //下单
        $params = [
            'type'         => $pay_type,
            'orderid'      => $pay_no,
            'title'        => $data['memo'],
            'amount'       => $data['money'],
            // 'amount'       => 0.01,
            'method'       => $pay_type == 'alipay' ? 'web' : 'scan',
            'notifyurl' => $this->request->root(true) . '/notify.php/paytype/'.$pay_type,
            'returnurl' => $this->request->root(true) . '/index/recharge',
        ];
        $res = Service::submitOrder($params);

        if($pay_type == 'wechat'){
            exit;
        }else{
            return $res;
        }
    }



}
