<?php
namespace app\api\controller;

use app\model\Card as CardModel;
use app\model\Cdkey as CdkeyModel;
use app\model\User as UserModel;
use support\think\Db;
use taoser\facade\Validate;
use hg\apidoc\annotation as Apidoc;

/**
 * 卡密模块
 */
class CardController extends BaseController{
    /**
     * 不需要鉴权的方法
     * @var array
     */
    public $noNeedAuth = ['*'];
    public $noNeedLogin = ['detail','list'];
    /**
     * 列表
     * @Apidoc\Query("kw", type="string", 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);
        $kw = (string)input('kw');
        $model = CardModel::where('status',1);
        if($kw){
            $model = $model->whereLike('title',$kw);
        }
        $list = $model->order('id desc')->paginate($limit);
        return $this->success(__('successful'),$list->toArray());

    }
    /**
     * 详情
     * @Apidoc\Query("id", type="int", require=true, desc="ID")
     * @Apidoc\Query("status", type="string", require=true, desc="状态")
     * @Apidoc\Query("page", type="int", require=true, desc="页码",default=1)
     * @Apidoc\Query("limit", type="int", require=true, desc="分页大小",default=10)
     */
    public function detail(){
        $limit = (int)input('limit',10);
        $id = (int)input('id',0);
        $status = (string)input('status','all');
        $model = CdkeyModel::where('category_id',$id);
        if($status!='all'){
            $model = $model->where('status',$status);
        }
        $list = $model->order('id desc')->paginate($limit);
        return $this->success(__('successful'),$list->toArray());
    }
    /**
     * 详情
     * @Apidoc\Query("id", type="int", require=true, desc="ID")
     */
    public function download(){
        $id = (int)input('id',0);
        $model = CdkeyModel::where('category_id',$id);
        $list = $model->order('id desc')->select();
        return $this->success(__('successful'),$list->toArray());
    }
    /**
     * 购买产品
     * @Apidoc\Method("POST")
     * @Apidoc\Param("title", type="string", require=true, desc="标题")
     * @Apidoc\Param("total", type="int", require=true, desc="数量")
     * @Apidoc\Param("days", type="int", require=true, desc="金额")
     * @Apidoc\Param("trade_password", type="string", require=true, desc="交易密码")
     */
    public function create()
    {
        $user = \support\Jwt::getUser();
        $data = [
            'user_id'   => $user->id,
            'title'=> input('title'),
            'total'  => (int)input('total'),
            'days'  => input('days'),
            'status'    =>  0
        ];
        if(!$data['title']){
            return $this->error(__('Incorrect title'));
        }
        /** @var CardModel $gift */
        if(!in_array($data['days'],[100,200,300,500])){
            return $this->error(__('Incorrect amount'));
        }
        if($data['total'] < 1){
            return $this->error(__('Incorrect quantity'));
        }
        $amount = $data['days'] * $data['total'];
        $data['user_id'] = $user->id;
        $data['amount'] = $amount;
        $data['type']   =   'active';
        $data['expires']   =   strtotime('2030-12-31');

        //验证交易密码
        $trade_password = input('trade_password');
        \support\Jwt::verify_trade_password($trade_password);
        //var_dump($user);
        //验证余额
        if($data['amount'] < 1){
            return $this->error(__('Incorrect amount'));
        }
        if($data['amount'] > $user->score){
            return $this->error(__('Insufficient balance'));
        }
        Db::startTrans();
        try{
            $data = CardModel::create($data);
            UserModel::score($data['user_id'],-$data['amount'],\app\enum\BalanceType::CDKEY,$data['id']);
            Hook('card.create',$data);
            Db::commit();
        }catch(\Exception $e){
            Db::rollback();
            return $this->error($e->getMessage());
        }
        return $this->success(__('successful'));
    }
}