package com.hzs.sale.shopping.controller.api;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.hzs.common.core.constant.CacheConstants;
import com.hzs.common.core.service.RedisService;
import com.hzs.common.core.utils.StringUtils;
import com.hzs.common.core.web.controller.BaseController;
import com.hzs.common.core.web.domain.AjaxResult;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.sale.shopping.param.CarWaresInfoParam;
import com.hzs.sale.shopping.service.IShoppingCartService;
import com.hzs.sale.shopping.vo.*;
import com.hzs.sale.wares.param.CuWaresParams;
import com.hzs.sale.wares.service.IBdWaresSpecsSkuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;

/**
 * 购物车操作处理
 *
 * @author hzs
 */
@RestController
@Slf4j
@RequestMapping("/api/shopping")
public class ApiShoppingCartController extends BaseController {

    @Autowired
    private RedisService redisService;
    @Autowired
    private IShoppingCartService shoppingCartService;

    @Autowired
    private IBdWaresSpecsSkuService bdWaresSpecsSkuService;
    @Autowired
    private IBdWaresSpecsSkuService waresSpecsSkuService;

    /**
     * 添加购物车
     *
     * @RepeatSubmitSimple
     */
    @PostMapping("/addShopping")
    public AjaxResult addShopping(@RequestBody ShoppingCartRedis scr) {
        if (StringUtils.isNull(scr)) {
            return AjaxResult.error("购物车为空");
        }
        if (null == scr.getPkCountry() || scr.getPkCountry() == 0) {
            scr.setPkCountry(SecurityUtils.getPkCountry());
        }
        String key = CacheConstants.SHOPPIN_GCART + SecurityUtils.getPkCountry() + "_" + SecurityUtils.getUserId();
        Map<String, Object> shoppingCartRedisMap = redisService.getCacheMap(key);
        if (shoppingCartRedisMap == null) {
            shoppingCartRedisMap = new HashMap<>();
        }
        if (CollectionUtil.isNotEmpty(scr.getProductGroup())) {
            Map<String, String> innerShopMap;
            if (shoppingCartRedisMap.containsKey(key)) {
                innerShopMap = (Map<String, String>) shoppingCartRedisMap.get(key);
            } else {
                innerShopMap = new HashMap<>();
            }
            StringBuilder innerKey = new StringBuilder().append(scr.getSpecialArea()).append("_");
            if (null != scr.getSource()) {
                innerKey.append(scr.getPkId().toString()).append("_");
            } else {
                innerKey.append(scr.getWaresCode()).append("_");
            }
            for (ProductGroup productGroup : scr.getProductGroup()) {
                innerKey.append(productGroup.getPkSkuId()).append("_").append(productGroup.getQuantity());
            }

            if (innerShopMap.containsKey(innerKey.toString())) {
                String jsonString = innerShopMap.get(innerKey.toString());
                ShoppingCartRedis shoppingCartRedis = JSONUtil.toBean(jsonString, ShoppingCartRedis.class);
                shoppingCartRedis.setNumber(shoppingCartRedis.getNumber() + scr.getNumber());
                shoppingCartRedis.setPkMakerSpace(scr.getPkMakerSpace());
                innerShopMap.put(innerKey.toString(), JSONUtil.toJsonStr(shoppingCartRedis));
            } else {
                scr.setShoppingId(scr.getSpecialArea() + String.valueOf(System.currentTimeMillis()));
                innerShopMap.put(innerKey.toString(), JSONUtil.toJsonStr(scr));
            }
            shoppingCartRedisMap.put(key, innerShopMap);
        }
        redisService.setCacheMap(key, shoppingCartRedisMap);
        return AjaxResult.success(true);
    }

    /**
     * 查询购物车
     */
    @GetMapping("/getShopping")
    public AjaxResult getShopping(ShoppingCartVO shoppingCartVO) {
        if (shoppingCartVO.getSpecialArea() == null
                || shoppingCartVO.getPkCountry() == null) {
            shoppingCartVO.setPkCountry(SecurityUtils.getPkCountry());
        }
        Long userId = SecurityUtils.getUserId();
        String key = CacheConstants.SHOPPIN_GCART + SecurityUtils.getPkCountry() + "_" + userId;
        Map<String, Object> shoppingCartRedisMap = redisService.getCacheMap(key);
        List<ShoppingCartVO> shoppingCartOld;
        if (shoppingCartRedisMap.containsKey(key)) {
            Map<String, String> innerShopMap;
            innerShopMap = (Map<String, String>) shoppingCartRedisMap.get(key);
            shoppingCartOld = shoppingCartService.getShopping(innerShopMap, shoppingCartVO.getSpecialArea(), shoppingCartVO.getPkCountry());
        } else {
            shoppingCartOld = new ArrayList<>();
        }
        return AjaxResult.success(shoppingCartOld);
    }


    /**
     * 查询购物车-数量
     */
    @GetMapping("/getShoppingCount")
    public AjaxResult getShoppingCount(ShoppingCartVO shoppingCartVO) {
        Long userId = SecurityUtils.getUserId();
        if (null == shoppingCartVO.getPkCountry()) {
            shoppingCartVO.setPkCountry(SecurityUtils.getPkCountry());
        }
        int count = 0;
        int smallCount = 0;
        String key = CacheConstants.SHOPPIN_GCART + SecurityUtils.getPkCountry() + "_" + userId;
        Map<String, Object> shoppingCartRedisMap = redisService.getCacheMap(key);
        if (shoppingCartRedisMap == null) {
            shoppingCartRedisMap = new HashMap<>();
        }
        if (shoppingCartRedisMap.containsKey(key)) {
            Map<String, String> innerShopMap = (Map<String, String>) shoppingCartRedisMap.get(key);
            if (null != innerShopMap) {
                Integer shoppingCartVO_pkCountry = shoppingCartVO.getPkCountry();
                Integer shoppingCartVO_specialArea = shoppingCartVO.getSpecialArea();
                Iterator<Map.Entry<String, String>> iterator = innerShopMap.entrySet().iterator();
                while (iterator.hasNext()) {
                    Map.Entry<String, String> entry = iterator.next();
                    String value = entry.getValue();
                    ShoppingCartRedis shoppingCartRedis = JSONUtil.toBean(value, ShoppingCartRedis.class);
                    Integer shoppingCartRedis_pkCountry = shoppingCartRedis.getPkCountry();
                    Integer shoppingCartRedis_specialArea = shoppingCartRedis.getSpecialArea();
                    if (shoppingCartRedis_pkCountry == 0) {
                        iterator.remove();
                        continue;
                    }
                    if (shoppingCartVO_pkCountry.equals(shoppingCartRedis_pkCountry)) {
                        if (null != shoppingCartRedis.getWaresCode()) {
                            CuWaresParams cuWaresParams = bdWaresSpecsSkuService.queryWaresSpecsSku(shoppingCartRedis_specialArea, shoppingCartRedis.getWaresCode(), userId, shoppingCartVO_pkCountry);
                            if (null != cuWaresParams && CollectionUtil.isNotEmpty(cuWaresParams.getProductParams())
                                    && CollectionUtil.isNotEmpty(cuWaresParams.getProductParams().get(0).getWaresItemsParamsList())) {
                                count += shoppingCartRedis.getNumber();
                            } else {
                                iterator.remove();
                                continue;
                            }
                        } else {
                            count += shoppingCartRedis.getNumber();
                        }
                    }
                    if (shoppingCartRedis_specialArea.equals(shoppingCartVO_specialArea)
                            && shoppingCartVO_pkCountry.equals(shoppingCartRedis_pkCountry)) {
                        if (null != shoppingCartRedis.getWaresCode()) {
                            CuWaresParams cuWaresParams = bdWaresSpecsSkuService.queryWaresSpecsSku(shoppingCartVO_specialArea, shoppingCartRedis.getWaresCode(), userId, shoppingCartVO_pkCountry);
                            if (null != cuWaresParams && CollectionUtil.isNotEmpty(cuWaresParams.getProductParams())
                                    && CollectionUtil.isNotEmpty(cuWaresParams.getProductParams().get(0).getWaresItemsParamsList())) {
                                smallCount += shoppingCartRedis.getNumber();
                            }
                        } else {
                            smallCount += shoppingCartRedis.getNumber();
                        }
                    }
                }
            }
        }

        redisService.setCacheMap(key, shoppingCartRedisMap);
        shoppingCartVO.setCont(count);
        shoppingCartVO.setSmallCount(smallCount);
        return AjaxResult.success(shoppingCartVO);
    }

    /**
     * 删除单个用户全部购物车
     */
    @PostMapping("/delShopping")
    public AjaxResult delShopping() {
        /**
         * 用户id
         */
        Long userId = SecurityUtils.getUserId();
        redisService.deleteObject(CacheConstants.SHOPPIN_GCART + SecurityUtils.getPkCountry() + "_" + userId);
        return AjaxResult.success();
    }

    /**
     * 批量删除购物车
     */
    @PostMapping("/batchDelShopping")
    public AjaxResult batchDelShopping(@RequestBody ShoppingCartVO sop) {
        /**
         * 用户id
         */
        Long userId = SecurityUtils.getUserId();
        shoppingCartService.batchDelShopping(userId, sop);
        return AjaxResult.success();
    }

    /**
     * 加减购物车数量
     */
    @PostMapping("/plusReduceShopping")
    public AjaxResult plusReduceShopping(@RequestBody ShoppingCartRedis scr) {
        Long userId = SecurityUtils.getUserId();
        if (null == scr.getPkCountry()) {
            scr.setPkCountry(SecurityUtils.getPkCountry());
        }
        String key = CacheConstants.SHOPPIN_GCART + SecurityUtils.getPkCountry() + "_" + userId;
        Map<String, Object> shoppingCartRedisMap = redisService.getCacheMap(key);
        if (shoppingCartRedisMap != null) {
            Map<String, String> innerShopMap = (Map<String, String>) shoppingCartRedisMap.get(key);
            if (innerShopMap != null) {
                innerShopMap.entrySet().stream()
                        .filter(entry -> {
                            ShoppingCartRedis shoppingCartRedis = JSONUtil.toBean(entry.getValue(), ShoppingCartRedis.class);
                            return shoppingCartRedis.getShoppingId().equals(scr.getShoppingId());
                        })
                        .forEach(entry -> {
                            ShoppingCartRedis shoppingCartRedis = JSONUtil.toBean(entry.getValue(), ShoppingCartRedis.class);
                            shoppingCartRedis.setNumber(scr.getNumber());
                            entry.setValue(JSONUtil.toJsonStr(shoppingCartRedis));
                        });
                shoppingCartRedisMap.put(key, innerShopMap);
                redisService.setCacheMap(key, shoppingCartRedisMap);
            }
        }
        return AjaxResult.success(true);
    }

    /**
     * 购物车展示商品信息
     *
     * @param scr
     * @return
     */
    @PostMapping("get-shopping-wares-detail")
    public AjaxResult getShoppingWaresDetail(@RequestBody CarWaresInfoParam scr) {
        if (null == scr.getPkCountry()) {
            scr.setPkCountry(SecurityUtils.getPkCountry());
        }

        String key = CacheConstants.SHOPPIN_GCART + SecurityUtils.getPkCountry() + "_" + SecurityUtils.getUserId();
        Map<String, Object> shoppingCartRedisMap = redisService.getCacheMap(key);
        CarWaresInfoVo carWaresInfoVo = new CarWaresInfoVo();
        List<WaresItemVo> itemList = new ArrayList<>();
        BigDecimal priceAmount = BigDecimal.ZERO;
        BigDecimal achieveAmount = BigDecimal.ZERO;
        BigDecimal assAchieveAmount = BigDecimal.ZERO;
        BigDecimal borderPriceAmount = BigDecimal.ZERO;
        if (shoppingCartRedisMap.containsKey(key)) {
            Map<String, String> innerShopMap = (Map<String, String>) shoppingCartRedisMap.get(key);
            if (null != innerShopMap) {
                for (String shoppingId : scr.getShoppingIds()) {
                    for (String innkey : innerShopMap.keySet()) {
                        String value = innerShopMap.get(innkey);
                        ShoppingCartRedis shoppingCartRedis = JSONUtil.toBean(value, ShoppingCartRedis.class);
                        if (shoppingCartRedis.getShoppingId().equals(shoppingId)) {
                            WaresItemVo waresItemVo = waresSpecsSkuService.selectWaresItemsVO(SecurityUtils.getUserId(), shoppingCartRedis.getPkCountry(), scr.getSpecialArea(),
                                    shoppingCartRedis.getWaresCode(), shoppingCartRedis.getProductGroup(), shoppingCartRedis.getNumber());
                            priceAmount = priceAmount.add(waresItemVo.getPriceAmount());
                            if (waresItemVo.getBorderAmount() != null) {
                                borderPriceAmount = borderPriceAmount.add(waresItemVo.getBorderAmount());
                            }
                            achieveAmount = achieveAmount.add(waresItemVo.getAchieveAmount());
                            assAchieveAmount = assAchieveAmount.add(waresItemVo.getAssAchieveAmount());
                            itemList.add(waresItemVo);
                        }
                    }
                }
            }
        }
        carWaresInfoVo.setOrderItemsParams(itemList);
        carWaresInfoVo.setPriceAmount(priceAmount);
        carWaresInfoVo.setBorderPriceAmount(borderPriceAmount);
        carWaresInfoVo.setAchieveAmount(achieveAmount);
        carWaresInfoVo.setAssAchieveAmount(assAchieveAmount);
        return AjaxResult.success(carWaresInfoVo);
    }
}
