<?php
namespace app\api\controller;

use app\model\Product as ProductModel;
use app\model\ProductOrder as ProductOrderModel;
use support\think\Db;
use taoser\facade\Validate;
use hg\apidoc\annotation as Apidoc;

/**
 * 产品模块
 */
class ProductController extends BaseController{
    /**
     * 不需要鉴权的方法
     * @var array
     */
    public $noNeedAuth = ['*'];
    public $noNeedLogin = ['detail','list'];
    /**
     * 列表
     * @Apidoc\Query("kw", type="string", require=false, desc="搜索关键字")
     * @Apidoc\Query("step", type="string", require=false, desc="类型,progress,done")
     * @Apidoc\Query("billing_cycle", type="int", require=true, desc="周期",default=1)
     * @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 = ProductModel::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 ProductModel $product */
        $product = ProductModel::where('id',$appid)->find();
        //->cache(true,86400,'product_detail')
        if(!$product) {
            return $this->error(__("Product does not exist"));
        }
        if($user['id']){
            $total_quantity_user = ProductOrderModel::where('product_id',$product->id)->where('user_id',$user['id'])->sum('quantity');
            
            $total_quantity_system = $product->user_quantity ?: 99999999;
            $max_quantity = $total_quantity_system-$total_quantity_user;
            $max_quantity= $max_quantity < 0 ? 0: $max_quantity;
            $product->max_quantity = $max_quantity;
            $product->total_quantity_user = $total_quantity_user;
        }else{
            $product->total_quantity_user = 0;
            $product->max_quantity = 0;
        }
        return $this->success(__('successful'),$product->toArray());
    }
}