<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use addons\epay\library\Service;
/**
 * 充值配置与充值订单
 */
class Pay extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];


    //金币充值
    public function money_config(){
        $list = Db::name('recharge_config')->order('weigh asc,id asc')->select();
        $data['config'] = $list;

        $wallet = model('wallet')->getWallet($this->auth->id);
        $data['wallet'] = $wallet;
        $this->success('success',$data);
    }

    //充值金币 创建订单
    public function money_recharge(){

        $rc_id     = input('rc_id',0);
        $pay_type  = 'wechat';
        $platform  = 'mini';
        $freemoney = input('freemoney',0);
        $uid = $this->auth->id;

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


        //赋值money
        if($rc_id){
            $recharge_config = Db::name('recharge_config')->where('id',$rc_id)->find();
            $money = $recharge_config['money'];
            $giftmoney = $recharge_config['giftmoney'];
        }

        //自由输入覆盖
        if(!empty($freemoney)){
            $rc_id = 0;
            $money = floatval($freemoney);
            $giftmoney = 0;
        }

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


        //创建订单
        $data = [];
        $data['user_id'] = $uid;
        $data['out_trade_no'] = createUniqueNo('P',$uid); // 数据库订单号加密
        $data['order_amount'] = $money;
        $data['createtime'] = time();

        $data['pay_type'] = $pay_type;
        $data['platform'] = $platform;
        $data['order_status'] = 0;
        $data['table_name'] = 'money_recharge';
        $data['table_id'] = 0;
        $data['args'] = json_encode(['giftmoney' => $giftmoney]);

        $orderid = Db::name('pay_order')->insertGetId($data);

        $openid = $this->auth->wxmini_openid;
        //下单
        $params = [
            'type'         => $pay_type,
            'orderid'      => $data['out_trade_no'],
            'title'        => '充值余额',
            'amount'       => $data['order_amount'],
            'method'       => $platform,
            'openid'       => $openid,
            'notifyurl' => config('pay_notify_url').'/api/notify/recharge_notify_base/paytype/'.$pay_type,
            'returnurl' => '',
        ];

        $res = Service::submitOrder($params);

        if($pay_type == 'wechat'){
            $this->success('success',json_decode($res,true));
        }else{
            $this->success('success',$res);
        }
    }





}
