
package com.tmerclub.cloud.product.service.impl;

import com.tmerclub.cloud.api.multishop.feign.ShopSubstituteSalesFeignClient;
import com.tmerclub.cloud.api.supplier.feign.SupplierDetailFeignClient;
import com.tmerclub.cloud.api.supplier.vo.SupplierApiDetailVO;
import com.tmerclub.cloud.common.constant.Constant;
import com.tmerclub.cloud.common.constant.StatusEnum;
import com.tmerclub.cloud.common.database.dto.PageDTO;
import com.tmerclub.cloud.common.database.util.PageUtil;
import com.tmerclub.cloud.common.database.vo.PageVO;
import com.tmerclub.cloud.common.product.constant.ContentKey;
import com.tmerclub.cloud.common.product.constant.ContentValue;
import com.tmerclub.cloud.common.product.constant.SpuStatus;
import com.tmerclub.cloud.common.product.constant.SupplierSpuChangeType;
import com.tmerclub.cloud.common.product.dto.SkuDTO;
import com.tmerclub.cloud.common.product.vo.SkuVO;
import com.tmerclub.cloud.common.product.vo.SpuVO;
import com.tmerclub.cloud.common.response.ServerResponseEntity;
import com.tmerclub.cloud.common.security.AuthUserContext;
import com.tmerclub.cloud.common.util.BeanUtil;
import com.tmerclub.cloud.common.util.PriceUtil;
import com.tmerclub.cloud.common.vo.ShopSubstituteSalesVO;
import com.tmerclub.cloud.product.dto.SpuSupplierChangeLogDTO;
import com.tmerclub.cloud.product.mapper.SkuLangMapper;
import com.tmerclub.cloud.product.mapper.SkuMapper;
import com.tmerclub.cloud.product.mapper.SpuMapper;
import com.tmerclub.cloud.product.mapper.SpuSupplierChangeLogMapper;
import com.tmerclub.cloud.product.model.Sku;
import com.tmerclub.cloud.product.model.SpuSupplierChangeLog;
import com.tmerclub.cloud.product.service.SkuService;
import com.tmerclub.cloud.product.service.SpuAttrValueService;
import com.tmerclub.cloud.product.service.SpuExtensionService;
import com.tmerclub.cloud.product.service.SpuSupplierChangeLogService;
import com.tmerclub.cloud.product.vo.SpuSupplierChangeLogVO;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 商品供应商变更记录
 *
 * @author lhd
 * @date 2022-06-22 16:57:27
 */
@Service
public class SpuSupplierChangeLogServiceImpl implements SpuSupplierChangeLogService {

    @Autowired
    private SpuSupplierChangeLogMapper spuSupplierChangeLogMapper;
    @Autowired
    private SpuMapper spuMapper;
    @Autowired
    private SkuService skuService;
    @Autowired
    private SkuMapper skuMapper;
    @Autowired
    private SkuLangMapper skuLangMapper;
    @Autowired
    private SpuAttrValueService spuAttrValueService;
    @Autowired
    private SpuExtensionService spuExtensionService;
    @DubboReference
    private ShopSubstituteSalesFeignClient shopSubstituteSalesFeignClient;
    @DubboReference
    private SupplierDetailFeignClient supplierDetailFeignClient;

    @Override
    public PageVO<SpuSupplierChangeLogVO> page(PageDTO pageDTO) {
        Long shopId = AuthUserContext.get().getTenantId();
        //获取供应商商品id列表
        List<Long> supplierSpuId = spuMapper.getSupplierSpuId(shopId);
        //获取供应商名称
        if (supplierSpuId.size() > 0) {
            PageVO<SpuSupplierChangeLogVO> pageVO = PageUtil.doPage(pageDTO, () -> spuSupplierChangeLogMapper.listBySpuIds(supplierSpuId));
            List<SpuSupplierChangeLogVO> spuSupplierChangeLogVOList = pageVO.getList();
            //供应商id
            List<Long> supplierIdList = spuSupplierChangeLogVOList.stream().map(SpuSupplierChangeLogVO::getSupplierId).collect(Collectors.toList());
            //获取供应商名称
            List<SupplierApiDetailVO> supplierApiDetailVOList = supplierDetailFeignClient.listBySupplierIds(supplierIdList).getData();
            Map<Long, String> supplierNameMap = supplierApiDetailVOList.stream().collect(Collectors.toMap(SupplierApiDetailVO::getSupplierId, SupplierApiDetailVO::getSupplierName));
            //获取供应商商品对应的代销商品id
            List<Long> supplieSpuIds = spuSupplierChangeLogVOList.stream().map(SpuSupplierChangeLogVO::getSpuId).collect(Collectors.toList());
            if (supplieSpuIds.size() == 0) {
                return pageVO;
            }
            List<SpuVO> spuVOList = spuMapper.listSpuByShopIdAndSupplierSpuId(shopId, supplieSpuIds);
            Map<Long, Long> collect = spuVOList.stream().collect(Collectors.toMap(SpuVO::getSupplierSpuId, SpuVO::getSpuId));
            for (SpuSupplierChangeLogVO spuSupplierChangeLogVO : spuSupplierChangeLogVOList) {
                //设置供应商名称
                spuSupplierChangeLogVO.setSupplierName(supplierNameMap.get(spuSupplierChangeLogVO.getSupplierId()));
                spuSupplierChangeLogVO.setCommissionSpuId(collect.get(spuSupplierChangeLogVO.getSpuId()));
                if (Objects.equals(spuSupplierChangeLogVO.getChangeType(), SupplierSpuChangeType.PUT_SHELF.value())) {
                    //上架
                    spuSupplierChangeLogVO.setContentKey(ContentKey.STATUS_CHANGE.value());
                    spuSupplierChangeLogVO.setContentValue(ContentValue.SPU_PUT.value());
                }
                if (Objects.equals(spuSupplierChangeLogVO.getChangeType(), SupplierSpuChangeType.OFF_SHELF.value())) {
                    //下架
                    spuSupplierChangeLogVO.setContentKey(ContentKey.STATUS_CHANGE.value());
                    spuSupplierChangeLogVO.setContentValue(ContentValue.SPU_OFF.value());
                }
                if (Objects.equals(spuSupplierChangeLogVO.getChangeType(), SupplierSpuChangeType.SKU_MSG_CHANGE.value())) {
                    //SKU描述变更
                    spuSupplierChangeLogVO.setContentKey(ContentKey.DESCRIBE_CHANGE.value());
                    spuSupplierChangeLogVO.setContentValue(ContentValue.SKU_CHANGE.value());
                }
                if (Objects.equals(spuSupplierChangeLogVO.getChangeType(), SupplierSpuChangeType.ADD_SKU.value())) {
                    //新增sku
                    spuSupplierChangeLogVO.setContentKey(ContentKey.ELSE_CHANGE.value());
                    spuSupplierChangeLogVO.setContentValue(ContentValue.ADD_SKU.value());
                }
                if (Objects.equals(spuSupplierChangeLogVO.getChangeType(), SupplierSpuChangeType.SPU_MSG_CHANGE.value())) {
                    // Spu描述变更
                    spuSupplierChangeLogVO.setContentKey(ContentKey.DESCRIBE_CHANGE.value());
                    spuSupplierChangeLogVO.setContentValue(ContentValue.SPU_CHANGE.value());
                }
            }
            return pageVO;
        }
        return null;
    }

    @Override
    public SpuSupplierChangeLog getBySpuChangeId(Long spuChangeId) {
        return spuSupplierChangeLogMapper.getBySpuChangeId(spuChangeId);
    }

    @Override
    public void save(SpuSupplierChangeLog spuSupplierChangeLog) {
        spuSupplierChangeLogMapper.save(spuSupplierChangeLog);
    }

    @Override
    public void update(SpuSupplierChangeLog spuSupplierChangeLog) {
        spuSupplierChangeLogMapper.update(spuSupplierChangeLog);
    }

    @Override
    public void deleteById(Long spuChangeId) {
        spuSupplierChangeLogMapper.deleteById(spuChangeId);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void syncSpu(Long shopId, List<SpuSupplierChangeLogDTO> spuSupplierChangeLog) {
        Map<Integer, List<SpuSupplierChangeLogDTO>> collect = spuSupplierChangeLog.stream().collect(Collectors.groupingBy(SpuSupplierChangeLogDTO::getChangeType));
        //上架
        List<SpuSupplierChangeLogDTO> putShelf = collect.get(SupplierSpuChangeType.PUT_SHELF.value());
        if (!Objects.isNull(putShelf)) {
            List<Long> putSupplierSpuId = putShelf.stream().map(SpuSupplierChangeLogDTO::getSpuId).collect(Collectors.toList());
            List<Long> putSpuId = spuMapper.getSpuIdByShopIdAndSupplierSpuId(shopId, putSupplierSpuId);
            spuMapper.batchChangeSpuStatus(putSpuId, SpuStatus.PUT_SHELF.value());
            spuSupplierChangeLog.removeAll(putShelf);
            spuMapper.batchChangeSynUpdate(putSpuId, 1);
        }
        //下架
        List<SpuSupplierChangeLogDTO> offShelf = collect.get(SupplierSpuChangeType.OFF_SHELF.value());
        if (!Objects.isNull(offShelf)) {
            List<Long> offSupplierSpuId = offShelf.stream().map(SpuSupplierChangeLogDTO::getSpuId).collect(Collectors.toList());
            List<Long> offSpuId = spuMapper.getSpuIdByShopIdAndSupplierSpuId(shopId, offSupplierSpuId);
            spuMapper.batchChangeSpuStatus(offSpuId, SpuStatus.OFF_SHELF.value());
            spuSupplierChangeLog.removeAll(offShelf);
            spuMapper.batchChangeSynUpdate(offSpuId, 1);
        }
        for (SpuSupplierChangeLogDTO supplierChangeLog : spuSupplierChangeLog) {
            //获取到代销商品信息
            SpuVO spuVo = spuMapper.getSpuByShopIdAndSupplierSpuId(shopId, supplierChangeLog.getSpuId());
            //获取代销商品sku信息
            List<SkuVO> skuVOList = skuService.listSkuAllInfoBySpuId(spuVo.getSpuId(), spuVo, false);
            //获取供应商品sku信息
            List<SkuVO> supplierSkuVOList = skuService.listSkuAllInfoBySpuId(supplierChangeLog.getSpuId(), spuVo, false);
            //同步sku信息变更
            if (Objects.equals(SupplierSpuChangeType.SKU_MSG_CHANGE.value(), supplierChangeLog.getChangeType())) {
                skuMsgChange(supplierSkuVOList, spuVo);
                spuMapper.changeSynUpdate(spuVo.getSpuId(), 1);
            }
            //同步新增sku
            if (Objects.equals(SupplierSpuChangeType.ADD_SKU.value(), supplierChangeLog.getChangeType())) {
                addSku(skuVOList, supplierSkuVOList, spuVo);
                spuMapper.changeSynUpdate(spuVo.getSpuId(), 1);
            }
        }
    }

    /**
     * 同步sku信息变更
     *
     * @param supplierSkuVOList
     * @param spuVo
     */
    public void skuMsgChange(List<SkuVO> supplierSkuVOList, SpuVO spuVo) {
        List<Sku> skus = new ArrayList<>(Constant.INITIAL_CAPACITY);
        for (SkuVO skuVO : supplierSkuVOList) {
            //根据供应商品skuId获取代销商品skuId
            Long skuId = skuMapper.getSkuIdBySupplierSkuId(skuVO.getSkuId(), spuVo.getSpuId());
            skuVO.setSpuId(spuVo.getSpuId());
            skuVO.setSkuId(skuId);
            //获取店铺代销设置设置销售价格
            Long priceFee = setPriceFee(skuVO);
            skuVO.setPriceFee(priceFee);
            skuVO.setMarketPriceFee(null);
            skus.add(BeanUtil.map(skuVO, Sku.class));
        }
        skuMapper.updateBatch(skus);
    }

    /**
     * 同步新增sku
     *
     * @param skuVOList
     * @param supplierSkuVOList
     * @param spuVo
     */
    public void addSku(List<SkuVO> skuVOList, List<SkuVO> supplierSkuVOList, SpuVO spuVo) {
        List<Long> skuIds = skuVOList.stream().map(SkuVO::getSkuId).collect(Collectors.toList());
        List<Long> supplierSkuIds = supplierSkuVOList.stream().map(SkuVO::getSkuId).collect(Collectors.toList());
        //获取供应商新增skuId
        supplierSkuIds.removeAll(skuIds);
        //获取供应商新增sku信息
        List<SkuVO> skuList = skuMapper.listSkuBySkuIds(supplierSkuIds);
        List<SkuDTO> skuDtoS = new ArrayList<>(Constant.INITIAL_CAPACITY);
        for (SkuVO skuVO : skuList) {
            skuVO.setSpuId(spuVo.getSpuId());
            //获取店铺代销设置设置销售价格
            Long priceFee = setPriceFee(skuVO);
            skuVO.setPriceFee(priceFee);
            skuDtoS.add(BeanUtil.map(skuVO, SkuDTO.class));
        }
        skuMapper.saveBatch(skuDtoS);
    }

    @Override
    public void insertBatchChangeStatus(List<Long> spuIds, Integer status) {
        if (status.equals(StatusEnum.ENABLE.value())) {
            spuSupplierChangeLogMapper.insertBatch(spuIds, SupplierSpuChangeType.PUT_SHELF.value());
        } else if (status.equals(StatusEnum.DISABLE.value())) {
            spuSupplierChangeLogMapper.insertBatch(spuIds, SupplierSpuChangeType.OFF_SHELF.value());
        }

    }

    @Override
    public void saveBatch(List<SpuSupplierChangeLog> spuSupplierChangeLogs) {
        spuSupplierChangeLogMapper.saveBatch(spuSupplierChangeLogs);
    }

    public Long setPriceFee(SkuVO skuVO) {
        Long shopId = AuthUserContext.get().getTenantId();
        //获取商家代销设置
        ServerResponseEntity<ShopSubstituteSalesVO> salesType = shopSubstituteSalesFeignClient.getByShopSubstituteSalesId(shopId);
        ShopSubstituteSalesVO shopSubstituteSalesVO = salesType.getData();
        if (!Objects.isNull(shopSubstituteSalesVO)) {
            if (shopSubstituteSalesVO.getSalesType() == 0) {
                //智能设价计算售价
                long price = 0L;
                if (shopSubstituteSalesVO.getSalesPriceType() == 0) {
                    //按比例加价
                    price = PriceUtil.divideByBankerRounding(skuVO.getPriceFee() * shopSubstituteSalesVO.getSalesPrice(), 10000) + skuVO.getPriceFee();
                }
                if (shopSubstituteSalesVO.getSalesPriceType() == 1) {
                    //按固定数值加价
                    price = skuVO.getPriceFee() + shopSubstituteSalesVO.getSalesPrice();
                }
                return price;
            }
        }
        return 0L;
    }


}
