package com.kmall.api.api;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.kmall.api.annotation.LoginUser;
import com.kmall.common.constant.Dict;
import com.kmall.api.entity.*;
import com.kmall.api.service.*;
import com.kmall.api.util.ApiBaseAction;
import com.kmall.common.utils.Constant;
import com.kmall.common.utils.MapUtils;
import com.qiniu.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

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

/**
 * 作者: @author Scott <br>
 * 时间: 2017-08-11 08:32<br>
 * 描述: ApiIndexController <br>
 */
@RestController
@RequestMapping("/api/cart")
public class ApiCartController extends ApiBaseAction {
    @Autowired
    private ApiCartService cartService;
    @Autowired
    private ApiGoodsService goodsService;
    @Autowired
    private ApiProductService productService;
    @Autowired
    private ApiAddressService addressService;
    @Autowired
    private ApiCouponService apiCouponService;
    @Autowired
    private ApiUserCouponService apiUserCouponService;
    @Autowired
    private ApiOrderGoodsService apiOrderGoodsService;
    @Autowired
    private ApiUserService apiUserService;

    @Autowired
    private ApiFreightService apiFreightService;
    @Autowired
    private ApiThirdMerchantBizService apiThirdMerchantBizService;
    @Autowired
    private ApiStoreService apiStoreService;

    /**
     * 获取购物车中的数据
     */
    @GetMapping("getCartMoney")
    public Object getCartMoney(@LoginUser UserVo loginUser, String checkCart) {
        Long storeId = getStoreId();
        Map<String, Object> resultObj = Maps.newHashMap();
        //查询列表数据
        Map param = Maps.newHashMap();
        param.put("user_id", loginUser.getId());
        param.put("store_id", storeId);
        param.put("checkCart",checkCart);
        param.putAll(setIsStockShare(storeId));
        List<CartVo> cartList = cartService.queryList(param);
        //获取购物车统计信息
        Integer goodsCount = 0;
        BigDecimal goodsAmount = new BigDecimal(0.00);
        Integer checkedGoodsCount = 0;
        BigDecimal checkedGoodsAmount = new BigDecimal(0.00);
        for (CartVo cartItem : cartList) {
            goodsCount += cartItem.getNumber();
            goodsAmount = goodsAmount.add(cartItem.getRetail_price().multiply(new BigDecimal(cartItem.getNumber())));
            if (null != cartItem.getChecked() && 1 == cartItem.getChecked()) {
                checkedGoodsCount += cartItem.getNumber();
                checkedGoodsAmount = checkedGoodsAmount.add(cartItem.getRetail_price().multiply(new BigDecimal(cartItem.getNumber())));
            }
        }

        resultObj.put("cartList", cartList);
        //
        Map<String, Object> cartTotal = Maps.newHashMap();
        cartTotal.put("goodsCount", goodsCount);
        cartTotal.put("goodsAmount", goodsAmount);
        cartTotal.put("checkedGoodsCount", checkedGoodsCount);
        cartTotal.put("checkedGoodsAmount", checkedGoodsAmount);
        //
        resultObj.put("cartTotal", cartTotal);
        return resultObj;
    }

    private Map setIsStockShare(Long storeId){
        Map param = Maps.newHashMap();
        StoreVo storeVo = apiStoreService.queryObject(storeId);
        if(storeVo != null) {
            ThirdMerchantBizVo thirdMerchantBiz = apiThirdMerchantBizService.getThirdMerchangByCode(storeVo.getThirdPartyMerchCode());
            if (null == thirdMerchantBiz) {
                return toResponsFail("第三方商户为空");
            }
            param.put("isStockShare", thirdMerchantBiz.getIsStockShare());
        }
        return param;
    }

    /**
     * 获取购物车中的数据
     */
    @GetMapping("getCart")
    public Object getCart(String checkCart,Long storeId) {
        UserVo loginUser = new UserVo();
        loginUser.setId(getUserId());
        Map<String, Object> resultObj = Maps.newHashMap();
        //查询列表数据
        Map param = Maps.newHashMap();
        param.put("user_id", loginUser.getId());
        storeId = getStoreId();
        param.put("store_id", storeId);
        param.put("merchSn", getMerchSn());
        param.put("checkCart", checkCart);
        param.putAll(setIsStockShare(storeId));
        List<CartVo> cartList = cartService.queryList(param);
        List<CartVo> validCartList = cartService.queryValidCartList(param);
        //获取购物车统计信息
        Integer goodsCount = 0;
        BigDecimal goodsAmount = new BigDecimal(0.00);
        Integer checkedGoodsCount = 0;
        BigDecimal checkedGoodsAmount = new BigDecimal(0.00);
        List<CartVo> cart00List = new ArrayList<>();
        List<CartVo> cart02List = new ArrayList<>();
        List<CartVo> cart10List = new ArrayList<>();
        List<CartVo> cart11List = new ArrayList<>();
        for (CartVo cartItem : cartList) {
            goodsCount += cartItem.getNumber();
            goodsAmount = goodsAmount.add(cartItem.getRetail_price().multiply(new BigDecimal(cartItem.getNumber())));
            if (null != cartItem.getChecked() && 1 == cartItem.getChecked()) {
                checkedGoodsCount += cartItem.getNumber();
                checkedGoodsAmount = checkedGoodsAmount.add(cartItem.getRetail_price().multiply(new BigDecimal(cartItem.getNumber())));
            }
            if(org.apache.commons.lang.StringUtils.isNotEmpty(cartItem.getGoodsBizType())){
                cartItem.setGoodsBizTypeName(Dict.orderBizType.valueOf("item_"+ cartItem.getGoodsBizType()).getItemName());
            }else{
                cartItem.setGoodsBizTypeName("");
            }

            if(Dict.orderBizType.item_00.getItem().equalsIgnoreCase(cartItem.getGoodsBizType())){
                CartVo cartVo00= cartItem;
                cart00List.add(cartVo00);
            }
            if(Dict.orderBizType.item_02.getItem().equalsIgnoreCase(cartItem.getGoodsBizType())){
                CartVo cartVo02= cartItem;
                cart02List.add(cartVo02);
            }
            if(Dict.orderBizType.item_10.getItem().equalsIgnoreCase(cartItem.getGoodsBizType())){
                CartVo cartVo10= cartItem;
                cart10List.add(cartVo10);
            }
            if(Dict.orderBizType.item_11.getItem().equalsIgnoreCase(cartItem.getGoodsBizType())){
                CartVo cartVo11= cartItem;
                cart11List.add(cartVo11);
            }

        }
        // 获取优惠信息提示 邮费
        CouponVo shippingCoupon = apiCouponService.matchShippingSign(loginUser.getId(), checkedGoodsAmount);

        // 获取优惠信息提示 满减
        CouponVo fullSubCoupon = apiCouponService.matchFullSubSign(loginUser.getId(), checkedGoodsAmount);

        List<CouponVo> couponInfoList = new ArrayList();
        if (null != shippingCoupon) {
            couponInfoList.add(shippingCoupon);
        }
        if (null != fullSubCoupon) {
            couponInfoList.add(fullSubCoupon);
        }

        resultObj.put("couponInfoList", couponInfoList);

        resultObj.put("cart00List", cart00List);//{'cartList':{'type': '保税备货','data':{}}}
        resultObj.put("cart02List", cart02List);
        resultObj.put("cart10List", cart10List);
        resultObj.put("cart11List", cart11List);
        resultObj.put("cartList", cartList);
        resultObj.put("validCartList", validCartList);
        //
        Map<String, Object> cartTotal = Maps.newHashMap();
        cartTotal.put("goodsCount", goodsCount);
        cartTotal.put("goodsAmount", goodsAmount);
        cartTotal.put("checkedGoodsCount", checkedGoodsCount);
        cartTotal.put("checkedGoodsAmount", checkedGoodsAmount);
        resultObj.put("cartTotal", cartTotal);

        param.put("checkCart","00");
        int total00 = cartService.queryTotal(param);
        param.put("checkCart","11");
        int total11 = cartService.queryTotal(param);
        resultObj.put("total00", total00);
        resultObj.put("total11", total11);
        return resultObj;
    }

    /**
     * 获取购物车中的数据，底部显示
     */
    @GetMapping("getFootCart")
    public Object getFootCart(@LoginUser UserVo loginUser) {
        Map<String, Object> resultObj = Maps.newHashMap();
        //查询列表数据
        Map param = Maps.newHashMap();
        param.put("user_id", loginUser.getId());
        Long storeId = getStoreId();
        param.put("store_id", storeId);
        param.putAll(setIsStockShare(storeId));
        List<CartVo> cartList = cartService.queryList(param);
        //获取购物车统计信息
        Integer goodsCount = 0;
        BigDecimal goodsAmount = new BigDecimal(0.00);
        Integer checkedGoodsCount = 0;
        BigDecimal checkedGoodsAmount = new BigDecimal(0.00);
        for (CartVo cartItem : cartList) {
            goodsCount += 1;
            goodsAmount = goodsAmount.add(cartItem.getRetail_price().multiply(new BigDecimal(cartItem.getNumber())));
            if (null != cartItem.getChecked() && 1 == cartItem.getChecked()) {
                checkedGoodsCount += cartItem.getNumber();
                checkedGoodsAmount = checkedGoodsAmount.add(cartItem.getRetail_price().multiply(new BigDecimal(cartItem.getNumber())));
            }
        }
        //
        resultObj.put("goodsCount", goodsCount);
        resultObj.put("goodsAmount", goodsAmount);
        resultObj.put("checkedGoodsCount", checkedGoodsCount);
        resultObj.put("checkedGoodsAmount", checkedGoodsAmount);
        //
        return toResponsSuccess(resultObj);
    }


    /**
     * 获取购物车信息，所有对购物车的增删改操作，都要重新返回购物车的信息
     */
    @GetMapping("indexs")
    public Object indexs(String checkCart,Long storeId) {
        return toResponsSuccess(getCart(checkCart,storeId));
    }

    /**
     * 添加商品到购物车
     */
    @PostMapping("add")
    public Object add(@LoginUser UserVo loginUser) {
        JSONObject jsonParam = getJsonRequest();
        Long goodsId = jsonParam.getLong("goodsId");
        Long productId = jsonParam.getLong("productId");
        Integer number = jsonParam.getInteger("number");
        String checkCart = jsonParam.getString("checkCart");
        //判断商品是否可以购买
        GoodsVo goodsInfo = goodsService.queryObjectByStoreId(goodsId, getStoreId());
        if (null == goodsInfo || goodsInfo.getIs_delete() == 1 || goodsInfo.getIs_on_sale() == 0) {
            return toResponsFail("商品已下架");
        }
        Long storeId = getStoreId();
        //取得规格的信息,判断规格库存
        /*ProductVo productInfo = productService.queryObjectByStoreId(productId, storeId);
        if (null == productInfo) {
            return toResponsFail("商品已下架");
        }
        if(productInfo.getStock_num() <= 0){
            return toResponsFail("库存不足");
        }*/
        ProductVo productInfo = productService.queryByStoreId(productId, storeId);
        if (null == productInfo) {
            return toResponsFail("商品已下架");
        }
        Integer stockNum = 0;
        ThirdMerchantBizVo thirdMerchantBizVo = apiThirdMerchantBizService.getThirdMerchangByCode(goodsInfo.getThirdPartyMerchCode());
        if(null == thirdMerchantBizVo){
            return toResponsFail("商品已下架");
        }
        //// TODO: 2019/3/5  普通商品不受共享库存影响，直接取门店配置库存
        if(goodsInfo.getGoodsBizType().equalsIgnoreCase(Dict.orderBizType.item_11.getItem())
                || goodsInfo.getGoodsBizType().equalsIgnoreCase(Dict.orderBizType.item_02.getItem())
                || goodsInfo.getGoodsBizType().equalsIgnoreCase(Dict.orderBizType.item_10.getItem())){
            stockNum = productInfo.getStock_num();
        }
        if(goodsInfo.getGoodsBizType().equalsIgnoreCase(Dict.orderBizType.item_00.getItem())){
            if (thirdMerchantBizVo.getIsStockShare().equalsIgnoreCase(Dict.isStockShare.item_1.getItem())){
                stockNum = goodsInfo.getGoods_number();
            }
            if (thirdMerchantBizVo.getIsStockShare().equalsIgnoreCase(Dict.isStockShare.item_0.getItem())){
                stockNum = productInfo.getStock_num();
            }
        }
        if(stockNum == null || number > stockNum || stockNum <= 0){
            return toResponsFail("该商品库存不足");
        }
        if (null == productInfo.getRetail_price()) {
            productInfo.setRetail_price(goodsInfo.getRetail_price());
            productInfo.setMarket_price(goodsInfo.getMarket_price());
        }
        //判断购物车中是否存在此规格商品
        Map cartParam = Maps.newHashMap();
        cartParam.put("goods_id", goodsId);
        cartParam.put("product_id", productId);
        cartParam.put("user_id", loginUser.getId());
        cartParam.put("store_id", storeId);
        cartParam.put("isStockShare", thirdMerchantBizVo.getIsStockShare());
        List<CartVo> cartInfoList = cartService.queryList(cartParam);
        CartVo cartInfo = null != cartInfoList && cartInfoList.size() > 0 ? cartInfoList.get(0) : null;
        if (null == cartInfo) {//添加规格名和值
            cartInfo = new CartVo();

            cartInfo.setGoods_id(goodsId);
            cartInfo.setProduct_id(productId);
            cartInfo.setGoods_sn(productInfo.getGoods_sn());
            cartInfo.setGoods_name(goodsInfo.getName());
            cartInfo.setList_pic_url(goodsInfo.getList_pic_url());
            cartInfo.setNumber(number);
            cartInfo.setStore_id(storeId);
            cartInfo.setUser_id(loginUser.getId());
            cartInfo.setRetail_price(productInfo.getRetail_price());
            cartInfo.setMarket_price(productInfo.getMarket_price());
            cartInfo.setGoods_specification_name_value(productInfo.getGoods_specification_name_value());
            cartInfo.setGoods_specification_ids(productInfo.getGoods_specification_ids());
            cartInfo.setChecked(1);
            cartInfo.setGoodsBizType(goodsInfo.getGoodsBizType());//业务类型
            cartInfo.setStockNum(stockNum);
            cartInfo.setMerchSn(goodsInfo.getMerchSn());
            cartInfo.setSku(goodsInfo.getSku());
            cartService.save(cartInfo);
        } else {
            if(number + cartInfo.getNumber() > stockNum){
                return toResponsFail("商品选购数量（含购物车已加购数量）已超过库存");
            }
            cartInfo.setNumber(cartInfo.getNumber() + number);
            cartInfo.setGoodsBizType(goodsInfo.getGoodsBizType());//业务类型
            cartInfo.setStockNum(stockNum);
            cartInfo.setSku(goodsInfo.getSku());
            cartService.update(cartInfo);
        }
        return toResponsSuccess(getCart(checkCart,storeId));
    }

    /**
     * 添加商品到购物车
     */
    @PostMapping("addByGoodsId")
    public Object addByGoodsId(@LoginUser UserVo loginUser) {
        JSONObject jsonParam = getJsonRequest();
        Long goodsId = jsonParam.getLong("goodsId");
        String checkCart = jsonParam.getString("checkCart");
        //判断商品是否可以购买
        GoodsVo goodsInfo = goodsService.queryObjectByStoreId(goodsId, getStoreId());
        if (null == goodsInfo || goodsInfo.getIs_delete() == 1 || goodsInfo.getIs_on_sale() == 0) {
            return toResponsFail("商品已下架");
        }
        Long storeId = getStoreId();
        Map resultObj = cartService.addByGoodsId(getUserId(), goodsId, storeId);
        if (0 != MapUtils.getInteger("errno", resultObj)) {
            return toResponsObject(MapUtils.getInteger("errno", resultObj), MapUtils.getString("errmsg", resultObj), "");
        }
        return toResponsSuccess(getCart(checkCart,storeId));
    }

    /**
     * 根据订单号添加商品到购物车
     */
    @GetMapping("addByOrder")
    public Object addByOrder(@LoginUser UserVo loginUser, Long orderId) {
        JSONObject jsonParam = getJsonRequest();
        //
        Map params = Maps.newHashMap();
        params.put("order_id", orderId);
        List<OrderGoodsVo> orderGoodsVos = apiOrderGoodsService.queryList(params);
        Integer stockNum = 0;
        Long storeId = getStoreId();
        for (OrderGoodsVo goodsVo : orderGoodsVos) {
            //判断商品是否可以购买
            ProductVo productInfo = productService.queryByStoreId(goodsVo.getProduct_id(), storeId);
            if (null == productInfo) {
                return toResponsFail("商品已下架");
            }
            GoodsVo goodsInfo = goodsService.queryObjectByStoreId(goodsVo.getGoods_id(), getStoreId());
            if (null == goodsInfo || goodsInfo.getIs_delete() == 1 || goodsInfo.getIs_on_sale() == 0) {
                return toResponsFail("商品已下架");
            }
            // TODO: 2019/3/5  普通商品不受共享库存影响，直接取门店配置库存
            if(goodsInfo.getGoodsBizType().equalsIgnoreCase(Dict.orderBizType.item_11.getItem())
                    || goodsInfo.getGoodsBizType().equalsIgnoreCase(Dict.orderBizType.item_02.getItem())
                    || goodsInfo.getGoodsBizType().equalsIgnoreCase(Dict.orderBizType.item_10.getItem())){
                stockNum = productInfo.getStock_num();
            }
            if(goodsInfo.getGoodsBizType().equalsIgnoreCase(Dict.orderBizType.item_00.getItem())) {
                if (goodsInfo.getIsStockShare().equalsIgnoreCase(Dict.isStockShare.item_1.getItem())) {
                    stockNum = goodsInfo.getGoods_number();
                }
                if (goodsInfo.getIsStockShare().equalsIgnoreCase(Dict.isStockShare.item_0.getItem())) {
                    stockNum = productInfo.getStock_num();
                }
            }
            if(stockNum == null || goodsVo.getNumber() > stockNum || stockNum <= 0){
                return toResponsFail("该商品库存不足");
            }
            CartVo cartInfo = new CartVo();
            cartInfo.setGoods_id(goodsVo.getGoods_id());
            cartInfo.setProduct_id(goodsVo.getProduct_id());
            cartInfo.setGoods_sn(goodsVo.getGoods_sn());
            cartInfo.setGoods_name(goodsVo.getGoods_name());
            cartInfo.setList_pic_url(goodsVo.getList_pic_url());
            cartInfo.setNumber(goodsVo.getNumber());
            cartInfo.setStore_id(storeId);
            cartInfo.setUser_id(getUserId());
            cartInfo.setRetail_price(goodsVo.getRetail_price());
            cartInfo.setMarket_price(goodsVo.getMarket_price());
            cartInfo.setGoods_specification_name_value(goodsVo.getGoods_specification_name_value());
            cartInfo.setGoods_specification_ids(goodsVo.getGoods_specification_ids());
            cartInfo.setChecked(1);
            cartInfo.setGoodsBizType(goodsVo.getOrderBizType());
            cartInfo.setStockNum(stockNum);
            cartInfo.setMerchSn(goodsVo.getMerchSn());
            cartInfo.setSku(goodsVo.getSku());

            Map map = Maps.newHashMap();
            map.put("user_id", getUserId());
            map.put("store_id", getStoreId());
            map.put("goods_id",goodsVo.getGoods_id());
            map.put("product_id",goodsVo.getProduct_id());
            map.put("number",goodsVo.getNumber());
            map.put("isStockShare", goodsInfo.getIsStockShare());
            List<CartVo> list= cartService.queryList(map);
            if(list != null && list.size() > 0){
                for (CartVo vo:list) {
                    cartInfo.setId(vo.getId());
                    cartService.update(cartInfo);
                }
            }else{
                cartService.save(cartInfo);
            }

        }
        return toResponsSuccess("添加成功");
    }


    /**
     * 减少商品到购物车
     */
    @PostMapping("minus")
    public Object minus(@LoginUser UserVo loginUser) {
        JSONObject jsonParam = getJsonRequest();
        Integer goodsId = jsonParam.getInteger("goodsId");
        Integer productId = jsonParam.getInteger("productId");
        Integer number = jsonParam.getInteger("number");

        GoodsVo goodsInfo = goodsService.queryObjectByStoreId(Long.valueOf(goodsId), getStoreId());
        if (null == goodsInfo || goodsInfo.getIs_delete() == 1 || goodsInfo.getIs_on_sale() == 0) {
            return toResponsFail("商品已下架");
        }
        ThirdMerchantBizVo thirdMerchantBiz = apiThirdMerchantBizService.getThirdMerchangByCode(goodsInfo.getThirdPartyMerchCode());
        if(null == thirdMerchantBiz){
            return toResponsFail("商品已下架");
        }
        /*if (thirdMerchantBiz.getIsStockShare().equalsIgnoreCase(Dict.isStockShare.item_1.getItem())){
            stockNum = goodsInfo.getGoods_number();
        }
        if (thirdMerchantBiz.getIsStockShare().equalsIgnoreCase(Dict.isStockShare.item_0.getItem())){
            stockNum = productInfo.getStock_num();
        }*/
        //判断购物车中是否存在此规格商品
        Map cartParam = Maps.newHashMap();
        cartParam.put("goods_id", goodsId);
        cartParam.put("product_id", productId);
        Long storeId = getStoreId();
        cartParam.put("store_id", storeId);
        cartParam.put("user_id", loginUser.getId());
        cartParam.put("isStockShare", thirdMerchantBiz.getIsStockShare());
        List<CartVo> cartInfoList = cartService.queryList(cartParam);
        CartVo cartInfo = null != cartInfoList && cartInfoList.size() > 0 ? cartInfoList.get(0) : null;
        int cart_num = 0;
        if (null != cartInfo) {
            if (cartInfo.getNumber() > number) {
                cartInfo.setNumber(cartInfo.getNumber() - number);
                cartService.update(cartInfo);
                cart_num = cartInfo.getNumber();
            } else if (cartInfo.getNumber() == 1) {
                cartService.delete(cartInfo.getId());
                cart_num = 0;
            }
        }
        return toResponsSuccess(cart_num);
    }

    /**
     * 更新指定的购物车信息
     */
    @PostMapping("update")
    public Object update(@LoginUser UserVo loginUser) {
        JSONObject jsonParam = getJsonRequest();
        Long goodsId = jsonParam.getLong("goodsId");
        Long storeId = getStoreId();
        Long productId = jsonParam.getLong("productId");
        Integer number = jsonParam.getInteger("number");
        Integer id = jsonParam.getInteger("id");
        String checkCart = jsonParam.getString("checkCart");
        boolean isAdd = true;
        Integer stockNum = 0;
        GoodsVo goodsInfo = goodsService.queryObjectByStoreId(Long.valueOf(goodsId), getStoreId());
        if (null == goodsInfo || goodsInfo.getIs_delete() == 1 || goodsInfo.getIs_on_sale() == 0) {
            return toResponsFail("商品已下架");
        }
        //取得规格的信息,判断规格库存
        ProductVo productInfo = productService.queryByStoreId(productId, storeId);
        if (null == productInfo) {
            return this.toResponsObject(400, "商品已下架", getCart(checkCart,storeId));
        }
        ThirdMerchantBizVo thirdMerchantBiz = apiThirdMerchantBizService.getThirdMerchangByCode(goodsInfo.getThirdPartyMerchCode());
        if(null == thirdMerchantBiz){
            return toResponsFail("商品已下架");
        }
        // TODO: 2019/3/5  普通商品不受共享库存影响，直接取门店配置库存
        if(goodsInfo.getGoodsBizType().equalsIgnoreCase(Dict.orderBizType.item_11.getItem())
                || goodsInfo.getGoodsBizType().equalsIgnoreCase(Dict.orderBizType.item_02.getItem())
                || goodsInfo.getGoodsBizType().equalsIgnoreCase(Dict.orderBizType.item_10.getItem())){
            stockNum = productInfo.getStock_num();//门店库存
        }
        if(goodsInfo.getGoodsBizType().equalsIgnoreCase(Dict.orderBizType.item_00.getItem())){
            if (thirdMerchantBiz.getIsStockShare().equalsIgnoreCase(Dict.isStockShare.item_1.getItem())){
                stockNum = goodsInfo.getGoods_number();
            }
            if (thirdMerchantBiz.getIsStockShare().equalsIgnoreCase(Dict.isStockShare.item_0.getItem())){
                stockNum = productInfo.getStock_num();
            }
        }
        if(stockNum == null || number > stockNum || stockNum <= 0){
            return this.toResponsObject(400, "该商品库存不足", getCart(checkCart,storeId));
        }
        String msg = "";
//        if (productInfo.getStock_num() < number) {
//            msg = "库存不足,仅剩余" + productInfo.getStock_num();
//            number = productInfo.getStock_num();
////            return this.toResponsObject(400, "库存不足,仅剩余" + productInfo.getStock_num(), "");
//        }
        //判断是否已经存在product_id购物车商品
        CartVo cartInfo = cartService.queryObject(id);
        //只是更新number
        if (cartInfo.getProduct_id().equals(productId)) {
            cartInfo.setNumber(number);
            cartInfo.setStockNum(stockNum);
            cartService.update(cartInfo);
            return toResponsObject(0, msg, getCart(checkCart,storeId));
        }

        Map cartParam = Maps.newHashMap();
        cartParam.put("goodsId", goodsId);
        cartParam.put("productId", productId);
        cartParam.put("store_id", storeId);
        cartParam.put("isStockShare", thirdMerchantBiz.getIsStockShare());
        List<CartVo> cartInfoList = cartService.queryList(cartParam);
        CartVo newcartInfo = null != cartInfoList && cartInfoList.size() > 0 ? cartInfoList.get(0) : null;
        if (null == newcartInfo) {
            cartInfo.setProduct_id(productId);
            cartInfo.setGoods_sn(productInfo.getGoods_sn());
            cartInfo.setNumber(number);
            cartInfo.setRetail_price(productInfo.getRetail_price());
            cartInfo.setMarket_price(productInfo.getRetail_price());
            cartInfo.setGoods_specification_name_value(productInfo.getGoods_specification_name_value());
            cartInfo.setGoods_specification_ids(productInfo.getGoods_specification_ids());
//            cartInfo.setSku(goodsVo.getSku());
            cartService.update(cartInfo);
        } else {
            //添加规格名和值
            cartInfo.setProduct_id(productId);
            cartInfo.setGoods_sn(productInfo.getGoods_sn());
            cartInfo.setNumber(number);
            cartInfo.setRetail_price(productInfo.getRetail_price());
            cartInfo.setMarket_price(productInfo.getRetail_price());
            cartInfo.setGoods_specification_name_value(productInfo.getGoods_specification_name_value());
            cartInfo.setSku(newcartInfo.getSku());
            cartInfo.setGoods_specification_ids(productInfo.getGoods_specification_ids());
            cartService.update(cartInfo);
        }
        return toResponsObject(0, msg, getCart(checkCart,storeId));
    }

    /**
     * 是否选择商品，如果已经选择，则取消选择，批量操作
     */
    @PostMapping("checked")
    public Object checked(@LoginUser UserVo loginUser) {
        JSONObject jsonParam = getJsonRequest();
        String goodsIds = jsonParam.getString("goodsIds");
        Integer isChecked = jsonParam.getInteger("isChecked");
        String goodsBizType = jsonParam.getString("goodsBizType");
        String checkCart = jsonParam.getString("checkCart");
        String[] goodsIdArray = null;
        if(StringUtils.isNullOrEmpty(goodsBizType)) {
            if (StringUtils.isNullOrEmpty(goodsIds)) {//点击全选时
                return this.toResponsFail("删除出错");
            }
            goodsIdArray = goodsIds.split(",");
        }else{
            //根据业务类型查询购物车
            List<CartVo> cartVoList = cartService.queryCartByGoodsBizType(goodsBizType);
            goodsIdArray = new String[cartVoList.size()];
            for (int i = 0;i< cartVoList.size();i++){
                goodsIdArray[i] =cartVoList.get(i).getGoods_id()+"";
            }
        }
        cartService.updateCheck(goodsIdArray, isChecked, loginUser.getId(), getStoreId());
        return toResponsSuccess(getCart(checkCart,getStoreId()));
    }

    //删除选中的购物车商品，批量删除
    @PostMapping("delete")
    public Object delete(@LoginUser UserVo loginUser) {
        JSONObject jsonObject = getJsonRequest();
        Long cartId = jsonObject.getLong("cartId");
        String checkCart = jsonObject.getString("checkCart");
        if (null == cartId) {
            return toResponsFail("删除出错");
        }
        cartService.delete(cartId);
        return toResponsSuccess(getCart(checkCart,getStoreId()));
    }

    //  获取购物车商品的总件件数
    @GetMapping("goodscounts")
    public Object goodscounts(@LoginUser UserVo loginUser, Long storeId) {
        if (null == loginUser || null == loginUser.getId()) {
            return toResponsFail("未登录");
        }
        Map<String, Object> resultObj = Maps.newHashMap();
        //查询列表数据
        Map param = Maps.newHashMap();
        param.put("user_id", loginUser.getId());
        param.put("store_id", storeId);
        param.putAll(setIsStockShare(storeId));
        List<CartVo> cartList = cartService.queryList(param);
        //获取购物车统计信息
        Integer goodsCount = 0;
        for (CartVo cartItem : cartList) {
            goodsCount += cartItem.getNumber();
        }
        resultObj.put("cartList", cartList);
        //
        Map<String, Object> cartTotal = Maps.newHashMap();
        cartTotal.put("goodsCount", goodsCount);
        //
        resultObj.put("cartTotal", cartTotal);
        return toResponsSuccess(resultObj);
    }

    /**
     * 订单提交前的检验和填写相关订单信息
     */
    @GetMapping("checkout")
    public Object checkout(@LoginUser UserVo loginUser, Long userCouponId, String merchSn, String checkCart) {
        Map<String, Object> resultObj = Maps.newHashMap();
        //选择的收货地址
        Map param = Maps.newHashMap();
        param.put("is_default", 1);
        param.put("user_id", loginUser.getId());
        List<AddressVo> addressEntityList = addressService.queryList(param);

        //获取要购买的商品
        Map<String, Object> cartData = (Map<String, Object>) this.getCartMoney(loginUser,checkCart);

        List<CartVo> checkedGoodsList = new ArrayList();
        for (CartVo cartEntity : (List<CartVo>) cartData.get("cartList")) {
            if (cartEntity.getChecked() == 1) {
                checkedGoodsList.add(cartEntity);
            }
        }
        //计算订单的费用
        //商品总价
        BigDecimal goodsTotalPrice = (BigDecimal) ((HashMap) cartData.get("cartTotal")).get("checkedGoodsAmount");

        //获取可用的优惠券信息 抵用券
        List<UserCouponVo> enableCouponList = apiUserCouponService.matchUserCouponList(loginUser.getId(),merchSn,goodsTotalPrice);
        UserCouponVo checkedCoupon = null;
        BigDecimal couponPrice = new BigDecimal(0.00);  //使用优惠券减免的金额
        if (null != enableCouponList && enableCouponList.size() > 0) {
            if (null != userCouponId) {
                for (UserCouponVo couponVo : enableCouponList) {
                    if (null != userCouponId && userCouponId.equals(couponVo.getId())) {
                        couponPrice = couponVo.getType_money();
                        checkedCoupon = couponVo;
                    }
                }
            }
        }
        // 根据收货地址计算运费
//        BigDecimal freightPrice = apiCouponService.matchShipping(loginUser.getId(), goodsTotalPrice);
        BigDecimal freightPrice00 = new BigDecimal("00");
        BigDecimal freightPrice02 = new BigDecimal("00");
        BigDecimal freightPrice10 = new BigDecimal("00");
        BigDecimal freightPrice11 = new BigDecimal("00");
        //查询运费模板
        for (CartVo vo: checkedGoodsList) {
            if(org.apache.commons.lang.StringUtils.isEmpty(checkCart)){
                if(vo.getGoodsBizType().equalsIgnoreCase(Dict.orderBizType.item_00.getItem())){
                    FreightEntity freightEntity = apiFreightService.queryObjectByGoodsId(vo.getGoods_id(), getStoreId());
                    freightPrice00 = freightEntity!=null ? freightEntity.getDefaultFreight().add(freightPrice00) : freightPrice00;
                }
                if(vo.getGoodsBizType().equalsIgnoreCase(Dict.orderBizType.item_02.getItem())){
                    FreightEntity freightEntity = apiFreightService.queryObjectByGoodsId(vo.getGoods_id(), getStoreId());
                    freightPrice02 = freightEntity!=null ? freightEntity.getDefaultFreight().add(freightPrice02) : freightPrice02;
                }
                if(vo.getGoodsBizType().equalsIgnoreCase(Dict.orderBizType.item_10.getItem())){
                    FreightEntity freightEntity = apiFreightService.queryObjectByGoodsId(vo.getGoods_id(), getStoreId());
                    freightPrice10 = freightEntity!=null ? freightEntity.getDefaultFreight().add(freightPrice10) : freightPrice10;
                }
                if (vo.getGoodsBizType().equalsIgnoreCase(Dict.orderBizType.item_11.getItem())) {
                    FreightEntity freightEntity = apiFreightService.queryObjectByGoodsId(vo.getGoods_id(), getStoreId());
                    freightPrice11 = freightEntity != null ? freightEntity.getDefaultFreight().add(freightPrice11) : freightPrice11;
                }
            }else{
                if(Dict.orderBizType.item_11.getItem().equalsIgnoreCase(checkCart)) {
                    if (vo.getGoodsBizType().equalsIgnoreCase(Dict.orderBizType.item_11.getItem())) {
                        FreightEntity freightEntity = apiFreightService.queryObjectByGoodsId(vo.getGoods_id(), getStoreId());
                        freightPrice11 = freightEntity != null ? freightEntity.getDefaultFreight().add(freightPrice11) : freightPrice11;
                    }
                }else{
                    if(vo.getGoodsBizType().equalsIgnoreCase(Dict.orderBizType.item_00.getItem())){
                        FreightEntity freightEntity = apiFreightService.queryObjectByGoodsId(vo.getGoods_id(), getStoreId());
                        freightPrice00 = freightEntity!=null ? freightEntity.getDefaultFreight().add(freightPrice00) : freightPrice00;
                    }
                    if(vo.getGoodsBizType().equalsIgnoreCase(Dict.orderBizType.item_02.getItem())){
                        FreightEntity freightEntity = apiFreightService.queryObjectByGoodsId(vo.getGoods_id(), getStoreId());
                        freightPrice02 = freightEntity!=null ? freightEntity.getDefaultFreight().add(freightPrice02) : freightPrice02;
                    }
                    if(vo.getGoodsBizType().equalsIgnoreCase(Dict.orderBizType.item_10.getItem())){
                        FreightEntity freightEntity = apiFreightService.queryObjectByGoodsId(vo.getGoods_id(), getStoreId());
                        freightPrice10 = freightEntity!=null ? freightEntity.getDefaultFreight().add(freightPrice10) : freightPrice10;
                    }
                }
            }
        }
        // 计算优惠券 todo 暂时不计算全场金额满减
        BigDecimal fullCutCouponDec = Constant.ZERO;
        Long fullCutCouponId = 0L;
        /*CouponVo fullSubCoupon = apiCouponService.matchFullSub(loginUser.getId(), goodsTotalPrice);
        if (null != fullSubCoupon && null != fullSubCoupon.getId()) {
            // 满减
            fullCutCouponDec = fullSubCoupon.getType_money();
            fullCutCouponId = fullSubCoupon.getId();
        }*/
        resultObj.put("fullCutCouponDec", fullCutCouponDec);
        resultObj.put("fullCutCouponId", fullCutCouponId);
        //订单的总价
        BigDecimal orderTotalPrice = goodsTotalPrice.add(freightPrice00).add(freightPrice02).add(freightPrice10).add(freightPrice11);

        BigDecimal actualPrice = orderTotalPrice.subtract(fullCutCouponDec).subtract(couponPrice);  //减去其它支付的金额后，要实际支付的金额

        resultObj.put("freightPrice00", freightPrice00);
        resultObj.put("freightPrice02", freightPrice02);
        resultObj.put("freightPrice10", freightPrice10);
        resultObj.put("freightPrice11", freightPrice11);
        resultObj.put("checkedCoupon", checkedCoupon);
        resultObj.put("couponList", enableCouponList);

        resultObj.put("couponPrice", couponPrice);
        resultObj.put("checkedGoodsList", checkedGoodsList);
        resultObj.put("goodsTotalPrice", goodsTotalPrice);
        resultObj.put("orderTotalPrice", orderTotalPrice);
        resultObj.put("actualPrice", actualPrice);
        if (null != addressEntityList && addressEntityList.size() > 0) {
            resultObj.put("addressVo", addressEntityList.get(0));
        } else { // 没有默认地址,选择一个
            param = Maps.newHashMap();
            param.put("user_id", loginUser.getId());
            addressEntityList = addressService.queryList(param);
            if (null != addressEntityList && addressEntityList.size() > 0) {
                resultObj.put("addressVo", addressEntityList.get(0));
            }
        }
        UserVo userVo = apiUserService.queryObject(loginUser.getId());
        if(userVo != null){
            resultObj.put("idNo", userVo.getIdNo());
            resultObj.put("userName", userVo.getUsername());
        }

        return toResponsSuccess(resultObj);
    }

    /**
     * 选择优惠券列表
     */
    @GetMapping("checkedCouponList")
    public Object checkedCouponList(@LoginUser UserVo loginUser) {
        //查询列表数据
        Map param = Maps.newHashMap();
        param.put("user_id", loginUser.getId());
        Long storeId = getStoreId();
        param.put("store_id", storeId);
        param.putAll(setIsStockShare(storeId));
        List<CartVo> cartList = cartService.queryList(param);
        //获取购物车统计信息
        BigDecimal checkedGoodsAmount = new BigDecimal(0.00);
        for (CartVo cartItem : cartList) {
            if (null != cartItem.getChecked() && 1 == cartItem.getChecked()) {
                checkedGoodsAmount = checkedGoodsAmount.add(cartItem.getRetail_price().multiply(new BigDecimal(cartItem.getNumber())));
            }
        }
        // 匹配优惠券
        List<UserCouponVo> couponVos = apiUserCouponService.signUserCouponList(loginUser.getId(),getMerchSn(),checkedGoodsAmount);
        return toResponsSuccess(couponVos);
    }

//    select checked from mall_cart where goods_biz_type ='00'

    @PostMapping("getCheckedDataByType")
    public Object getCheckedDataByType() {

        JSONObject jsonParam = getJsonRequest();
        String goodsBizType = jsonParam.getString("goodsBizType");
        List<CartVo> cartVoList = cartService.queryCartByGoodsBizType(goodsBizType);
        for (int i=0;i<cartVoList.size();i++){
            if(cartVoList.get(i).getChecked()==0){//未选中
                Map map=new HashMap();
                map.put("isChecked",false);
                return toResponsSuccess(map);
            }
        }
        Map map=new HashMap();
        map.put("isChecked",true);
        return toResponsSuccess(map);
    }

    /**
     * 清空购物车失效商品
     * @return
     */
    @GetMapping("deleteValidCart")
    public Object deleteValidCart(String checkCart) {
        try{
            Map param = Maps.newHashMap();
            param.put("user_id", getUserId());
            Long storeId = getStoreId();
            param.put("store_id", storeId);
            List<CartVo> list = cartService.queryValidCartList(param);
            for (CartVo cart: list) {
                cartService.delete(cart.getId());
            }
            return toResponsSuccess(getCart(checkCart,storeId));
        }catch (Exception e){
            return toResponsFail("清空失败");
        }
    }

}