<?php

namespace app\api\controller;

use app\common\controller\Api;
use \think\Db;
use addons\epay\library\Service;

/*
 * 公众号搜索用户进行充值
 * */
class Recharge extends Api
{

    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
    }



    //金币兑换配置列表
    public function config(){
        $rs = Db::name('paygold_webcon')->field('id,money,gold')->order('id asc')->select();
        if ($rs) {
            foreach ($rs as &$v) {
                $v['money_to_gold'] = config('site.money_to_gold');
            }
            $arr = [
                'id' => -1,
                'money' => 0,
                'gold' => 0,
                'money_to_gold' => config('site.money_to_gold')
            ];

            array_push($rs, $arr);
        }

        $this->success('success',$rs);
    }

    //根据uid检索人
    public function check_user()
    {
        $mobile = input('mobile');
        if(!$mobile){
            $this->error('请输入用户手机号');
        }

        //填充0
        $map = [
            'mobile'=>$mobile,
        ];

        $user_info = Db::name('user')->field('username,nickname')->where($map)->find();
        if (empty($user_info)) {
            $this->error('用户信息不存在');
        }
        $this->success('success',$user_info);
    }



    //兑换金币
    public function exchangegold() {
        $id = input('id', 0, 'intval');
        $freemoney = input_post('freemoney', 0, 'intval'); //自定义
        $uid = $this->auth->id;
        if(!$id && !$freemoney){
            $this->error('请选择或填写兑换金额');
        }

        if ($id) {
            //赋值money
            $paygold_webcon = Db::name('paygold_webcon')->where('id', $id)->find();
            $money = $paygold_webcon ? $paygold_webcon['money'] : 0;
            $gold = $paygold_webcon ? $paygold_webcon['gold'] : 0;
        }
        if ($freemoney) {
            $money = $freemoney;
            $bili = config('site.money_to_gold') ?: '0.1';
            $gold  = bcmul($money,$bili,0);
        }

        if($money<=0) {
            $this->error('支付金额必须大于0');
        }
        if($money > 10000){
            $this->error('支付金额太大');
        }
        //验证余额
        $user_info = model('wallet')->getWallet($this->auth->id);
        if ($user_info['money'] < $money) {
            $this->success('您的余额不足', ['code' => 2]);
        }

        //开启事务
        Db::startTrans();
        //扣费
        $wallet_rs = model('wallet')->lockChangeAccountRemain($uid,0,'money',-$money,18,'兑换金币');
        if($wallet_rs['status'] === false){
            Db::rollback();
            $this->error($wallet_rs['msg']);
        }
        //赠送金币
        $wallet_rs = model('wallet')->lockChangeAccountRemain($uid,0,'gold',$gold,19,'获得兑换金币');
        if($wallet_rs['status'] === false){
            Db::rollback();
            $this->error($wallet_rs['msg']);
        }

        Db::commit();

        $this->success('兑换成功');
    }



}