<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use think\Validate;
use think\Config;

/**
 * 购物车接口
 */
class Car extends Api
{
    protected $carModel;

    protected function _initialize()
    {
        parent::_initialize();
        $this->carModel = new \app\api\model\Car;
    }

    /**
     * @ApiTitle    (获取购物车数量)
     * @ApiSummary  (获取购物车数量)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/car/getCarNumber)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiReturn({
    "code": 1,
    "msg": "SUCCESS",
    "time": "1587610459",
    "data": 1   购物车数量
    })
     */
    public function getCarNumber(){
        $userId = $this->getUserId();
        $where['user_id'] = $userId;

        $data = $this->carModel->where($where)->count();
        $this->success('SUCCESS',$data);
    }

    /**
     * @ApiTitle    (获取购物车列表)
     * @ApiSummary  (获取购物车列表)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/car/getCarList)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams  (name=page, type=string, required=false, description="页数")
     * @ApiReturn({
    "code": 1,
    "msg": "SUCCESS",
    "time": "1587610459",
    "data": {
    "total": 1,
    "list": [
    {
    "createtime": "1970-01-01",
    "ch_country_name": "丹麦", 原产地中文名称
    "en_country_name": "Denmark",  原产地英文名称
    "number": 3,  数量
    "goods_id": 3,  商品id
    "ch_name": "猪肉",  中文名称
    "en_name": "EMP selected",  英文名称
    "image": "http://q7s0a1rb4.bkt.clouddn.com/uploads/20200420/26f5e51b8ac7fbd6f1c649cc45a18265.png", 缩略图
    "goods_price": "60.00", 原价
    "group_price": 30, 拼团价格
    "is_group": "2"   团购:1=开启,2=关闭
    }
    ]
    }
    })
     */
    public function getCarList(){
        $userId = $this->getUserId();
        $where['c.user_id'] = $userId;

        $page = $this->request->param('page');
        $limit = Config::get('paginate.index_rows');

        $data = $this->carModel->selectPageData($where,$page,$limit,$this->lang);
        foreach ($data['list'] as $k => $v){
            $v['user_type'] = $this->user['type'];
            $data['list'][$k]['price'] = get_price_not_group($v);
        }
        $this->success('SUCCESS',$data);
    }

    /**
     * @ApiTitle    (获取购物车金额)
     * @ApiSummary  (获取购物车金额,购物车递增递减后调用此接口刷新金额)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/car/getCarMoney)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams  (name=car_id, type=string, required=false, description="购物车id 例 1,2,3")
     * @ApiReturn({
    "code": 1,
    "msg": "SUCCESS",
    "time": "1587610459",
    "data": {
        "price": 316,  折扣后价格
        "discount_price": 50,     折扣金额
        "original_price": 366     原价
    }
    })
     */
    public function getCarMoney(){
        $userId = $this->getUserId();
        $where['c.user_id'] = $userId;

        $carid = $this->request->param('car_id');
        $priceArr = $this->carModel->getCarMoney(['id'=>['in',$carid]]);
        $price = 0; //折扣后价格
        $discount_price = 0; //折扣金额
        $original_price = 0; //原价
        $data['integral'] = 0; //积分
        foreach ($priceArr as $k=>$v){
            $priceArr[$k]['user_type'] = $this->user['type'];
            $price += get_price($v);
            $discount_price += get_discount_price($v);
            $original_price += $v['goods_price'];
            if (!empty($v['integral'])) $data['integral'] += $v['integral'];
        }
        $data['price'] = round($price,2);
        $data['discount_price'] = round($discount_price,2);
        $data['original_price'] = $original_price;
        $this->success('SUCCESS',$data);
    }

    /**
     * @ApiTitle    (添加购物车)
     * @ApiSummary  (添加购物车)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/car/addCar)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams  (name=goods_id, type=string, required=true, description="商品id")
     * @ApiParams  (name=number, type=string, required=true, description="数量")
     * @ApiParams  (name=type, type=string, required=true, description="类型:1=普通商品,2=积分商品")
     * @ApiReturn({
    "code": 1,
    "msg": "SUCCESS",
    "time": "1587472510",
    "data": {
    "total": 1,
    "list": [
    {
    "content": "content",    评论内容
    "images": [
    "http://q7s0a1rb4.bkt.clouddn.com/uploads/20200420/26f5e51b8ac7fbd6f1c649cc45a18265.png"   评论图片
    ],
    "createtime": "2020-04-20",  评论日期
    "avatar": "avatar",  用户头像
    "nickname": "admin"  用户昵称
    }
    ]
    }
    })
     */
    public function addCar(){
        $userId = $this->getUserId();
        $data = $this->request->param();
        $data['user_id'] = $userId;
        $validate = new Validate([
            'goods_id' => 'require',
            'type' => 'require',
            'number' => 'require',
        ]);

        $validate->message([
            'goods_id' => '缺少参数 goods_id!',
            'type' => '缺少参数 type!',
            'number' => '缺少参数 number!',
        ]);

        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }
//        if($data['type'] == 1){
//            $is_group = Db::name('goods')->where(['id'=>$data['goods_id'],'is_group'=>1])->count();
//            if ($is_group) $this->error('团购商品不可以加入购物车');
//        }

        $stock_num = Db::name('goods')->where(['id'=>$data['goods_id']])->value('stock_num');
        if (!$stock_num) $this->error('库存不足');

        $last = $this->carModel->where(['user_id'=>$userId,'goods_id'=>$data['goods_id'],'type'=>$data['type']])->value('id');
        if ($last) $res = $this->carModel->where(['id'=>$last])->setInc('number',1);
        else $res = $this->carModel->save($data);

        if ($res) $this->success('SUCCESS');
        else $this->error('ERROR');
    }

    /**
     * @ApiTitle    (购物车数量递增)
     * @ApiSummary  (购物车数量递增)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/car/setIncCar)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams  (name=car_id, type=string, required=true, description="购物车id")
     * @ApiReturn({
    "code": 1,
    "msg": "SUCCESS",
    "time": "1587472510",
    "data": {
    }
    })
     */
    public function setIncCar(){
        $userId = $this->getUserId();
        $car_id = $this->request->param('car_id');
        if (empty($car_id)) $this->error('缺少参数 car_id!');
        $where['user_id'] = $userId;
        $where['id'] = $car_id;
        $carInfo = $this->carModel->where('id',$car_id)->find();
        $stock_num = Db::name('goods')->where(['id'=>$carInfo['goods_id']])->value('stock_num');
        if ($carInfo['number']+1>$stock_num) $this->error('库存不足');
        $res = $this->carModel->where($where)->setInc('number',1);
        if ($res) $this->success('SUCCESS');
        else $this->error('ERROR');
    }

    /**
     * @ApiTitle    (购物车数量递减)
     * @ApiSummary  (购物车数量递减)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/car/setDecCar)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams  (name=car_id, type=string, required=true, description="购物车id")
     * @ApiReturn({
    "code": 1,
    "msg": "SUCCESS",
    "time": "1587472510",
    "data": {
    }
    })
     */
    public function setDecCar(){
        $userId = $this->getUserId();
        $car_id = $this->request->param('car_id');
        if (empty($car_id)) $this->error('缺少参数 car_id!');
        $where['user_id'] = $userId;
        $where['id'] = $car_id;
        $carInfo = $this->carModel->where('id',$car_id)->find();
        if ($carInfo['number'] == 1) $this->error('不可以再减了');

        $res = $this->carModel->where($where)->setDec('number',1);
        if ($res) $this->success('SUCCESS');
        else $this->error('ERROR');
    }

    /**
     * @ApiTitle    (删除购物车)
     * @ApiSummary  (删除购物车)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/car/delCar)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams  (name=car_id, type=string, required=true, description="购物车id 批量1,2,3")
     * @ApiReturn({
    "code": 1,
    "msg": "SUCCESS",
    "time": "1587472510",
    "data": {
    }
    })
     */
    public function delCar(){
        $userId = $this->getUserId();
        $car_id = $this->request->param('car_id');
        if (empty($car_id)) $this->error('缺少参数 car_id!');

        $res = $this->carModel->where(['id'=>['in',$car_id]])->delete();
        if ($res) $this->success('SUCCESS');
        else $this->error('ERROR');
    }
}