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;

    /**
     * 添加购物车
     *
     * @param scr
     * @return
     */
    @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;
            if (null != scr.getSource()) {
                innerKey = new StringBuilder(scr.getPkId().toString()).append("_");
            } else {
                innerKey = new StringBuilder(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());
                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());
        }
        String key = CacheConstants.SHOPPIN_GCART + SecurityUtils.getPkCountry() + "_" + SecurityUtils.getUserId();
        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;
        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 shoppingCartPkCountry = shoppingCartVO.getPkCountry();
                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 shoppingCartRedisPkCountry = shoppingCartRedis.getPkCountry();
                    Integer shoppingCartRedisSpecialArea = shoppingCartRedis.getSpecialArea();
                    if (shoppingCartRedisPkCountry == 0) {
                        iterator.remove();
                        continue;
                    }
                    if (shoppingCartPkCountry.equals(shoppingCartRedisPkCountry)) {
                        if (null != shoppingCartRedis.getWaresCode()) {
                            CuWaresParams cuWaresParams = bdWaresSpecsSkuService.queryWaresSpecsSkuCount(shoppingCartRedisSpecialArea, shoppingCartRedis.getWaresCode(), userId, shoppingCartRedisPkCountry);
                            if (null != cuWaresParams && CollectionUtil.isNotEmpty(cuWaresParams.getProductParams())
                                    && CollectionUtil.isNotEmpty(cuWaresParams.getProductParams().get(0).getWaresItemsParamsList())) {
                                count += shoppingCartRedis.getNumber();
                            } else {
                                iterator.remove();
                            }
                        } else {
                            count += shoppingCartRedis.getNumber();
                        }
                    }
                }
            }
        }
        redisService.setCacheMap(key, shoppingCartRedisMap);
        shoppingCartVO.setCont(count);
        return AjaxResult.success(shoppingCartVO);
    }

    /**
     * @description: 专区购物车数量 getAreaShoppingCount
     * @author: zhang jing
     * @date: 2024/3/28 10:27
     * @param: [shoppingCartVO]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @GetMapping("/getAreaShoppingCount")
    public AjaxResult getAreaShoppingCount(ShoppingCartVO shoppingCartVO) {
        Long userId = SecurityUtils.getUserId();
        if (null == shoppingCartVO.getPkCountry()) {
            shoppingCartVO.setPkCountry(SecurityUtils.getPkCountry());
        }
        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 shoppingCartPkCountry = shoppingCartVO.getPkCountry();
                Integer shoppingCartSpecialArea = 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 shoppingCartRedisPkCountry = shoppingCartRedis.getPkCountry();
                    Integer shoppingCartRedisSpecialArea = shoppingCartRedis.getSpecialArea();
                    if (shoppingCartRedisPkCountry == 0) {
                        iterator.remove();
                        continue;
                    }
                    if (shoppingCartRedisSpecialArea.equals(shoppingCartSpecialArea)
                            && shoppingCartPkCountry.equals(shoppingCartRedisPkCountry)) {
                        if (null != shoppingCartRedis.getWaresCode()) {
                            CuWaresParams cuWaresParams = bdWaresSpecsSkuService.queryWaresSpecsSkuCount(shoppingCartSpecialArea, shoppingCartRedis.getWaresCode(), userId, shoppingCartPkCountry);
                            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.setSmallCount(smallCount);
        return AjaxResult.success(shoppingCartVO);
    }

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

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

    /**
     * 加减购物车数量
     */
    @PostMapping("/plusReduceShopping")
    public AjaxResult plusReduceShopping(@RequestBody ShoppingCartRedis 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);
        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;
        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 = bdWaresSpecsSkuService.selectWaresItemsVO(SecurityUtils.getUserId(), shoppingCartRedis.getPkCountry(), scr.getSpecialArea(),
                                    shoppingCartRedis.getWaresCode(), shoppingCartRedis.getProductGroup(), shoppingCartRedis.getNumber());
                            priceAmount = priceAmount.add(waresItemVo.getPriceAmount());
                            achieveAmount = achieveAmount.add(waresItemVo.getAchieveAmount());
                            assAchieveAmount = assAchieveAmount.add(waresItemVo.getAssAchieveAmount());
                            if (null == waresItemVo.getQuantity() || waresItemVo.getQuantity() == 0) {
                                // 当商品数量为空或者为0时，直接不进行显示
                                continue;
                            }
                            itemList.add(waresItemVo);
                        }
                    }
                }
            }
        }

        carWaresInfoVo.setOrderItemsParams(itemList);
        carWaresInfoVo.setPriceAmount(priceAmount);
        carWaresInfoVo.setAchieveAmount(achieveAmount);
        carWaresInfoVo.setAssAchieveAmount(assAchieveAmount);
        return AjaxResult.success(carWaresInfoVo);
    }
}
