<?php
namespace app\api\controller;

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

/**
 * 我的产品
 */
class ProductOrderController extends BaseController{
    /**
     * 不需要鉴权的方法
     * @var array
     */
    public $noNeedAuth = ['*'];
    public $noNeedLogin = [];
    /**
     * 列表
     * @Apidoc\Query("step", 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);
        $page = (int)input('page',1);
        $step = (int)input('step',0);
        $user_id = \support\Jwt\JwtToken::getCurrentId();
        $model = ProductOrderModel::with(['product'])->where('user_id',$user_id);
        if($step){
            $ids = \app\model\WorkRecord::where('user_id',$user_id)
                ->distinct(true)
                ->where('status',$step)
                ->column('order_id');
            $model = $model->whereIn('id',$ids);
        }
        $list = $model->where('status',1)
            ->order('created_at desc')
            ->paginate($limit);
        $list->each(function($item)use($step){
            //$_step=1;
            if($step){
                $_step = $step;
            }else{
                $_step = \app\model\WorkRecord::where('order_id',$item->id)
                    ->order('status','asc')
                    ->limit(0,1)
                    ->value('status');
            }
            $item->step = $_step;
            return $item;
        });
        return $this->success(__('successful'),$list->toArray());
    }
    /**
     * 购买产品
     * @Apidoc\Method("POST")
     * @Apidoc\Param("product_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();
        //验证交易密码
        $trade_password = input('trade_password');
        \support\Jwt::verify_trade_password($trade_password);
        $data = [
            'user_id'   => $user->id,
            'product_id'=> input('product_id'),
            'quantity'  => (int)input('quantity'),
            'accelerate'  => input('accelerate'),
            'status'    =>  1
        ];
        if(!$data['product_id']){
            return $this->error(__('Product is incorrect'));
        }
        if($data['quantity'] < 1){
            return $this->error(__('Quantity is incorrect'));
        }
        if($data['product_id'] == 12){
            $exsit = ProductOrderModel::where('product_id',$data['product_id'])->where('user_id',$data['user_id'])->count('id');
            if($exsit != 0){
                return $this->error(__('微量包每个用户只能购买一个'));
            }
            if($data['quantity'] != 1){
                return $this->error(__('微量包每个用户只能购买一个'));
            }
        }
        
        /** @var ProductModel $product */
        $product = ProductModel::where('id',$data['product_id'])->find();
        if(!$product){
            return $this->error(__('Product is incorrect'));
        }
        /*
        if ($product->start_time > time() || $product->end_time < time()) {
            return $this->error(__('Can\'t buy now'));
        }
        */
        //return $this->success(__('successful'),[$product->start_time]);
        $data['price'] = $product['price'];
        if($data['accelerate']){
            $data['price'] += $product['accelerate_price'];
            $data['accelerate_times'] = $product['accelerate_assign_times'];
            $data['accelerate_used'] = 0;
        }
        $data['amount'] = $data['price'] * $data['quantity'];
        $data['total'] = $product['total'] * $data['quantity'];
        $data['assigned'] = 0;
		/*
        $total_quantity_user = ProductOrderModel::where('product_id',$product->id)->where('user_id',$user['id'])->sum('quantity');
        
        $total_quantity_system = $product->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
            ]));
        }
        */
        //var_dump($user);
        //验证余额
        if($data['amount'] > $user->money){
            return $this->error(__('Insufficient balance'));
        }
        Db::startTrans();
        try{
            $data = ProductOrderModel::create($data);
            $product->sales = $product->sales + $data['quantity'];
            $product->save();
            UserModel::money($data['user_id'],-$data['amount'],\app\enum\BalanceType::PRODUCT_BUY,$data['id']);
            Hook('product.buy',$data);
            Db::commit();
        }catch(\Exception $e){
            Db::rollback();
            return $this->error($e->getMessage());
        }
        return $this->success(__('successful'));
    }
}