

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

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.tmerclub.cloud.api.product.feign.WarehouseFeignClient;
import com.tmerclub.cloud.api.multishop.feign.ShopSubstituteSalesFeignClient;
import com.tmerclub.cloud.common.constant.Constant;
import com.tmerclub.cloud.common.constant.StatusEnum;
import com.tmerclub.cloud.common.exception.LuckException;
import com.tmerclub.cloud.common.leaf.manager.SegmentManager;
import com.tmerclub.cloud.common.product.constant.*;
import com.tmerclub.cloud.common.product.dto.*;
import com.tmerclub.cloud.common.product.vo.SkuVO;
import com.tmerclub.cloud.common.product.vo.SpuAttrValueVO;
import com.tmerclub.cloud.common.product.vo.SpuDetailVO;
import com.tmerclub.cloud.common.product.vo.SpuVO;
import com.tmerclub.cloud.common.response.ResponseEnum;
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.constant.DistributedIdKey;
import com.tmerclub.cloud.product.mapper.BrandMapper;
import com.tmerclub.cloud.product.mapper.SkuMapper;
import com.tmerclub.cloud.product.mapper.SpuMapper;
import com.tmerclub.cloud.product.model.*;
import com.tmerclub.cloud.product.service.*;
import com.tmerclub.cloud.product.model.*;
import com.tmerclub.cloud.product.service.*;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author xxw
 * @date 2022/8/2 14:09
 */
@Lazy
@Service
public class ImportSupplierSpuServiceImpl implements ImportSupplierSpuService {
    @Autowired
    private SpuMapper spuMapper;
    @Autowired
    private SpuAttrValueService spuAttrValueService;
    @Autowired
    private SpuExtensionService spuExtensionService;
    @Autowired
    private SkuMapper skuMapper;
    @Autowired
    private BrandMapper brandMapper;
    @Autowired
    private SkuService skuService;
    @Autowired
    private SpuLangService spuLangService;
    @Autowired
    private SpuDetailService spuDetailService;
    @Autowired
    private SpuConsignmentChangeService spuConsignmentChangeService;
    @Autowired
    private SegmentManager segmentManager;
    @DubboReference
    private ShopSubstituteSalesFeignClient shopSubstituteSalesFeignClient;
    @Autowired
    private WarehouseFeignClient warehouseFeignClient;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long importSpu(Long supplierSpuId, Long shopId, Integer sysType, Long userId, Boolean isPurchaseOrder) {
        if (Objects.isNull(supplierSpuId)) {
            shopId = AuthUserContext.get().getTenantId();
        }
        //查看是否已导入
        SpuVO commissionSup = spuMapper.getSpuByShopIdAndSupplierSpuId(shopId, supplierSpuId);
        if (!Objects.isNull(commissionSup)) {
            return commissionSup.getSpuId();
        }
        //查找供应商spu信息
        SpuVO spuVo = spuMapper.getBySpuId(supplierSpuId);
        SpuDTO spuDTO = BeanUtil.map(spuVo, SpuDTO.class);
        //商品状态默认为下架
        spuDTO.setStatus(SpuStatus.OFF_SHELF.value());
        //供应商商品类型：商家代销
        spuDTO.setSupplierSpuType(SupplierSpuType.CONSIGNMENT.value());
        //发货方式：供应商发货
        if (Objects.equals(spuVo.getStatus(), StatusEnum.DISABLE.value())) {
            spuDTO.setSupplierDeliveryType(SupplierDeliveryType.SHOP_DELIVERY.value());
        } else {
            spuDTO.setSupplierDeliveryType(SupplierDeliveryType.SUPPLIER_DELIVERY.value());
        }
        // 如果是采购订单时导入商品发货方式需要变成商家发货
        if (isPurchaseOrder) {
            spuDTO.setSupplierDeliveryType(SupplierDeliveryType.SHOP_DELIVERY.value());
        }
        //关联商品商品id
        spuDTO.setSupplierSpuId(spuVo.getSpuId());
        //代销商品规格选择状态:全选
        spuDTO.setSkuChoiceStatus(SkuChoiceStatus.ALL_CHOICE.value());
        //供应商id
        spuDTO.setSupplierId(spuVo.getSupplierId());
        spuDTO.setShopId(shopId);
        //代销商品无需模板id
        spuDTO.setDeliveryTemplateId(null);
        //获取商家代销设置
        ServerResponseEntity<ShopSubstituteSalesVO> salesType = shopSubstituteSalesFeignClient.getByShopSubstituteSalesId(shopId);
        ShopSubstituteSalesVO shopSubstituteSalesVO = salesType.getData();
        if (Objects.isNull(shopSubstituteSalesVO)) {
            // 保存店铺代销设置默认值
            shopSubstituteSalesFeignClient.saveDefault(shopId);
            shopSubstituteSalesVO = shopSubstituteSalesFeignClient.getByShopSubstituteSalesId(shopId).getData();
        }
        spuDTO.setPriceFee(computeSpuPrice(spuDTO, shopSubstituteSalesVO));
        spuDTO.setScoreFee(Objects.isNull(spuDTO.getScoreFee()) ? Constant.ZERO_LONG : spuDTO.getScoreFee());
        //保存商品信息
        Spu spu = BeanUtil.map(spuDTO, Spu.class);
        spu.setSpuId(segmentManager.getSegmentId(DistributedIdKey.tmerclub_SPU));
        spuMapper.save(spu);
        //保存 商家代销商品基本信息相对于供应商品是否改变
        SpuConsignmentChange spuConsignmentChange = new SpuConsignmentChange();
        spuConsignmentChange.setSpuId(spu.getSpuId());
        spuConsignmentChangeService.save(spuConsignmentChange);
        //查询供应商商品属性
        List<SpuAttrValueVO> spuAttrs = spuAttrValueService.getSpuAttrsBySpuId(supplierSpuId);
        List<SpuAttrValueDTO> spuAttrValueList = new ArrayList<>(Constant.INITIAL_CAPACITY);
        for (SpuAttrValueVO spuAttr : spuAttrs) {
            SpuAttrValueDTO spuAttrValueDTO = new SpuAttrValueDTO();
            spuAttr.setSpuId(spu.getSpuId());
            spuAttrValueDTO.setAttrId(spuAttr.getAttrId());
            spuAttrValueDTO.setAttrName(spuAttr.getSpuAttrValueLangList().get(0).getAttrName());
            spuAttrValueDTO.setAttrValueName(spuAttr.getSpuAttrValueLangList().get(0).getAttrValueName());
            if (!Objects.isNull(spuAttr.getAttrValueId())) {
                spuAttrValueDTO.setAttrValueId(spuAttr.getAttrValueId());
            }
            spuAttrValueList.add(spuAttrValueDTO);
        }
        // 2.保存商品属性信息
        spuAttrValueService.save(spu.getSpuId(), spu.getCategoryId(), spuAttrValueList, sysType);
        // 3.国际化信息、商品详情
        spuDTO.setSpuId(spu.getSpuId());
        loadSpuLangInfo(spuDTO);
        //保存商品扩展信息
        SpuExtension spuExtension = new SpuExtension();
        spuExtension.setSpuId(spu.getSpuId());
        spuExtensionService.save(spuExtension);
        //sku信息
        List<SkuVO> skuVOList = skuMapper.listSkuWithAttrBySpuId(supplierSpuId);
        List<SkuDTO> skuList = new ArrayList<>(Constant.INITIAL_CAPACITY);
        // 目前只有一个中文，后面国际化就要重新改造了
        String spuName = spuDTO.getSpuLangList().get(0).getSpuName();
        for (SkuVO skuVO : skuVOList) {
            skuVO.setPriceFee(computeSkuPrice(skuVO, shopSubstituteSalesVO));
            SkuDTO skuDTO = BeanUtil.map(skuVO, SkuDTO.class);
            skuDTO.setSupplierSkuId(skuDTO.getSkuId());
            skuDTO.setSpuId(null);
            skuDTO.setStock(0);
            skuDTO.setSpuName(spuName);
            skuDTO.setSpuMainImgUrl(spu.getMainImgUrl());
            if (Objects.isNull(skuDTO.getStockPointList())) {
                skuDTO.setStockPointList(new ArrayList<>());
            }
            // 添加一条总库存数据
            Long warehouseId = warehouseFeignClient.getDefaultIdByShopId(shopId, sysType).getData();
            StockPointSkuDTO stockPointSkuDTO = new StockPointSkuDTO(warehouseId, StockPointType.WAREHOUSE.getValue(), null, skuDTO.getSkuId(), skuDTO.getStatus(), 0, null);
            stockPointSkuDTO.setStock(0);
            skuDTO.setStockPointList(Collections.singletonList(stockPointSkuDTO));
            skuList.add(skuDTO);
        }
        // 更新品牌信息
        brandMapper.batchUpdateSpuCount(Collections.singleton(spu.getBrandId()));
        //保存sku信息
        skuService.saveSkuAndStock(spuDTO.getSpuMold(),spuDTO.getSpuId(), spuDTO.getStatus(), skuList, sysType, userId, shopId);
        return spu.getSpuId();
    }

    private void loadSpuLangInfo(SpuDTO spuDTO) {
        List<SpuDetail> spuDetailList = new ArrayList<>(Constant.INITIAL_CAPACITY);
        List<SpuLang> spuLangList = new ArrayList<>(Constant.INITIAL_CAPACITY);
        boolean dataCorrect = false;
        for (SpuLangDTO spuLangDTO : spuDTO.getSpuLangList()) {
            SpuLang spuLang = BeanUtil.map(spuLangDTO, SpuLang.class);
            spuLang.setSpuId(spuDTO.getSpuId());
            boolean isBlank = StrUtil.isBlank(spuLang.getSpuName()) && StrUtil.isBlank(spuLang.getSellingPoint());
            if (!isBlank) {
                spuLangList.add(spuLang);
            }
            List<SpuDetailVO> detailList = spuDTO.getDetailList();
            if (CollUtil.isNotEmpty(detailList)) {
                spuDetailList = detailList.stream().map(spuDetailVO -> {
                    SpuDetail detail = new SpuDetail();
                    detail.setSpuId(spuDTO.getSpuId());
                    detail.setDetail(spuDetailVO.getDetail());
                    detail.setLang(spuDetailVO.getLang());
                    return detail;
                }).collect(Collectors.toList());
            } else {
                if (StrUtil.isNotBlank(spuLangDTO.getDetail())) {
                    SpuDetail spuDetail = new SpuDetail();
                    spuDetail.setSpuId(spuDTO.getSpuId());
                    spuDetail.setLang(spuLangDTO.getLang());
                    spuDetail.setDetail(spuLangDTO.getDetail());
                    spuDetailList.add(spuDetail);
                }
            }
            if (!isBlank && Objects.equals(spuLang.getLang(), Constant.DEFAULT_LANG)) {
                dataCorrect = true;
            }

        }

        // 商品名称、卖点，商品详情，是否包含默认语言信息
        if (CollUtil.isEmpty(spuLangList) || !dataCorrect) {
            throw new LuckException(ResponseEnum.DATA_ERROR);
        }
        if (spuDetailList.size() != 0) {
            spuDetailService.batchSave(spuDetailList);
        }
        if (spuLangList.size() != 0) {
            spuLangService.batchSave(spuLangList);
        }
    }

    /**
     * 根据代销设置计算代销商品Spu售价
     *
     * @param spuDTO
     * @param shopSubstituteSalesVO
     * @return
     */
    private Long computeSpuPrice(SpuDTO spuDTO, ShopSubstituteSalesVO shopSubstituteSalesVO) {
        Long spuPriceFee = 0L;

        if (Objects.equals(shopSubstituteSalesVO.getSalesType(), SalesType.SMART_PRICE.value())) {
            //智能设价计算售价
            if (Objects.equals(shopSubstituteSalesVO.getSalesPriceType(), SalesPriceType.PROPORTION_PRICE.value())) {
                //按比例加价
                spuPriceFee = PriceUtil.divideByBankerRounding(spuDTO.getPriceFee() * shopSubstituteSalesVO.getSalesPrice(), 10000) + spuDTO.getPriceFee();
            }
            if (Objects.equals(shopSubstituteSalesVO.getSalesPriceType(), SalesPriceType.FIXED_NUMBER_PRICE.value())) {
                //按固定数值加价
                spuPriceFee = spuDTO.getPriceFee() + shopSubstituteSalesVO.getSalesPrice();
            }
        }
        if (Objects.equals(shopSubstituteSalesVO.getSalesType(), SalesType.MANUAL_OPERATION_PRICE.value())) {
            //手动设价
            spuPriceFee = spuDTO.getPriceFee();
        }
        return spuPriceFee;
    }

    /**
     * 根据代销设置计算代销商品sku售价
     *
     * @param skuVO
     * @param shopSubstituteSalesVO
     * @return
     */
    private Long computeSkuPrice(SkuVO skuVO, ShopSubstituteSalesVO shopSubstituteSalesVO) {
        Long skuPriceFee = 0L;
        if (Objects.equals(shopSubstituteSalesVO.getSalesType(), SalesType.SMART_PRICE.value())) {
            //智能设价计算售价
            if (Objects.equals(shopSubstituteSalesVO.getSalesPriceType(), SalesPriceType.PROPORTION_PRICE.value())) {
                //按比例加价
                skuPriceFee = priceRound(skuVO, shopSubstituteSalesVO);
            }
            if (Objects.equals(shopSubstituteSalesVO.getSalesPriceType(), SalesPriceType.FIXED_NUMBER_PRICE.value())) {
                //按固定数值加价
                skuPriceFee = skuVO.getPriceFee() + shopSubstituteSalesVO.getSalesPrice();
            }
        }

        if (Objects.equals(shopSubstituteSalesVO.getSalesType(), SalesType.MANUAL_OPERATION_PRICE.value())) {
            //手动设价
            skuPriceFee = skuVO.getPriceFee();
        }
        return skuPriceFee;
    }

    private Long priceRound(SkuVO skuVO, ShopSubstituteSalesVO shopSubstituteSalesVO) {
        Long priceFee = skuVO.getPriceFee();
        double priceFeeD = Double.parseDouble(priceFee.toString());
        Long salesPrice = shopSubstituteSalesVO.getSalesPrice();
        double salesPriceD = Double.parseDouble(salesPrice.toString());
        double addPrice = (priceFeeD * salesPriceD) / 10000;

        BigDecimal bigDecimal = new BigDecimal(addPrice);
        addPrice = bigDecimal.setScale(0, RoundingMode.HALF_UP).doubleValue();

        return Double.valueOf(priceFee + addPrice).longValue();
    }

}
