<?php
namespace app\api\controller;

use app\model\Address as AddressModel;
use app\model\User as UserModel;
use app\model\Withdrawl as WithdrawlModel;
use support\Request;
use support\think\Db;
use taoser\facade\Validate;
use hg\apidoc\annotation as Apidoc;

/**
 * 提现模块
 */
class WithdrawlController extends BaseController{
    /**
     * 不需要鉴权的方法
     * @var array
     */
    public $noNeedAuth = ['*'];

    /**
     * 无需登录及鉴权的方法
     * @var array
     */
    public $noNeedLogin = ['notify','notify1','recent'];
    /**
     * 列表
     * @Apidoc\Method("GET")
     * @Apidoc\Query("status", type="int", require=false, desc="状态")
     * @Apidoc\Query("page", type="int", require=true, desc="页码",default=1)
     * @Apidoc\Query("limit", type="int", require=true, desc="分页大小",default=10)
     */
    public  function list()
    {
        $limit = (int)input('limit',10);
        $status = input('status','all');
        $model = WithdrawlModel::where('user_id',\support\Jwt\JwtToken::getCurrentId())
            ->order('id desc');
        if($status!='all'){
            $model = $model->where('status',$status);
        }
        $list = $model->paginate($limit);
        return $this->success(__('successful'),$list->toArray());
    }
    /**
     * 最近提现
     * @Apidoc\Method("GET")
     */
    public  function recent()
    {
        $list = WithdrawlModel::with(['user'])->
            where('status',\app\enum\WithdrawlStatus::COMPLETE->value)->
            order('id desc')->
            limit(10)->select();
        $list->each(function($item){
            $item->user = UserModel::field('username,email')->where('id',$item->user_id)->find();
        });
        return $this->success(__('successful'),$list->toArray());
    }
    /**
     * 创建
     * @Apidoc\Method("POST")
     * @Apidoc\Param("amount", type="string", require=true, desc="金额")
     * @Apidoc\Param("address_id", type="string", require=true, desc="地址ID,列表选择")
     * @Apidoc\Param("trade_password", type="string", require=true, desc="交易密码")
     */
    public  function create()
    {
        //return $this->error(__('The system is under maintenance, please wait...'));
        //* @Apidoc\Param("code", type="string", require=true, desc="图形验证码(type=withdrawl)")
        //captcha_verfiy('image','withdrawl');
        $address_id = input('address_id');
        if(!$address_id){
            return $this->error(__('Address is incorrect'));
        }
        /** @var AddressModel $address */
        $address = AddressModel::where('id',$address_id)->find();
        if(!$address){
            return $this->error(__('Address is incorrect'));
        }
        // if(!$address->status){
        //     return $this->error(__('Unverified address'));
        // }
        $user = \support\Jwt::getUser();
        if(Config('site.trade_password_type') == 'email'){
            captcha_verfiy('email','withdrawl',$user['username']);
        }else{
            //验证交易密码
            $trade_password = input('trade_password');
            \support\Jwt::verify_trade_password($trade_password);
        }
        
        $deduction_amount = input('amount',0);
        $fee = config('site.withdrawl_fee')[$address['network']];
        if($fee < 0.5){
            $fee = bcmul( $fee , $deduction_amount,2);
        }
        $data = [
            'user_id'   => \support\Jwt\JwtToken::getCurrentId(),
            'deduction_amount'    => $deduction_amount,
            'title'     => $address['title'],
            'network'   => $address['network'],
            'address'   => $address['address'],
            'fee'       => $fee,
            'type'      => 0,
            'status'    => \app\enum\WithdrawlStatus::CREATED->value
        ];
        //验证最小提现金额
        $data['recive_amount'] = $data['deduction_amount'] - $data['fee'];
        $withdrawl_minimum = Config('site.withdrawl_minimum')[$data['network']];
        if($data['deduction_amount'] < $withdrawl_minimum){
            return $this->error(__('Minimum withdrawal of %num%',[
                '%num%' =>  $withdrawl_minimum
            ]));
        }
        //var_dump($user);
        //验证余额
        if($data['deduction_amount'] > $user->money){
            return $this->error(__('The amount exceeds the available balance'));
        }
        //if(WithdrawlModel::whereTime('created_at','-24 hours')->count('id')){
        if(WithdrawlModel::whereTime('created_at','today')->where('user_id',$data['user_id'])->count('id')){
            return $this->error(__('You can only withdraw once a day.'));
        }
        if (!$data['network'] || !in_array($data['network'],['BEP-20','TRC-20','ALIPAY','WECHAT'])) {
            return $this->error(__('Network is incorrect'));
        }
        if (!$data['address']) {
            return $this->error(__('Address is incorrect'));
        }
        Db::startTrans();
        try{
            /** @var WithdrawlModel $data */
            $data = WithdrawlModel::create($data);
            UserModel::money($data->user_id,-$data->deduction_amount,\app\enum\BalanceType::WITHDRAWAL,$data->id);
            
            Db::commit();
            return $this->success(__('successful'),$data);
        }catch(\Exception $e){
            Db::rollback();
            return $this->error($e->getMessage());
        }
    }
    /**
     * 详情
     * @Apidoc\Query("id", type="string", require=true, desc="ID")
     */
    public function detail(){
        $appid = input('id');
        $vo = WithdrawlModel::where('id',$appid)->find();
        if($vo) {
            return $this->success(__('successful'),$vo->toArray());
        }else{
            return $this->error(__("Record does not exist"));
        }
    }
    /**
     * 转账成功异步通知
     * @Apidoc\NotParse()
     * @Apidoc\NotDebug()
     */
    public function notify(){
        $data = aesdecode(input('data',''));
        $data = json_decode($data,true);
        /** @var WithdrawlModel $vo */
        $vo = WithdrawlModel::where('id',$data['out_trade_no'])->find();
        if($vo){
            if($data['result'] == 'SUCCESS'){
                if($vo->status  != \app\enum\WithdrawlStatus::COMPLETE->value){
                    $vo->status  = \app\enum\WithdrawlStatus::COMPLETE->value;
                    $vo->txid = $data['txid'];
                    $vo->transfer_at = $data['transfer_at'] ?: time();
                    $vo->save();
                    Hook('withdrawl.success',$vo);
                }
            }else{
                $vo->status  = \app\enum\WithdrawlStatus::FAIL->value;
                $vo->txid = $data['txid'];
                $vo->memo = $data['reason'];
                $vo->save();
            }
        }
        return response("SUCCESS");
    }
}