<?php
namespace app\api\controller;

use app\model\Gift as GiftModel;
use app\model\GiftOrder as GiftOrderModel;
use app\model\User as UserModel;
use support\think\Db;
use taoser\facade\Validate;
use hg\apidoc\annotation as Apidoc;

/**
 * 礼品模块
 */
class GiftController 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);
        $model = GiftModel::where('status',1);
        $list = $model->order('weight desc,id asc')->paginate($limit);
        return $this->success(__('successful'),$list->toArray());

    }
    /**
     * 详情
     * @Apidoc\Query("id", type="int", require=true, desc="ID")
     */
    public function detail(){
        try{
            $user = \support\Jwt::getUser();
        }catch(\Exception $e){
            $user = ['id'=>0,'role_id'=>0];
        }
        $appid = input('id');
        if(!$appid){
            return $this->error(__("Product does not exist"));
        }
        /** @var GiftModel $gift */
        $gift = GiftModel::where('id',$appid)->find();
        //->cache(true,86400,'product_detail')
        if(!$gift) {
            return $this->error(__("Product does not exist"));
        }
        if($user['id']){
            /** @var GiftOrderModel $total_quantity_user */
            $total_quantity_user = GiftOrderModel::where('gift_id',$gift->id)->where('user_id',$user['id'])->sum('quantity');
            
            $total_quantity_system = $gift->user_quantity ?: 99999999;
            $max_quantity = $total_quantity_system-$total_quantity_user;
            $max_quantity= $max_quantity < 0 ? 0: $max_quantity;
            $gift->max_quantity = $max_quantity;
            $gift->total_quantity_user = $total_quantity_user;
        }else{
            $gift->total_quantity_user = 0;
            $gift->max_quantity = 0;
        }
        return $this->success(__('successful'),$gift->toArray());
    }
    /**
     * 列表
     * @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 record(){
        $limit = (int)input('limit',10);
        $page = (int)input('page',1);
        $status = input('status','all');
        $user_id = \support\Jwt\JwtToken::getCurrentId();
        $model = GiftOrderModel::with(['gift'])->where('user_id',$user_id);
        if($status!='all'){
            $model = $model->where('status',$status);
        }
        $list = $model->order('created_at desc')
            ->paginate($limit);
        return $this->success(__('successful'),$list->toArray());
    }
    /**
     * 购买产品
     * @Apidoc\Method("POST")
     * @Apidoc\Param("gift_id", type="string", require=true, desc="产品ID")
     * @Apidoc\Param("quantity", 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,
            'gift_id'=> input('gift_id'),
            'quantity'  => (int)input('quantity'),
            'denomination'  => input('denomination',0),
            'status'    =>  0
        ];
        if(!$data['gift_id']){
            return $this->error(__('Gift is incorrect'));
        }
        /** @var GiftModel $gift */
        $gift = GiftModel::where('id',$data['gift_id'])->find();
        if(!$gift){
            return $this->error(__('Gift is incorrect'));
        }
        // if(!in_array($data['denomination'],$gift->amounts)){
        //     return $this->error(__('Denomination is incorrect'));
        // }
        if($data['quantity'] < 1){
            return $this->error(__('Quantity is incorrect'));
        }
        if($gift->stock < $data['quantity']){
            return $this->error(__('Gift stock is insufficient'));
        }
        //$data['amount'] = $data['denomination'] * $data['quantity'];
        $data['denomination'] = $gift->price;
        $data['amount'] = $gift->price * $data['quantity'];

        $total_quantity_user = GiftOrderModel::where('gift_id',$gift->id)->where('user_id',$user['id'])->sum('quantity');
        
        $total_quantity_system = $gift->user_quantity ?: 99999999;
        $can_purchase = $total_quantity_system-$total_quantity_user;
        $can_purchase= $can_purchase < 0 ? 0: $can_purchase;
        if($can_purchase < $data['quantity']){
            return $this->error(__('You can only purchase %max_quantity% copies',[
                '%max_quantity%'    =>  $can_purchase
            ]));
        }
        //验证交易密码
        $trade_password = input('trade_password');
        \support\Jwt::verify_trade_password($trade_password);
        //var_dump($user);
        //验证余额
        if($data['amount'] > $user->score){
            return $this->error(__('Insufficient balance'));
        }
        Db::startTrans();
        try{
            $data = GiftOrderModel::create($data);
            $gift->stock = $gift->stock - $data['quantity'];
            $gift->sales = $gift->sales + $data['quantity'];
            $gift->save();
            UserModel::score($data['user_id'],-$data['amount'],\app\enum\BalanceType::GIFT_BUY,$data['id']);
            Hook('gift.buy',$data);
            Db::commit();
        }catch(\Exception $e){
            Db::rollback();
            return $this->error($e->getMessage());
        }
        return $this->success(__('successful'));
    }
}