package com.bjtdba.order.controller;

import com.bjtdba.entity.order.StoreCart;
import com.bjtdba.entity.order.StoreProduct;
import com.bjtdba.entity.order.StoreProductAttrValue;
import com.bjtdba.entity.order.User;
import com.bjtdba.order.service.*;
import com.bjtdba.order.util.redis.RedisUtil;
import com.bjtdba.order.vo.MerchantVo;
import com.bjtdba.order.vo.StoreCartVo;
import com.bjtdba.utils.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("order_service/orderService/cart")
public class StoreCartController {

    @Autowired
    private StoreProductService storeProductService;
    @Autowired
    private StoreProductAttrValueService storeProductAttrValueService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private UserService userService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private StoreCartService storeCartService;


    /**
     * 该用户添加购物车商品
     * @return
     */
    @PostMapping("/create")
    public Object create(@RequestBody Map<String,String> map,@RequestHeader Map<String,String> hmap){
        if(hmap.containsKey("X-Token")){
            return ResponseUtil.fail("请求头参数错误");
        }
        if(map.containsKey("product_id")){
            return ResponseUtil.fail("product_id 参数错误");
        }
        if(map.containsKey("product_attr_unique")){
            return ResponseUtil.fail("product_attr_unique 参数错误");
        }
        if(map.containsKey("cart_num")){
            return ResponseUtil.fail("cart_num 参数错误");
        }
        if(map.containsKey("is_new")){
            return ResponseUtil.fail("is_new 参数错误");
        }
        //初始化传入的数据
        StoreCart storeCartData=new StoreCart();
        storeCartData.setProductId(Long.parseLong(map.get("product_id").toString()));
        storeCartData.setProductAttrUnique(map.get("product_attr_unique").toString());
        storeCartData.setCartNum(Integer.parseInt(map.get("cart_num").toString()));
        storeCartData.setIsNew(Integer.parseInt(map.get("is_new").toString()));

        if(Integer.parseInt(map.get("cart_num")+"")>0){
            return ResponseUtil.fail("cart_num 数量必须大于0");
        }
        //查询商品信息
        StoreProduct product=new StoreProduct();
        product= storeProductService.queryById(Long.parseLong(map.get("product_id")+""));
        if(product==null){
            return ResponseUtil.fail("商品不存在");
        }
        //查询商品属性值信息
        StoreProductAttrValue res=new StoreProductAttrValue();
        res=storeProductAttrValueService.queryById();
        if(res==null){
            return ResponseUtil.fail("SKU不存在");
        }
        if(product.getProductId()!=res.getProductId()){
            return ResponseUtil.fail("数据不一致");
        }
        if(product.getMerId().equals(148)  && map.get("is_new").equals(0)){
            return ResponseUtil.fail("积分商品不能加入购物车");
        }

        //检查该用户加入购物车商品是否满足
        User user =new User();
        if(product.getIsGiftBag()!=0){
            if(map.get("is_new").equals("0")){
                return ResponseUtil.fail("礼包商品不可加入购物车");
            }
            if(Integer.parseInt(map.get("cart_num"))>1){
                return ResponseUtil.fail("礼包商品只能购买一个");
            }

//            String token=map.get("X-Toke");
//            if(!redisUtil.hasKey("java_"+token)){
//                return  ResponseUtil.fail("用户不存在");
//            }

//            String uid=redisUtil.get("java_"+token).toString();
            String uid=hmap.get("uid");
            user=userService.queryById(Long.parseLong(uid));

            if(user!=null&&user.getIsPromoter().equals(1)){
                return ResponseUtil.fail("'您已经是分销员了'");
            }else{
                return  ResponseUtil.fail("'用户不存在'");
            }
        }


        if(product.getProductType()==1){
//            if(product.getEndTime) endtiem不存在
            Integer  count=orderService.seckillOrderCounut(map.get("product_id")+"",null);
            if(Integer.parseInt(map.get("is_new"))!=1){
                return ResponseUtil.fail("秒杀商品不能加入购物车");
            }
            if(Integer.parseInt(map.get("cart_num"))>1){
                return ResponseUtil.fail("秒杀商品只能购买一个");
            }
            if(res.getStock()<=count){
                return ResponseUtil.fail("限购数量不足");
            }
            StoreProductAttrValue storeProductAttrValue=new StoreProductAttrValue();
            storeProductAttrValue.setProductId(Long.parseLong(product.getOldProductId()+""));
            storeProductAttrValue.setSku(res.getSku());
            List<StoreProductAttrValue> storeProductAttrValueList=storeProductAttrValueService.queryAllByList(storeProductAttrValue);
            if(storeProductAttrValueList!=null&&storeProductAttrValueList.size()!=0){
                StoreProductAttrValue sku=storeProductAttrValueList.get(0);
                if(sku.getStock()<=0){
                    return ResponseUtil.fail("原库存不足");
                }
            }else {
                return ResponseUtil.fail("原商品SKU不存在");
            }
            int getDayPayCount =orderService.getDayPayCount(Long.parseLong(map.get("product_id").toString()),user.getUid());
            if(getDayPayCount!=1){
                return ResponseUtil.fail("您的本次活动购买数量上限");
            }
            int getPayCount=orderService.getPayCount(Long.parseLong(map.get("product_id").toString()),user.getUid());
            if(getPayCount!=1){
                return ResponseUtil.fail("您的该商品购买数量上限");
            }
        }

        StoreCart queryStoreCart=new StoreCart();
        queryStoreCart.setUid(user.getUid());
        queryStoreCart.setProductAttrUnique(map.get("product_attr_unique").toString());
        List<StoreCart> storeCartList=storeCartService.queryByPage(queryStoreCart);

        //不是礼包，不是立即购买，不是秒杀商品，购物车存在
        if(product.getIsGiftBag()==0 && storeCartData.getIsNew()==0 && product.getProductType()==0 && storeCartList!=null&&storeCartList.size()!=0){
            StoreCart storeCart=storeCartList.get(0);
            if(res.getStock()<(storeCart.getCartNum()+storeCartData.getCartNum())){
                return ResponseUtil.fail("库存不足");
            }
            storeCart.setCartNum(storeCart.getCartNum()+storeCartData.getCartNum());
            storeCartService.update(storeCart);
        }else {

            if(res.getStock()<storeCartData.getCartNum()){
                return ResponseUtil.fail("库存不足");
            }
            storeCartData.setSource(0);
            storeCartData.setProductType(product.getProductType());
            storeCartService.insert(storeCartData);


        }

        return  ResponseUtil.ok();
    }


    /**
     * 通过购车id删除购物车商品
     * @param map
     * @param hmap
     * @return
     */
    @PostMapping("/delete")
    public Object delete(@RequestBody Map<String,String> map,@RequestHeader Map<String,String> hmap){
        if(hmap.containsKey("X-Token")){
            return ResponseUtil.fail("请求头参数错误");
        }

        if (map.containsKey("cart_id")){
            return  ResponseUtil.fail("cart_id请求参数错误");
        }
        Long uid=Long.parseLong(redisUtil.get("X-Token").toString());
        String [] cartIds=map.get("cart_id").toString().split(",");
        if(storeCartService.batchDelete(cartIds,uid)){
            return  ResponseUtil.ok("删除成功");
        }else{
            return  ResponseUtil.fail("删除失败");
        }


    }

    @PostMapping("/lst")
    public Object lst(@RequestBody Map<String,String> map){
        Map<String,Object> data=new HashMap<String,Object>();
        if(!map.containsKey("uid")){
            return ResponseUtil.fail("请求参数错误");
        }
//        Long uid=Long.parseLong(redisUtil.get("X-Token").toString());
        Long uid=Long.parseLong(map.get("uid"));
        Integer[] merids=storeCartService.getMerids(uid);
        List<MerchantVo> list=new ArrayList<MerchantVo>();
        if (merids.length==0) {
            data.put("list",list);
            return ResponseUtil.ok("list",list);

        }
        //装载数据
        list = storeCartService.getMerchantVo(merids);//对应的所有商户
        List<StoreCartVo> storeCartVoList=new ArrayList<StoreCartVo>();
        storeCartVoList=storeCartService.queryByuid(uid);

        for (MerchantVo mercantvo:list) {

            for (StoreCartVo storeCartVo:storeCartVoList) {
                //同一个商户的商品放在一起
                Integer vmerid=Integer.parseInt(storeCartVo.getMer_id()+"");
                if(mercantvo.getMer_id().equals(vmerid)){
                    StoreProduct storeProduct=storeProductService.queryById(storeCartVo.getProduct_id());
                    BigDecimal yanglao=new BigDecimal(0);
                    //获取养老金数据
                    yanglao=storeProductService.yanglaojin(storeProduct,null,null);
                    storeCartVo.setYanglao(yanglao);
                    mercantvo.getList().add(storeCartVo);
                }
            }
        }


        data.put("list",list);
        return ResponseUtil.ok(data);

    }

    /**
     * 修改购物车数量
     * @param id
     * @param map
     * @return
     */
    @PostMapping("/change/{id}")
    public Object change(@PathVariable Long id,@RequestBody Map<String,String> map){
        if(!map.containsKey("cart_num")){
            return ResponseUtil.fail("cart_num 请求参数错误");
        }
        if(!map.containsKey("uid")){
            return ResponseUtil.fail("请求参数错误");
        }
        Integer cart_num=Integer.parseInt(map.get("cart_num")+"");
        if(cart_num<0){
            return ResponseUtil.fail("数量必须大于0");
        }
        Long uid=Long.parseLong(map.get("uid"));
        StoreCartVo storeCartVo=storeCartService.queryByUidCartId(uid,id);
        if(storeCartVo==null){
            return ResponseUtil.fail("购物车信息不存在");
        }
        StoreProductAttrValue storeProductAttrValue=storeProductAttrValueService.queryByunique(storeCartVo.getProduct_attr_unique());
        if(storeProductAttrValue==null){
            return ResponseUtil.fail("SKU不存在");
        }
        if(storeProductAttrValue.getStock()<cart_num){
            return ResponseUtil.fail("库存不足");
        }
        StoreCart storeCart=new StoreCart();
        storeCart.setCartId(storeCartVo.getCart_id());
        storeCart.setCartNum(storeCartVo.getCart_num());
        storeCartService.update(storeCart);
        return ResponseUtil.ok("修改成功");
    }


}
