<?php


namespace app\api\controller;


use app\api\model\GoodsSpec;
use app\common\controller\Api;
use think\Db;

/**
 * 我常买
 */
class Buy extends Api
{
    protected $noNeedRight = ['*'];

    /**
     * @ApiTitle    (我常买列表)
     * @ApiMethod   (POST)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiReturn   ({
    'code':'1',
    'msg':'返回成功'
    })
     */
    public function buyList()
    {
        $model = new \app\api\model\UserBuylist();
        $list = $model
            ->with(['goods','sku'])
            ->where('user_id',$this->auth->id)
            ->select();
        foreach ($list as $key => $value){
            $value->getRelation('goods')->visible(['goods_name','goods_id']);
            $value->getRelation('sku')->visible(['goods_spec_id','goods_price','spec_sku_id']);
        }
        $list = collection($list)->toArray();
        foreach ($list as $k => &$val){
            $skuids = explode('_', $val['sku']['spec_sku_id']);
            $sku = Db::name('litestore_spec_value')->where('id','in',$skuids)->column('spec_value');
            $skuname = !empty($sku)?implode(' ',$sku):'';
            $val['sku']['sku_name'] = $skuname;
        }
        $this->success('SUCCESS',$list);
    }

    /**
     * @ApiTitle    (价格计算)
     * @ApiSummary ([{goods_id:22 goods_sku_id:106 number:2} {goods_id:23 goods_sku_id:66 number:2}])
     * @ApiMethod   (POST)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="data_json", type="string", required=true, description="下单的商品json数据")
     * @ApiParams   (name="goods_id", type="integer", required=false, description="商品id 此值不传 json数组注释用")
     * @ApiParams   (name="goods_sku_id", type="integer", required=false, description="规格id 此值不传 json数组注释用")
     * @ApiParams   (name="number", type="integer", required=false, description="购买数量 此值不传 json数组注释用")
     * @ApiReturn   ({
    'code':'1',
    'msg':'购物车页面价格'
    'data':
    "price": "37574.00" 总价
    })
     */
    public function priceCalculation()
    {
        $json = $this->request->param('data_json');
        if (!$json) $this->error('data_json参数不能为空');
        $json = str_replace('&quot;','"',$json);
        $data = json_decode($json,true);
        $goodsmodel = new \app\api\model\Goods();
        $skumodel = new GoodsSpec();
        $sum_price = 0; //总价格
        foreach ($data as $key => $value){
            if (!is_numeric($value['goods_id']) || !is_numeric($value['goods_sku_id']) || !is_numeric($value['number'])){
                $this->error('参数不合法');
            }
            $goods = $goodsmodel->where('goods_id',$value['goods_id'])->field('goods_id,goods_name,image,spec_type')->find();
            if (!$goods) $this->error('商品不存在');
            $sku = $skumodel->where('goods_spec_id',$value['goods_sku_id'])
                ->field('goods_spec_id,spec_sku_id,goods_price')->find();
            if (!$sku) $this->error('商品规格不存在');

            $sum_price = bcadd($sum_price,bcmul($sku['goods_price'],$value['number'],2),2);
        }
        $this->success('购物车页面价格',['price'=>$sum_price]);
    }

    /**
     * @ApiTitle    (删除列表)
     * @ApiMethod   (POST)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="cart_ids", type="integer", required=true, description="列表id 逗号隔开")
     * @ApiReturn   ({
    'code':'1',
    'msg':'SUCCESS'
    })
     */
    public function delList()
    {
        $ids = $this->request->post('cart_ids');
        if (!$ids) $this->error('参数不可为空');
        $ids = explode(',',$ids);
        foreach ($ids as $key => $value){
            if (!is_numeric($value)) $this->error('参数不合法');
        }
        $model = new \app\api\model\UserBuylist();
        $model->whereIn('id',$ids)->delete();
        $this->success('SUCCESS');
    }

    /**
     * @ApiTitle    (增加购买数量)
     * @ApiMethod   (POST)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="id", type="integer", required=true, description="列表id")
     * @ApiParams   (name="number", type="integer", required=true, description="增加数量")
     * @ApiReturn   ({
    'code':'1',
    'msg':'SUCCESS'
    })
     */
    public function addBuyListNumber()
    {
        $id = $this->request->post('id');
        $number = $this->request->post('number');

        if (!is_numeric($id)  || !is_numeric($number)) $this->error('参数不合法');

        $model = new \app\api\model\UserBuylist();
        $order = $model->with('sku')->where('id',$id)->find();
        if ($number+$order['number'] > $order['sku']['stock_num']) $this->error('已达到最大库存,请勿重复提交');
        $model->where('id',$id)->setInc('number',$number);
        $this->success('SUCCESS');
    }

    /**
     * @ApiTitle    (减少购买数量)
     * @ApiMethod   (POST)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="id", type="integer", required=true, description="列表id")
     * @ApiParams   (name="number", type="integer", required=true, description="减少数量")
     * @ApiReturn   ({
    'code':'1',
    'msg':'SUCCESS'
    })
     */
    public function subBuyListNumber()
    {
        $id = $this->request->post('id');
        $number = $this->request->post('number');

        if (!is_numeric($id)  || !is_numeric($number)) $this->error('参数不合法');

        $model = new \app\api\model\UserBuylist();
        if ($model->where('id',$id)->value('number') ==1){
            $this->error('购买数量不可再减少');
        }else{
            $model->where('id',$id)->setDec('number',$number);
        }
        $this->success('SUCCESS');
    }
}