package com.hzs.sale.shopping.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.hzs.common.core.constant.CacheConstants;
import com.hzs.common.core.domain.R;
import com.hzs.common.core.enums.ESpecialArea;
import com.hzs.common.core.service.RedisService;
import com.hzs.common.core.utils.StringUtils;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.sale.shopping.service.IShoppingCartService;
import com.hzs.sale.shopping.vo.*;
import com.hzs.sale.wares.param.CuProductParams;
import com.hzs.sale.wares.param.CuWaresItemsParams;
import com.hzs.sale.wares.param.CuWaresParams;
import com.hzs.sale.wares.service.*;
import com.hzs.system.base.ICurrencyServiceApi;
import com.hzs.system.base.dto.CurrencyDTO;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * 购物车服务实现
 **/
@Service
public class ShoppingCartServiceImpl implements IShoppingCartService {

    @Autowired
    private RedisService redisService;
    @Autowired
    private IBdWaresSpecsSkuService bdWaresSpecsSkuService;

    @DubboReference
    ICurrencyServiceApi currencyServiceApi;

    /**
     * 查询需要下单的购物车
     *
     * @param userId
     * @param sop
     */
    @Override
    public List<ShoppingCartRedis> queryShopping(Long userId, ShoppingCartVO sop) {
        List<ShoppingCartRedis> deleteList = sop.getDeleteList();
        List<ShoppingCartRedis> newShoppingCartRedis = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(deleteList)) {
            String key = CacheConstants.SHOPPIN_GCART + SecurityUtils.getPkCountry() + "_" + SecurityUtils.getUserId();
            Map<String, Object> shoppingCartRedisMap = redisService.getCacheMap(key);
            if (shoppingCartRedisMap.containsKey(key)) {
                Map<String, String> innerShopMap = (Map<String, String>) shoppingCartRedisMap.get(key);
                if (null != innerShopMap) {
                    for (ShoppingCartRedis sc : deleteList) {
                        for (String innkey : innerShopMap.keySet()) {
                            String value = innerShopMap.get(innkey);
                            ShoppingCartRedis shoppingCartRedis = JSONUtil.toBean(value, ShoppingCartRedis.class);
                            if (shoppingCartRedis.getShoppingId().equals(sc.getShoppingId())) {
                                newShoppingCartRedis.add(shoppingCartRedis);
                            }
                        }
                    }
                }
            }
        }
        return newShoppingCartRedis;
    }

    /**
     * 批量删除购物车
     *
     * @param userId
     * @param sop
     */
    @Override
    public void batchDelShopping(Long userId, ShoppingCartVO sop) {
        List<ShoppingCartRedis> deleteList = sop.getDeleteList();
        if (CollectionUtil.isNotEmpty(deleteList)) {
            String key = CacheConstants.SHOPPIN_GCART + SecurityUtils.getPkCountry() + "_" + SecurityUtils.getUserId();
            Map<String, Object> shoppingCartRedisMap = redisService.getCacheMap(key);
            if (shoppingCartRedisMap.containsKey(key)) {
                Map<String, String> innerShopMap = (Map<String, String>) shoppingCartRedisMap.get(key);
                if (null != innerShopMap) {
                    for (ShoppingCartRedis scr : deleteList) {
                        Iterator<Map.Entry<String, String>> iterator = innerShopMap.entrySet().iterator();
                        while (iterator.hasNext()) {
                            Map.Entry<String, String> entry = iterator.next();
                            String innkey = entry.getKey();
                            String value = innerShopMap.get(innkey);
                            ShoppingCartRedis shoppingCartRedis = JSONUtil.toBean(value, ShoppingCartRedis.class);
                            if (shoppingCartRedis.getShoppingId().equals(scr.getShoppingId())) {
                                iterator.remove();
                            }
                        }
                    }
                    shoppingCartRedisMap.put(key, innerShopMap);
                }
                redisService.setCacheMap(key, shoppingCartRedisMap);
            }
        }
    }

    /**
     * @description: 查询购物车
     * @author: zhang jing
     * @date: 2022/12/12 19:03
     * @param: [shoppingCartOld]
     * @return: com.hz.web.controller.api.vo.ShoppingCartVO
     **/
    @Override
    public List<ShoppingCartVO> getShopping(Map<String, String> innerShopMap, Integer specialArea, Integer pkCountry) {
        Long userId = SecurityUtils.getUserId();
        //汇率
        List<ShoppingCartVO> shoppingCartOld = new ArrayList<>();
        R<CurrencyDTO> currency = currencyServiceApi.getCurrency(SecurityUtils.getPkCountry());
        if (StringUtils.isNotNull(specialArea)) {
            ShoppingCartVO scv = new ShoppingCartVO();
            List<ShoppingCart> shoppingCartList = new ArrayList<>();
            for (ESpecialArea value : ESpecialArea.values()) {
                if (specialArea == value.getValue()) {
                    scv.setSpecialArea(value.getValue());
                    scv.setSpecialAreaVal(value.getLabel());
                    break;
                }
            }
            for (String innkey : innerShopMap.keySet()) {
                String mapValue = innerShopMap.get(innkey);
                ShoppingCartRedis scr = JSONUtil.toBean(mapValue, ShoppingCartRedis.class);
                if (scr.getSpecialArea().equals(specialArea) && pkCountry.equals(scr.getPkCountry())) {
                    ShoppingCart shoppingCart = new ShoppingCart();
                    shoppingCart.setShoppingId(scr.getShoppingId());
                    shoppingCart.setNumber(scr.getNumber());
                    BigDecimal waresPrice = new BigDecimal(0);
                    BigDecimal achieve = new BigDecimal(0);
                    BigDecimal assAchieve = new BigDecimal(0);
                    if (scr.getSpecialArea() != null && StringUtils.isNotEmpty(scr.getWaresCode())) {
                        getShoppingCart(shoppingCart, scr.getSpecialArea(), scr.getWaresCode(), userId,
                                scr, waresPrice, achieve, assAchieve, currency, pkCountry);
                        shoppingCartList.add(shoppingCart);
                    }
                }
            }
            scv.setShoppingCartList(shoppingCartList);
            shoppingCartOld.add(scv);
        } else {
            for (ESpecialArea value : ESpecialArea.values()) {
                ShoppingCartVO scv = new ShoppingCartVO();
                List<ShoppingCart> shoppingCartList = new ArrayList<>();
                for (String innkey : innerShopMap.keySet()) {
                    String mapValue = innerShopMap.get(innkey);
                    ShoppingCartRedis scr = JSONUtil.toBean(mapValue, ShoppingCartRedis.class);
                    if (scr.getSpecialArea() == value.getValue()) {
                        scv.setSpecialArea(value.getValue());
                        scv.setSpecialAreaVal(value.getLabel());
                        if (pkCountry.equals(scr.getPkCountry())) {
                            ShoppingCart shoppingCart = new ShoppingCart();
                            shoppingCart.setShoppingId(scr.getShoppingId());
                            shoppingCart.setNumber(scr.getNumber());
                            BigDecimal waresPrice = new BigDecimal(0);
                            BigDecimal achieve = new BigDecimal(0);
                            BigDecimal assAchieve = new BigDecimal(0);
                            if (scr.getSpecialArea() != null && StringUtils.isNotEmpty(scr.getWaresCode())) {
                                getShoppingCart(shoppingCart, scr.getSpecialArea(), scr.getWaresCode(), userId,
                                        scr, waresPrice, achieve, assAchieve, currency, pkCountry);
                                shoppingCartList.add(shoppingCart);
                            }
                        }
                    }
                }
                if (CollectionUtil.isNotEmpty(shoppingCartList)) {
                    scv.setShoppingCartList(shoppingCartList);
                    shoppingCartOld.add(scv);
                }
            }
        }
        return shoppingCartOld;
    }

    /**
     * @description: 获取购物车商品信息
     * @author: zhang jing
     * @date: 2023/5/22 14:36
     * @param: [shoppingCart, specialArea, waresCode, userId, sst, waresPrice, achieve, assAchieve, currency,]
     * @return: com.hzs.sale.shopping.vo.ShoppingCart
     **/
    private ShoppingCart getShoppingCart(ShoppingCart shoppingCart, Integer specialArea, String waresCode, Long userId, ShoppingCartRedis sst,
                                         BigDecimal waresPrice, BigDecimal achieve, BigDecimal assAchieve, R<CurrencyDTO> currency, Integer pkCountry) {
        CuWaresParams cuWaresParams = bdWaresSpecsSkuService.queryWaresSpecsSkuShopping(specialArea, waresCode, userId, pkCountry);
        if (cuWaresParams == null) {
            return shoppingCart;
        }

        shoppingCart.setWaresCode(cuWaresParams.getWaresCode());
        shoppingCart.setWaresName(cuWaresParams.getWaresName());
        shoppingCart.setCover1(cuWaresParams.getCover1());
        shoppingCart.setPrefixLabel(cuWaresParams.getPrefixLabel());
        shoppingCart.setCoolLabel(cuWaresParams.getCoolLabel());
        shoppingCart.setSLabel(cuWaresParams.getSLabel());
        shoppingCart.setWarnMessage(cuWaresParams.getWarnMessage());

        List<ProductGroup> productGroups = sst.getProductGroup();
        List<CuProductParams> newProductParams = new ArrayList<>();
        for (ProductGroup pgp : productGroups) {
            for (CuProductParams cpp : cuWaresParams.getProductParams()) {
                if (pgp.getPkProduct().equals(cpp.getProductId())) {
                    CuProductParams cppNew = BeanUtil.copyProperties(cpp, CuProductParams.class);
                    List<CuWaresItemsParams> waresItemsParamsList = new ArrayList<>();
                    for (CuWaresItemsParams cwip : cpp.getWaresItemsParamsList()) {
                        if (pgp.getPkSkuId().equals(cwip.getPkSkuId())) {
                            CuWaresItemsParams cwipNew = BeanUtil.copyProperties(cwip, CuWaresItemsParams.class);
                            int quantity = pgp.getQuantity() != null ? pgp.getQuantity() : 1;
                            waresPrice = waresPrice.add(cwip.getPrice().multiply(BigDecimal.valueOf(quantity)));
                            achieve = achieve.add(cwip.getAchieve().multiply(new BigDecimal(quantity)).multiply(currency.getData().getInExchangeRate()));
                            if (cwip.getAssAchieve() != null) {
                                assAchieve = assAchieve.add(cwip.getAssAchieve().multiply(new BigDecimal(quantity)));
                            } else {
                                assAchieve = assAchieve.add(cwip.getAssAchieveTotal());
                            }

                            cwipNew.setQuantity(quantity);
                            waresItemsParamsList.add(cwipNew);
                        }
                    }
                    if (CollectionUtil.isNotEmpty(waresItemsParamsList)) {
                        cppNew.setWaresItemsParamsList(waresItemsParamsList);
                        newProductParams.add(cppNew);
                    }
                }
            }
        }

        // 购物车中显示的商品价格
        shoppingCart.setWaresPrice(waresPrice);
        shoppingCart.setAchieve(achieve);
        shoppingCart.setAssAchieve(assAchieve);
        shoppingCart.setProductParams(newProductParams);

        return shoppingCart;
    }

}
