<?php
namespace app\api\controller;
use app\model\User as UserModel;
use support\Request;
use app\model\Cdkey as CdkeyModel;
use taoser\facade\Validate;
use support\think\Db;
use hg\apidoc\annotation as Apidoc;

/**
 * 钱包接口
 */
class WalletController extends BaseController{
    /**
     * 不需要鉴权的方法
     * @var array
     */
    public $noNeedAuth = ['*'];

    /**
     * 无需登录及鉴权的方法
     * @var array
     */
    public $noNeedLogin = [];
    /**
     * 用户调研币兑换问卷指标
     * @Apidoc\Method("POST")
     * @Apidoc\Param("currency", type="string",require=true, desc="货币money_to_score")
     * @Apidoc\Param("sendAmount", type="string",require=true, desc="调研币兑换数量")
     * @Apidoc\Param("receiveAmount", type="string",require=true, desc="问卷指标兑换数量")
     * @Apidoc\Param("trade_password", type="string",require=true, desc="交易密码")
     * @Apidoc\Param("code", type="string",require=true, desc="图形验证码(event=exchange)")
     */
    public function exchange(){
        //return $this->error(__('The system is under maintenance, please wait...'));
        $user = \support\Jwt\JwtToken::getUser();
        // if(Config('site.trade_password_type') == 'email'){
        //     captcha_verfiy('email','exchange',$user['username']);
        // }else{
        //     $trade_password = input('trade_password');
        //     \support\Jwt::verify_trade_password($trade_password);
        // }
        $currency_pair = input('currency');
        $currencys = explode('_to_', $currency_pair);
        $from_currency = $currencys[0];
        $to_currency = $currencys[1];
        if(!$from_currency || !$to_currency){
            return $this->error(__('Invalid parameters'));
        }
        $sendAmount = (float)input('sendAmount');
        $receiveAmount = (float)input('receiveAmount');
        $rate = Config('site.'.$currency_pair.'_rate');
        if(!$sendAmount || !$receiveAmount || !$rate){
            return $this->error(__('Invalid parameters'));
        }
        $_receiveAmount = intval($sendAmount / $rate);
        $_sendAmount = $_receiveAmount * $rate;
        if($sendAmount > $user->$from_currency || $receiveAmount <= 0){
            return $this->error(__('Invalid parameters').$sendAmount .'<' .$user->$from_currency .'||'. $receiveAmount);
        }
        Db::startTrans();
        try{
            UserModel::$from_currency($user->id,-$_sendAmount,\app\enum\BalanceType::EXCHANGE);
            UserModel::$to_currency($user->id,$_receiveAmount,\app\enum\BalanceType::EXCHANGE);
            Db::commit();
            return $this->success(__('Exchange successful'));
        }catch(\Exception $e){
            Db::rollback();
            return $this->error($e->getMessage());
        }
    }
    /**
     * 用户间score转账
     * @Apidoc\Method("POST")
     * @Apidoc\Param("username", type="string",require=true, desc="收款用户/用户ID")
     * @Apidoc\Param("amount", type="string",require=true, desc="金额")
     * @Apidoc\Param("trade_password", type="string",require=true, desc="交易密码")
     * @Apidoc\Param("code", type="string",require=true, desc="图形验证码(event=transfer)")
     */
    public function transfer(){
        //return $this->error(__('The system is under maintenance, please wait...'));
        $user = \support\Jwt::getUser();
        $username = input('username');
        if(!$username){
            return $this->error(__('User is incorrect'));
        }
        /** @var UserModel $to_user */
        if(str_contains($username,'@')){
            $to_user = UserModel::where('username',$username)->find();
        }else{
            $to_user_id = idDecode($username);
            $to_user = UserModel::where('id',$to_user_id)->find();
        }

        if(!$to_user){
            return $this->error(__('User is incorrect'));
        }
        if(Config('site.trade_password_type') == 'email'){
            //captcha_verfiy('email','transfer',$to_user['username']);
        }else{
            $trade_password = input('trade_password');
            \support\Jwt::verify_trade_password($trade_password);
        }
        $amount = (float)input('amount');
        if($amount <= 0){
            return $this->error(__('Invalid parameters'));
        }
        if($user->score < $amount){
            return $this->error(__('Insufficient balance'));
        }
        Db::startTrans();
        try{
            UserModel::score($user->id,-$amount,\app\enum\BalanceType::TRANSFER,$to_user->id);
            UserModel::score($to_user->id,$amount,\app\enum\BalanceType::TRANSFER,$user->id);
            Db::commit();
            return $this->success(__('Transfer successful'));
        }catch(\Exception $e){
            Db::rollback();
            return $this->error($e->getMessage());
        }
    }
    /**
     * 根据关键字查询用户列表
     * @Apidoc\Method("POST")
     * @Apidoc\Param("kw", type="string",require=true, desc="关键字")
     */
    function getuserlist(){
        $kw = Input('kw');
        $user_id = \support\Jwt\JwtToken::getCurrentId();
        $list = [];
        if($kw){
            //$list = User::where('id','<>',\support\Jwt\JwtToken::getCurrentId())->whereLike('nickname|username|email','%'.$kw.'%')->limit(0,10)->order('id asc')->field('id,username')->select();
            
            //$list = User::where('id','<>',\support\Jwt\JwtToken::getCurrentId())->whereLike('username','%'.$kw.'%')->limit(0,10)->order('id asc')->field('id,username,username as name')->select();
            $list = UserModel::whereLike('username','%'.$kw.'%')->where('id','<>',$user_id)->limit(0,10)->order('id asc')->field('id,username,username as name')->select();
            // foreach($list as $k=>$v){

            // }
        }
        
        return $this->success(__('successful'),$list);
    }
    /**
     * 本地cdkey兑换
     * @Apidoc\Method("POST")
     * @Apidoc\Param("cdkey", type="string",require=true, desc="cdkey")
     * @Apidoc\Param("trade_password", type="string",require=true, desc="交易密码")
     * @Apidoc\Param("code", type="string",require=true, desc="图形验证码(event=cdkeyExchange)")
     */
    public function cdkeyExchange_local_cdkey(){
        //return $this->error(__('The system is under maintenance, please wait...'));
        $user = \support\Jwt\JwtToken::getUser();
        // if(Config('site.trade_password_type') == 'email'){
        //     captcha_verfiy('email','exchange',$user['username']);
        // }else{
        //     $trade_password = input('trade_password');
        //     \support\Jwt::verify_trade_password($trade_password);
        // }
        $cdkey = input('cdkey');
        
        /** @var CdkeyModel $Cdkey */
        $Cdkey = CdkeyModel::where('account',$cdkey)->lock(true)->where('is_used',0)->find();
        if(!$Cdkey){
            return $this->error(__('卡密不存在'));
        }
        if($Cdkey['type'] == 3){
            //不能使用续费激活码
            return $this->error(__('卡密不存在'));
        }

        Db::startTrans();
        try{
            CdkeyModel::where('id',$Cdkey->id)->save([
                'record_id' =>  $user->id,
                'is_used'       =>  1,
                'use_time'      =>  time(),
            ]);
            UserModel::score($user->id,$Cdkey->days,\app\enum\BalanceType::RECHARGE_CARD);
            Db::commit();
            return $this->success(__('Exchange successful'));
        }catch(\Exception $e){
            Db::rollback();
            return $this->error($e->getMessage());
        }
    }
    
    /**
     * cdkey兑换
     * @Apidoc\Method("POST")
     * @Apidoc\Param("card_number", type="string",require=true, desc="卡号")
     * @Apidoc\Param("password", type="string",require=true, desc="密码")
     */
    function cdkey_exchange(){
        
        $user = \support\Jwt\JwtToken::getUser();
        $domain = 'http://127.0.0.1:8383';
        $data=[
            'user_id'    =>  \support\Jwt\JwtToken::getCurrentId(),
            'card_number'=>  input('card_number'),
            'password'=>  input('password'),
        ];
        $activeData = [
            'app_id'        =>  8,
            'card_number'   =>  $data['card_number'],
            'password'      =>  $data['password'],
            'type'          =>  'recharge',
            'record_id'     =>  $user->id
        ];
        $remoteResponse = post($domain.'/api/cdkey/redeem',$activeData);
        \support\Log::info($remoteResponse);
        try{
            $remoteResponse = json_decode($remoteResponse,true);
        }catch(\Exception $e){
            return $this->error($e->getMessage());
        }
        if($remoteResponse['code'] !== 0){
            \support\Log::info(json_encode($remoteResponse));
            return $this->error($remoteResponse['msg']);
        }
        if($remoteResponse['data']['days']){
            UserModel::money($user->id,$remoteResponse['data']['days'],\app\enum\BalanceType::RECHARGE_CARD);
            return $this->success(__('Exchange successful'));
        }
        return $this->error($remoteResponse['msg'],$remoteResponse);

    }
}