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.constant.CountryConstants;
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.member.base.IMemberServiceApi;
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.*;

/**
 * @description: 购物车服务实现
 * @author: zhang jing
 * @date: 2022/11/22 14:47
 * @param:
 * @return:
 **/
@Service
public class ShoppingCartServiceImpl implements IShoppingCartService {

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

    @DubboReference
    ICurrencyServiceApi currencyServiceApi;
    @DubboReference
    IMemberServiceApi memberServiceApi;

    /**
     * 查询需要下单的购物车
     *
     * @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)) {
                    if (pkCountry.equals(scr.getPkCountry())) {
                        ShoppingCart shoppingCart = new ShoppingCart();
                        shoppingCart.setShoppingId(scr.getShoppingId());
                        shoppingCart.setNumber(scr.getNumber());

                        if (scr.getSpecialArea() != null && StringUtils.isNotEmpty(scr.getWaresCode())) {
                            getShoppingCart(shoppingCart, userId, scr, 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());

                            if (scr.getSpecialArea() != null && StringUtils.isNotEmpty(scr.getWaresCode())) {
                                getShoppingCart(shoppingCart, userId, scr, 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, userId, sst, currency]
     **/
    private void getShoppingCart(ShoppingCart shoppingCart, Long userId, ShoppingCartRedis sst,
                                 R<CurrencyDTO> currency, Integer pkCountry) {
        List<CuProductParams> productParams = new ArrayList<>();
        BigDecimal waresPrice = new BigDecimal(0);
        BigDecimal achieve = new BigDecimal(0);
        BigDecimal assachieve = new BigDecimal(0);

        Integer specialArea = sst.getSpecialArea();
        String waresCode = sst.getWaresCode();

        CuWaresParams cuWaresParams = bdWaresSpecsSkuService.queryWaresSpecsSku(specialArea, waresCode, userId, pkCountry);
        if (StringUtils.isNotNull(cuWaresParams)) {
            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());
            shoppingCart.setBorderPrice(cuWaresParams.getBorderPrice());
            shoppingCart.setBorderUnit(cuWaresParams.getBorderUnit());
            if (CollectionUtil.isNotEmpty(cuWaresParams.getProductParams())) {
                for (ProductGroup pgp : sst.getProductGroup()) {
                    for (CuProductParams cpp : cuWaresParams.getProductParams()) {
                        if (pgp.getPkProduct().intValue() == cpp.getProductId().intValue()) {
                            CuProductParams cppNew = BeanUtil.copyProperties(cpp, CuProductParams.class);
                            //更新SKU
                            List<CuWaresItemsParams> waresItemsParamsList = new ArrayList<>();
                            if (CollectionUtil.isNotEmpty(cpp.getWaresItemsParamsList())) {
                                for (CuWaresItemsParams cwip : cpp.getWaresItemsParamsList()) {
                                    if (cwip.getPkSkuId().intValue() == pgp.getPkSkuId().intValue()) {
                                        CuWaresItemsParams cwipNew = BeanUtil.copyProperties(cwip, CuWaresItemsParams.class);
                                        if (StringUtils.isNotNull(pgp.getQuantity())) {
                                            cwipNew.setQuantity(pgp.getQuantity());
                                            waresPrice = waresPrice.add(cwip.getPrice().multiply(BigDecimal.valueOf(pgp.getQuantity())));
                                            if (SecurityUtils.getPkCountry() == CountryConstants.CHINA_COUNTRY) {
                                                achieve = achieve.add(cwip.getAchieve().multiply(new BigDecimal(pgp.getQuantity())).multiply(currency.getData().getInExchangeRate()));
                                            } else {
                                                achieve = achieve.add(cwip.getAchieve().multiply(new BigDecimal(pgp.getQuantity())));
                                            }

                                            if (StringUtils.isNotNull(cwip.getAssAchieve())) {
                                                assachieve = assachieve.add(cwip.getAssAchieve().multiply(new BigDecimal(pgp.getQuantity())));
                                            }
                                        } else {
                                            waresPrice = waresPrice.add(cwip.getPriceTotal());
                                            achieve = achieve.add(cwip.getAchieveTotal());
                                            assachieve = assachieve.add(cwip.getAssAchieveTotal());
                                        }
                                        waresItemsParamsList.add(cwipNew);
                                    }
                                }
                            }
                            cppNew.setWaresItemsParamsList(waresItemsParamsList);
                            if (CollectionUtil.isNotEmpty(waresItemsParamsList)) {
                                productParams.add(cppNew);
                            }
                        }
                    }
                }
                shoppingCart.setWaresPrice(waresPrice);
                shoppingCart.setAchieve(achieve);
                shoppingCart.setAssAchieve(assachieve);
            }
            shoppingCart.setProductParams(productParams);
        }
    }

}
