
package com.tmerclub.cloud.product.controller.admin;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import com.tmerclub.cloud.api.auth.constant.SysTypeEnum;
import com.tmerclub.cloud.api.combo.feign.ComboFeignClient;
import com.tmerclub.cloud.api.multishop.bo.EsShopDetailBO;
import com.tmerclub.cloud.api.multishop.constant.ShopStatus;
import com.tmerclub.cloud.api.multishop.feign.ShopDetailFeignClient;
import com.tmerclub.cloud.api.multishop.feign.ShopSubstituteSalesFeignClient;
import com.tmerclub.cloud.api.platform.dto.OfflineHandleEventDTO;
import com.tmerclub.cloud.api.platform.feign.ConfigFeignClient;
import com.tmerclub.cloud.api.platform.vo.DistributionConfigApiVO;
import com.tmerclub.cloud.api.platform.vo.OfflineHandleEventVO;
import com.tmerclub.cloud.api.platform.vo.SysConfigApiVO;
import com.tmerclub.cloud.api.product.util.ProductLangUtil;
import com.tmerclub.cloud.common.constant.AutoCheckEnum;
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.product.constant.*;
import com.tmerclub.cloud.common.product.dto.SkuComboDTO;
import com.tmerclub.cloud.common.product.dto.SpuDTO;
import com.tmerclub.cloud.common.product.vo.*;
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.ExcelUtil;
import com.tmerclub.cloud.common.util.Json;
import com.tmerclub.cloud.common.vo.ShopSubstituteSalesVO;
import com.tmerclub.cloud.product.dto.SpuPageSearchDTO;
import com.tmerclub.cloud.product.handler.ProductCommentWriteHandler;
import com.tmerclub.cloud.product.listener.SpuExcelListener;
import com.tmerclub.cloud.product.model.SpuConsignmentChange;
import com.tmerclub.cloud.product.service.*;
import com.tmerclub.cloud.common.util.SheetUtil;
import com.tmerclub.cloud.product.service.*;
import com.tmerclub.cloud.product.vo.CategoryShopVO;
import com.tmerclub.cloud.product.vo.SpuExcelVO;
import com.tmerclub.cloud.product.vo.SupplierSpuExcelVO;
import com.tmerclub.cloud.product.vo.SupplierSpuVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import org.apache.commons.collections.CollectionUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * spu信息
 *
 * @author tmerclub
 * @date 2020-10-28 15:27:24
 */
@RestController("adminSpuController")
@RequestMapping("/mp/spu")
@Tag(name = "admin-spu信息")
public class SpuController {

    private static final Logger LOGGER = LoggerFactory.getLogger(SpuController.class);

    @Autowired
    private SpuService spuService;
    @Autowired
    private SkuService skuService;
    @Autowired
    private SkuComboService skuComboService;
    @Autowired
    private BrandService brandService;
    @Autowired
    private ShopCartService shopCartService;
    @Autowired
    private GiveawayService giveawayService;
    @Autowired
    private SpuExcelService spuExcelService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private GiveawaySpuService giveawaySpuService;
    @Autowired
    private SpuAttrValueService spuAttrValueService;
    @Autowired
    private CategoryShopService categoryShopService;
    @Autowired
    private SpuConsignmentChangeService spuConsignmentChangeService;
    @DubboReference
    private ComboFeignClient comboFeignClient;
    @DubboReference
    private ConfigFeignClient configFeignClient;
    @DubboReference
    private ShopDetailFeignClient shopDetailFeignClient;
    @DubboReference
    private ShopSubstituteSalesFeignClient shopSubstituteSalesFeignClient;

    @GetMapping
    @Operation(summary = "获取spu信息", description = "根据spuId获取spu信息")
    public ServerResponseEntity<SpuVO> getBySpuId(@RequestParam Long spuId) {
        // 获取spu信息
        SpuVO spuVO = spuService.getBySpuId(spuId);
        if (Objects.equals(spuVO.getSupplierSpuType(), SupplierSpuType.CONSIGNMENT.value()) && !Objects.isNull(spuVO.getSupplierSpuId())) {
            //处理返回的代销商品信息
            disposeSpuMsg(spuVO);
            //返回商家代销设置
            setSalesMsg(spuVO);
            //供应商商品信息
            SpuVO supplierSpu = spuService.getBySpuId(spuVO.getSupplierSpuId());
            spuVO.setSupplierSpuStatus(supplierSpu.getStatus());
            spuVO.setSupplierSpuCode(supplierSpu.getSpuCode());
            if (Objects.equals(spuVO.getSupplierDeliveryType(), SupplierDeliveryType.SUPPLIER_DELIVERY.value()) && Objects.equals(supplierSpu.getStatus(), StatusEnum.DELETE.value())) {
                spuVO.setSupplierDeliveryType(SupplierDeliveryType.SHOP_DELIVERY.value());
            }
        }
        Integer sysType = AuthUserContext.get().getSysType();
        if (!Objects.equals(sysType, SysTypeEnum.MULTISHOP.value()) && !Objects.equals(spuVO.getSupplierSpuType(), SupplierSpuType.YES.value())) {
            if (!Objects.equals(spuVO.getShopId(), AuthUserContext.get().getTenantId()) && !Objects.equals(Constant.PLATFORM_SHOP_ID, AuthUserContext.get().getTenantId())) {
                return ServerResponseEntity.fail(ResponseEnum.UNAUTHORIZED);
            }
        }
        List<SpuAttrValueVO> spuAttrsBySpuId = spuAttrValueService.getSpuAttrsBySpuId(spuId);
        spuVO.setSpuAttrValues(spuAttrsBySpuId);

        // 物流模板
        SpuVO.DeliveryModeVO deliveryModeVO = Json.parseObject(spuVO.getDeliveryMode(), SpuVO.DeliveryModeVO.class);
        spuVO.setDeliveryModeVO(deliveryModeVO);
        // 品牌信息
        spuVO.setBrand(brandService.getByBrandId(spuVO.getBrandId()));
        // sku信息
        if (Objects.equals(spuVO.getSupplierSpuType(), SupplierSpuType.CONSIGNMENT.value())) {
            //代销商品
            spuVO.setSkus(skuService.listConsignmentSku(spuVO, false));
        } else {
            //其他商品（商家商品，供应商商品）
            spuVO.setSkus(skuService.listSkuAllInfoBySpuId(spuId, spuVO, false));
        }



        // 从sku中计算商品库存
        int totalStock = 0;
        int saleNum = 0;
        for (SkuVO sku : spuVO.getSkus()) {
            totalStock += Objects.isNull(sku.getStock()) ? 0: sku.getStock();
            saleNum += Objects.isNull(sku.getSaleNum()) ? 0: sku.getSaleNum();
        }
        spuVO.setTotalStock(totalStock);
        spuVO.setSaleNum(saleNum);
        spuService.loadSpuAttrs(spuVO);
        // 平台分类、店铺分类信息
        spuVO.setCategory(categoryService.getInfo(spuVO.getCategoryId()));
        ProductLangUtil.category(spuVO.getCategory());
        if (Objects.nonNull(spuVO.getShopCategoryId()) && !Objects.equals(spuVO.getShopCategoryId(), Constant.DEFAULT_ID)) {
            spuVO.setShopCategory(categoryService.getInfo(spuVO.getShopCategoryId()));
            if (!Objects.isNull(spuVO.getShopCategory())) {
                ProductLangUtil.category(spuVO.getShopCategory());
            }
        }
        // 是否为套餐商品
        Boolean data = comboFeignClient.checkComboSpu(spuId, AuthUserContext.get().getTenantId()).getData();
        spuVO.setIsComboSpu(data);
        return ServerResponseEntity.success(spuVO);
    }

    private void setSalesMsg(SpuVO spuVO) {
        if (Objects.equals(AuthUserContext.get().getSysType(), SysTypeEnum.MULTISHOP.value())) {
            Long shopId = AuthUserContext.get().getTenantId();
            //获取商家代销设置
            ServerResponseEntity<ShopSubstituteSalesVO> shopSubstituteSales = shopSubstituteSalesFeignClient.getByShopSubstituteSalesId(shopId);
            spuVO.setSalesType(shopSubstituteSales.getData().getSalesType());
            spuVO.setSalesPriceType(shopSubstituteSales.getData().getSalesPriceType());
//            if (Objects.equals(spuVO.getSupplierDeliveryType(), SupplierDeliveryType.SUPPLIER_DELIVERY.value())) {
            spuVO.setSalesPrice(shopSubstituteSales.getData().getSalesPrice());
//            }
        }
    }

    @PostMapping
    @Operation(summary = "保存spu信息", description = "保存spu信息")
    public ServerResponseEntity<Long> save(@Valid @RequestBody SpuDTO spuDTO) {
        spuDTO.setStatus(StatusEnum.ENABLE.value());
        if (!Objects.equals(spuDTO.getSpuType(), SpuType.ACTIVE.value())) {
            spuDTO.setSpuType(SpuType.NORMAL.value());
        }
        spuService.save(spuDTO);
        return ServerResponseEntity.success(spuDTO.getSpuId());
    }

    @PutMapping
    @Operation(summary = "更新spu信息", description = "更新spu信息")
    public ServerResponseEntity<Void> update(@Valid @RequestBody SpuDTO spuDTO) {
        SpuVO spuDb = spuService.getBySpuId(spuDTO.getSpuId());
        if (!Objects.equals(spuDb.getShopId(), AuthUserContext.get().getTenantId())) {
            return ServerResponseEntity.fail(ResponseEnum.UNAUTHORIZED);
        }
        spuService.update(spuDTO);
        //  清除购物车数量缓存
        shopCartService.removeShopCartItemCache(Collections.singletonList(spuDTO.getSpuId()));
        return ServerResponseEntity.success();
    }


    @DeleteMapping
    @Operation(summary = "删除spu信息", description = "根据spu信息id删除spu信息")
    public ServerResponseEntity<Void> delete(@RequestParam Long spuId) {
        SpuVO spuDb = spuService.getBySpuId(spuId);
        Long shopId = AuthUserContext.get().getTenantId();
        if (!Objects.equals(spuDb.getShopId(), shopId) && !Objects.equals(shopId, Constant.PLATFORM_SHOP_ID)) {
            return ServerResponseEntity.fail(ResponseEnum.UNAUTHORIZED);
        }
        //判断是否包含赠品活动、判断商品是否为套餐活动(正在进行的)的主商品
        checkBeforeDeleteSpu(spuId, shopId);

        spuService.deleteById(spuId);
        // 更新分销配置（移除分销指定商品）
        this.updateDistributionAfterDeleteSpu(spuId);
        //  清除购物车数量缓存
        shopCartService.removeShopCartItemCache(Collections.singletonList(spuId));
        return ServerResponseEntity.success();
    }

    @PutMapping("/update_spu_data")
    @Operation(summary = "修改spu（名称、价格、库存、序号）信息", description = "更新spu信息")
    public ServerResponseEntity<Void> updateSpuData(@RequestBody SpuDTO spuDTO) {
        SpuVO spuDb = spuService.getBySpuId(spuDTO.getSpuId());
        if (!Objects.equals(spuDb.getShopId(), AuthUserContext.get().getTenantId())) {
            return ServerResponseEntity.fail(ResponseEnum.UNAUTHORIZED);
        }
        spuService.updateSpuOrSku(spuDTO);
        //  清除购物车数量缓存
        shopCartService.removeShopCartItemCache(Collections.singletonList(spuDTO.getSpuId()));
        return ServerResponseEntity.success();
    }


    /**
     * 更新商品状态
     */
    @PutMapping("/prod_status")
    @Operation(summary = "商品上下架", description = "商品上下架")
    public ServerResponseEntity<Void> spuChangeStatus(@RequestBody SpuPageSearchDTO spuDTO) {
        Long shopId = AuthUserContext.get().getTenantId();
        if (Objects.nonNull(spuDTO.getSpuId())) {
            spuDTO.setSpuIds(Collections.singletonList(spuDTO.getSpuId()));
        }
        if (CollUtil.isEmpty(spuDTO.getSpuIds())) {
            throw new LuckException("商品id不能为空");
        }
        List<SpuVO> spuList = spuService.listSpuBySpuIds(spuDTO.getSpuIds());

        checkShop(spuDTO);
        for (SpuVO spuVO : spuList) {
            if (Objects.equals(spuDTO.getStatus(), StatusEnum.ENABLE.value())) {
                checkInfo(spuVO);
            }
            //供应商商品
            if (SupplierSpuType.YES.value().equals(spuDTO.getSupplierSpuType())) {
                SpuVO spuVo = spuService.getSpuByShopIdAndSupplierSpuId(shopId, spuDTO.getSpuId());
                if (!Objects.isNull(spuVo)) {
                    spuDTO.setSpuId(spuVo.getSpuId());
                    spuDTO.setShopId(spuVo.getShopId());
                    spuVO.setShopId(spuVo.getShopId());
                }
            }
            if (!Objects.equals(spuVO.getShopId(), shopId) && !Objects.equals(shopId, Constant.PLATFORM_SHOP_ID)) {
                return ServerResponseEntity.fail(ResponseEnum.UNAUTHORIZED);
            }
        }
        // 是否开启“商品发布时审核”，若开启，上架修改状态为“待审核”【平台端不用审核】
        ServerResponseEntity<String> config = configFeignClient.getConfig(Constant.SPU_SWITCH_CONFIG);
        String prodSwitchConfig = config.getData();
        boolean shouldChange = SpuStatus.PUT_SHELF.value().equals(spuDTO.getStatus())
                && !SysTypeEnum.PLATFORM.value().equals(AuthUserContext.get().getSysType())
                && !ObjectUtils.isEmpty(prodSwitchConfig);
        if (shouldChange) {
            Boolean spuAudit = JSON.parseObject(prodSwitchConfig, new TypeReference<Map<String, Boolean>>() {
                    })
                    .getOrDefault("spuAudit", false);
            if (spuAudit) {
                spuDTO.setStatus(SpuStatus.PUBLISH_WAIT_AUDIT.value());
            }
        }
        spuBatchUpdateStatus(spuDTO);
        for (SpuVO spuVO : spuList) {
            spuService.removeSpuCacheBySpuId(spuVO.getSpuId());
        }
        //  清除购物车数量缓存
        shopCartService.removeShopCartItemCache(spuDTO.getSpuIds());
        return ServerResponseEntity.success();
    }

    @GetMapping("/soldExcel")
    @Operation(summary = "导出excel", description = "导出商品excel")
    public ServerResponseEntity<Void> spuSoldExcel(HttpServletResponse response, SpuPageSearchDTO spuDTO) {
        List<SpuExcelVO> list = spuExcelService.excelSpuList(spuDTO);
        ExcelUtil.soleExcelWithHandler(response, list, SpuExcelVO.EXCEL_NAME, SpuExcelVO.MERGE_ROW_INDEX,
                SpuExcelVO.MERGE_COLUMN_INDEX, new ProductCommentWriteHandler(SysTypeEnum.MULTISHOP.value()), SpuExcelVO.class);
        return ServerResponseEntity.success();
    }

    @GetMapping("/exportModel")
    @Operation(summary = "导出商品excel模板", description = "导出商品excel模板")
    public ServerResponseEntity<Void> exportModel(HttpServletResponse response) {
        spuExcelService.downloadModel(response);
        return ServerResponseEntity.success();
    }

    @Operation(summary = "导入文件")
    @PostMapping("/export_excel")
    public ServerResponseEntity<String> exportExcel(@RequestParam("excelFile") MultipartFile file) {
        if (file == null) {
            throw new LuckException("网络繁忙，请稍后重试");
        }
        // 判断execl文件是否为空
        if (SheetUtil.sheetIsNull(file)) {
            return ServerResponseEntity.success("[导入文件为空]");
        }
        String info;
        try {
            Map<Integer, List<String>> errorMap = new HashMap<>(8);
            EasyExcel.read(file.getInputStream(), SpuExcelVO.class, new SpuExcelListener(spuExcelService, errorMap)).sheet().doRead();
            info = spuExcelService.spuExportError(errorMap);
        } catch (IOException e) {
            throw new LuckException(e.getMessage());
        }
        return ServerResponseEntity.success(info);
    }


    @PostMapping("/offline")
    @Operation(summary = "下线商品", description = "下线商品")
    public ServerResponseEntity<Void> offline(@RequestBody OfflineHandleEventDTO offlineHandleEventDto) {
        if (!Objects.equals(Constant.PLATFORM_SHOP_ID, AuthUserContext.get().getTenantId())) {
            throw new LuckException(ResponseEnum.UNAUTHORIZED);
        }
        SpuVO spuVO = spuService.getBySpuId(offlineHandleEventDto.getHandleId());
        if (spuVO == null) {
            throw new LuckException(ResponseEnum.DATA_ERROR);
        }
        spuService.offline(offlineHandleEventDto);
        spuService.removeSpuCacheBySpuId(offlineHandleEventDto.getHandleId());
        return ServerResponseEntity.success();
    }

    @PostMapping("/batch_offline")
    @Operation(summary = "批量下线商品", description = "批量下线商品")
    public ServerResponseEntity<Void> batchOffline(@RequestBody OfflineHandleEventDTO offlineHandleEventDto) {
        if (!Objects.equals(Constant.PLATFORM_SHOP_ID, AuthUserContext.get().getTenantId())) {
            throw new LuckException(ResponseEnum.UNAUTHORIZED);
        }
        if (CollectionUtil.isEmpty(offlineHandleEventDto.getHandleIds())) {
            throw new LuckException("下线的商品id列表不能为空");
        }
        spuService.batchOffile(offlineHandleEventDto);
        return ServerResponseEntity.success();
    }

    @GetMapping("/getOfflineHandleEvent/{spuId}")
    @Operation(summary = "获取最新下线的事件", description = "获取最新下线的事件")
    public ServerResponseEntity<OfflineHandleEventVO> getOfflineHandleEvent(@PathVariable Long spuId) {
        SpuVO spuDb = spuService.getBySpuId(spuId);
        if (!Objects.equals(spuDb.getShopId(), AuthUserContext.get().getTenantId()) && !Objects.equals(Constant.PLATFORM_SHOP_ID, AuthUserContext.get().getTenantId())) {
            return ServerResponseEntity.fail(ResponseEnum.UNAUTHORIZED);
        }
        return ServerResponseEntity.success(spuService.getOfflineHandleEvent(spuId));
    }

    @PostMapping("/audit")
    @Operation(summary = "审核商品", description = "审核商品")
    public ServerResponseEntity<Void> audit(@RequestBody OfflineHandleEventDTO offlineHandleEventDto) {
        if (!Objects.equals(Constant.PLATFORM_SHOP_ID, AuthUserContext.get().getTenantId())) {
            throw new LuckException(ResponseEnum.UNAUTHORIZED);
        }
        SpuVO spuVO = spuService.getBySpuId(offlineHandleEventDto.getHandleId());
        if (!Objects.equals(spuVO.getStatus(), SpuStatus.WAITAUDIT.value())) {
            // 商品状态已改变，请刷新页面
            throw new LuckException("商品状态已改变，请刷新页面");
        }
        spuService.audit(offlineHandleEventDto);
        spuService.removeSpuCacheBySpuId(offlineHandleEventDto.getHandleId());
        return ServerResponseEntity.success();
    }

    @PostMapping("/auditApply")
    @Operation(summary = "违规活动提交审核", description = "违规活动提交审核")
    public ServerResponseEntity<Void> auditApply(@RequestBody OfflineHandleEventDTO offlineHandleEventDto) {
        SpuVO spuDb = spuService.getBySpuId(offlineHandleEventDto.getHandleId());
        if (!Objects.equals(spuDb.getShopId(), AuthUserContext.get().getTenantId())) {
            return ServerResponseEntity.fail(ResponseEnum.UNAUTHORIZED);
        }
        spuService.auditApply(offlineHandleEventDto);
        return ServerResponseEntity.success();
    }

    @GetMapping("/getSupplierInfoByspuId")
    @Operation(summary = "商家编辑商品时获取供应商商品信息", description = "商家编辑商品时获取供应商商品信息")
    public ServerResponseEntity<SupplierSpuVo> getSupplierInfoBySpuId(Long supplierSpuId) {
        Long shopId = AuthUserContext.get().getTenantId();
        //供应商商品信息
        SupplierSpuVo supplierInfo = spuService.getSupplierInfoBySpuId(supplierSpuId, shopId);
        //属性
        supplierInfo.setSpuAttrValues(spuAttrValueService.getSpuAttrsBySpuId(supplierSpuId));
        // 平台分类、店铺分类信息
        supplierInfo.setCategory(categoryService.getInfo(supplierInfo.getCategoryId()));
        // 品牌信息
        supplierInfo.setBrand(brandService.getByBrandId(supplierInfo.getBrandId()));
        if (Objects.nonNull(supplierInfo.getShopCategoryId()) && !Objects.equals(supplierInfo.getShopCategoryId(), Constant.DEFAULT_ID)) {
            supplierInfo.setShopCategory(categoryService.getInfo(supplierInfo.getShopCategoryId()));
        }
        //获取店铺
        return ServerResponseEntity.success(supplierInfo);
    }


    @PostMapping("/import_supplier_spu")
    @Operation(summary = "商家单个/批量导入供应商商品", description = "商家单个/批量导入供应商商品")
    public ServerResponseEntity<List<Long>> importSupplierSpu(@RequestBody List<Long> supplierSpuId) {
        List<Long> spuIdList = spuService.importSupplierSpu(supplierSpuId);
        return ServerResponseEntity.success(spuIdList);
    }

    @GetMapping("/supplier_excel")
    @Operation(summary = "代销商品导出excel", description = "导出商品excel")
    public ServerResponseEntity<Void> supplierSpuSoldExcel(HttpServletResponse response, SpuPageSearchDTO spuDTO) {
        List<SupplierSpuExcelVO> list = spuExcelService.excelSupplierSpuList(spuDTO);
        ExcelUtil.soleExcelWithHandler(response, list, SupplierSpuExcelVO.EXCEL_NAME, SupplierSpuExcelVO.MERGE_ROW_INDEX,
                SupplierSpuExcelVO.MERGE_COLUMN_INDEX, new ProductCommentWriteHandler(null), SupplierSpuExcelVO.class);
        return ServerResponseEntity.success();
    }

    @GetMapping("/has_stock_by_sku_ids")
    @Operation(summary = "当前关联商品列表是否有共同供货仓库", description = "当前关联商品列表是否有共同供货仓库")
    public ServerResponseEntity<Boolean> hasStockBySkuIds(SkuComboDTO skuComboDTO) {
        Long shopId = AuthUserContext.get().getTenantId();
        Boolean hasStock = skuService.hasStockBySkuIds(skuComboDTO.getSkuIds(),shopId);
        return ServerResponseEntity.success(hasStock);
    }

    private void checkBeforeDeleteSpu(Long spuId, Long shopId) {
        Boolean data = comboFeignClient.checkComboSpu(spuId, shopId).getData();
        if (data) {
            throw new LuckException("参加以下活动的商品不能被删除：优惠套餐");
        }
        GiveawayVO giveawayVO = giveawayService.getBySpuId(spuId);
        List<GiveawaySpuVO> giveawaySpuVOList = giveawaySpuService.getBySpuId(spuId);
        if (giveawayVO != null || CollectionUtils.isNotEmpty(giveawaySpuVOList)) {
            //参加以下活动的商品不能被删除：赠品
            throw new LuckException("参加以下活动的商品不能被删除：赠品");
        }
    }

    /**
     * 处理代销商品信息
     *
     * @param spuVO
     * @return
     */
    private void disposeSpuMsg(SpuVO spuVO) {
        Long spuId = spuVO.getSpuId();
        //获取代销商品基本信息是否改变
        SpuConsignmentChange spuConsignmentChange = spuConsignmentChangeService.consignmentChange(spuId);
        if (Objects.isNull(spuConsignmentChange)) {
            return;
        }
        //获取供应商信息
        SpuVO supplierSpu = spuService.getBySpuId(spuVO.getSupplierSpuId());
        List<SpuLangVO> spuLangList = spuVO.getSpuLangList();
        List<SpuLangVO> supplierSpuLangList = supplierSpu.getSpuLangList();
        Map<Integer, SpuLangVO> supplierSpuLangMap = supplierSpuLangList.stream().collect(Collectors.toMap(SpuLangVO::getLang, e -> e));
        if (Objects.equals(spuVO.getSupplierDeliveryType(), SupplierDeliveryType.SUPPLIER_DELIVERY.value())) {
            //名称
            if (Objects.equals(spuConsignmentChange.getNameChange(), 0)) {
                for (SpuLangVO spuLangVO : spuLangList) {
                    SpuLangVO langVO = supplierSpuLangMap.get(spuLangVO.getLang());
                    if (Objects.isNull(langVO)) {
                        continue;
                    }
                    spuLangVO.setSpuName(langVO.getSpuName());
                }
            }
            //图片
            if (Objects.equals(spuConsignmentChange.getImageChange(), 0)) {
                spuVO.setImgUrls(supplierSpu.getImgUrls());
                spuVO.setMainImgUrl(supplierSpu.getMainImgUrl());
            }
            //视频
            if (Objects.equals(spuConsignmentChange.getVideoChange(), 0)) {
                spuVO.setVideo(supplierSpu.getVideo());
            }
            //卖点
            if (Objects.equals(spuConsignmentChange.getSellingPointChange(), 0)) {
                for (SpuLangVO spuLangVO : spuLangList) {
                    SpuLangVO langVO = supplierSpuLangMap.get(spuLangVO.getLang());
                    if (Objects.isNull(langVO)) {
                        continue;
                    }
                    spuLangVO.setSellingPoint(langVO.getSellingPoint());
                }
            }
            //计量单位
            if (Objects.equals(spuConsignmentChange.getMeasureUnitChange(), 0)) {
                spuVO.setMeasureUnit(supplierSpu.getMeasureUnit());
            }
            //spuCod
            if (Objects.equals(spuConsignmentChange.getSpuCodeChange(), 0)) {
                spuVO.setSpuCode(supplierSpu.getSpuCode());
            }
            //详情描述
            if (Objects.equals(spuConsignmentChange.getDetailChange(), 0)) {
                spuVO.setDetail(supplierSpu.getDetail());
            }
            //品牌
            if (Objects.equals(spuConsignmentChange.getBrandChange(), 0)) {
                // 品牌信息
                spuVO.setBrand(brandService.getByBrandId(supplierSpu.getBrandId()));
            }
            //序号
            spuVO.setSeq(supplierSpu.getSeq());
        }

    }

    private void checkInfo(SpuVO spuVO) {
        if (!Objects.equals(spuVO.getSpuType(), SpuType.SCORE.value())) {
            CategoryVO category = categoryService.getInfo(spuVO.getCategoryId());
            if (category == null || Objects.equals(category.getStatus(), StatusEnum.DISABLE.value())) {
                // 平台分类处于下线中，商品不能上架，请联系管理员后再进行操作
                throw new LuckException("商品【" + spuVO.getName() + "】的平台分类处于下线中，商品不能上架，请联系管理员后再进行操作");
            }
            boolean write = Objects.equals(spuVO.getSpuMold(), 1) && !Objects.equals(0, spuVO.getWriteOffNum()) &&
                    Objects.equals(spuVO.getWriteOffTime(), 0) && Objects.nonNull(spuVO.getWriteOffEnd()) && new Date().after(spuVO.getWriteOffEnd());
            if (write) {
                //商品已过核销有效期
                throw new LuckException("该商品已过核销有效期");
            }
            if (!Objects.equals(spuVO.getSpuType(), SpuType.SCORE.value())) {
                CategoryVO shopCategory = categoryService.getById(spuVO.getShopCategoryId());
                if (shopCategory == null || Objects.equals(shopCategory.getStatus(), StatusEnum.DISABLE.value())) {
                    // 本店分类处于下线中，商品不能上架
                    throw new LuckException("商品【" + spuVO.getName() + "】的本店分类处于下线中，商品不能上架");
                }
            }
            // 商家代销的供应商商品上架，如果是仓库发货，需要检验是否存在物流模板id了
            if (Objects.equals(spuVO.getSupplierSpuType(), SupplierDeliveryType.SHOP_DELIVERY.value()) && Objects.isNull(spuVO.getDeliveryTemplateId())) {
                // 请先设置商品的物流模板
                throw new LuckException("请先设置商品的物流模板： 商品名称【" + spuVO.getName() + "】");
            }
        }
        // 如果商品正在下架，但又是活动商品，代表这个商品所属的活动被平台下架了
        if (Objects.equals(spuVO.getSpuType(), SpuType.SECKILL.value())) {
            throw new LuckException("商品【" + spuVO.getName() + "】所属的秒杀活动处于违规下线中，商品不能上架");
        }
        if (Objects.equals(spuVO.getSpuType(), SpuType.GROUP.value())) {
            throw new LuckException("商品【" + spuVO.getName() + "】所属的团购活动处于违规下线中，商品不能上架");
        }
        if(Objects.equals(spuVO.getSpuMold(),SpuMold.COMBO.value())){
            checkEnableComboSpu(spuVO);
        }
    }

    /**
     * 组合商品上架条件:
     * 1.关联商品 > 0
     * 2.关联商品不为(预售,供应商发货(商家的组合商品))类型
     * 3.关联的商品(sku)都为上架状态
     * @param spuVO
     */
    private void checkEnableComboSpu(SpuVO spuVO) {
        List<SkuVO> skuList = skuService.listSkuWithAttrBySpuId(spuVO.getSpuId());
        List<SkuComboVO> combSpus = skuComboService.getCombSpusBySpuIds(Collections.singletonList(spuVO.getSpuId()));
        Map<Long, List<SkuComboVO>> skuComboMap = combSpus.stream().collect(Collectors.groupingBy(SkuComboVO::getSkuId));
        for (SkuVO skuVO : skuList) {
            if(!skuComboMap.containsKey(skuVO.getSkuId())){
                throw new LuckException("组合商品的每个规格至少关联一个商品");
            }
        }
        Set<Long> spuIds = combSpus.stream().map(SkuComboVO::getComboSpuId).collect(Collectors.toSet());
        Set<Long> skuIds = combSpus.stream().map(SkuComboVO::getComboSkuId).collect(Collectors.toSet());
        int count = spuService.countNormalSpuBySpuIds(spuIds);
        int skuCount = skuService.countNormalSkuBySkuIds(skuIds);
        if(count > 0 || skuCount > 0){
            throw new LuckException("当前组合商品关联的商品状态异常或者类型不对不能进行上架");
        }
    }

    private void checkShop(SpuPageSearchDTO spuDTO) {
        if (Objects.equals(spuDTO.getStatus(), StatusEnum.ENABLE.value()) && !Objects.equals(AuthUserContext.get().getTenantId(), Constant.PLATFORM_SHOP_ID)) {
            // 上架商品时，需要根据店铺状态判断是否可以上架商品
            ServerResponseEntity<EsShopDetailBO> shopRequest = shopDetailFeignClient.getShopByShopId(AuthUserContext.get().getTenantId());
            EsShopDetailBO shopDetail = shopRequest.getData();
            if (!Objects.equals(shopDetail.getShopStatus(), ShopStatus.OPEN.value())) {
                // 合同到期
                if (shopDetail.getContractEndTime() != null && shopDetail.getContractEndTime().compareTo(new Date()) < 0) {
                    throw new LuckException("店铺有效期已过，不能进行此操作，请联系管理员后重试");
                }
                throw new LuckException("店铺处于违规下线状态，不能上架商品");
            }
        }
    }


    /**
     * spu批量上下架
     *
     * @param spuDTO
     */
    private void spuBatchUpdateStatus(SpuPageSearchDTO spuDTO) {
        List<Long> spuIds = spuDTO.getSpuIds();
        Integer status = spuDTO.getStatus();
        spuDTO.setStatus(null);
        List<SpuVO> spuList;
        if (Objects.equals(spuDTO.getSupplierSpuType(), SupplierSpuType.CONSIGNMENT.value())) {
            spuList = spuService.supplierSpuList(spuDTO);
        } else {
            spuList = spuService.list(spuDTO);
        }
        if (CollUtil.isEmpty(spuList)) {
            throw new LuckException("获取不到该商品信息，请刷新后重试");
        }
        checkUpdateStatusData(spuList, status);
        if (CollUtil.isEmpty(spuIds)) {
            throw new LuckException("您所选择的商品中没有符合操作条件的商品");
        }
        spuService.batchChangeSpuStatus(spuIds, status);
    }

    /**
     * 校验spu上下架信息
     *
     * @param list   商品列表
     * @param status 更新的状态
     * @return
     */
    private void checkUpdateStatusData(List<SpuVO> list, Integer status) {
        ProductLangUtil.spuList(list);
        Long shopId = AuthUserContext.get().getTenantId();
        Integer sysType = AuthUserContext.get().getSysType();
        ServerResponseEntity<EsShopDetailBO> shopRequest = shopDetailFeignClient.getShopByShopId(shopId);
        EsShopDetailBO shopDetail = shopRequest.getData();
        if (Objects.equals(shopDetail.getShopStatus(), ShopStatus.OFFLINE.value()) || Objects.equals(shopDetail.getShopStatus(), ShopStatus.OFFLINE_AWAIT_AUDIT.value())) {
            throw new LuckException("店铺处于违规下线中，不能修改商品");
        }
        for (SpuVO spu : list) {
            if (!Objects.equals(spu.getShopId(), shopId) && !Objects.equals(AuthUserContext.get().getTenantId(), Constant.PLATFORM_SHOP_ID)) {
                throw new LuckException(ResponseEnum.UNAUTHORIZED);
            }
            // 商品状态不为启用或未启用状态
            if (!Objects.equals(spu.getStatus(), StatusEnum.ENABLE.value())
                    && !Objects.equals(spu.getStatus(), StatusEnum.DISABLE.value())) {
                throw new LuckException("商品(" + spu.getName() + ")不能进行上下架操作");
            }
            if (Objects.equals(status, StatusEnum.ENABLE.value()) && !Objects.equals(spu.getSpuType(), SpuType.SCORE.value())) {
                CategoryVO category = categoryService.getById(spu.getCategoryId());
                if (!Objects.equals(category.getStatus(), StatusEnum.ENABLE.value())) {
                    throw new LuckException("商品(" + spu.getName() + ")所属的平台分类处于下线中，商品不能进行上架操作，请联系管理员后再进行操作");
                }
                CategoryVO shopCategory = categoryService.getById(spu.getShopCategoryId());
                if (!Objects.equals(shopCategory.getStatus(), StatusEnum.ENABLE.value())) {
                    throw new LuckException("商品(" + spu.getName() + ")所属的店铺分类处于下线中，商品不能进行上架操作");
                }
                CategoryShopVO categoryShopVO = categoryShopService.getByShopIdAndCategoryId(spu.getShopId(), spu.getCategoryId(), sysType);
                if (Objects.isNull(categoryShopVO)) {
                    throw new LuckException("商品(" + spu.getName() + ")所属的平台分类与店铺的签约关系已失效，商品不能进行上架操作");
                }
                // 如果是组合商品,判断一下所有组合的商品是否状态正常,状态正常才可以上线
                if(Objects.equals(spu.getSpuMold(), SpuMold.COMBO.value())){
                    Integer count = skuComboService.countDisableComboSpuBySpuId(spu.getSpuId());
                    if(count > 0){
                        throw new LuckException("请在关联商品状态均为上架时进行操作");
                    }
                }
            }
        }
    }

    /**
     * 更新分销配置信息
     * @param spuId 商品id
     */
    private void updateDistributionAfterDeleteSpu(Long spuId) {
        if (Objects.isNull(spuId)) {
            return;
        }
        // 获取系统分销配置
        String configStr = configFeignClient.getConfig(Constant.DISTRIBUTION_CONFIG).getData();
        if (ObjectUtils.isEmpty(configStr)) {
            return;
        }
        DistributionConfigApiVO distributionConfig = Json.parseObject(configStr, DistributionConfigApiVO.class);
        if (Objects.isNull(distributionConfig)
                || !Objects.equals(distributionConfig.getAutoCheck(), AutoCheckEnum.SYSTEM.value())) {
            return;
        }
        // 没有指定购买商品 或 删除商品不在指定购买商品内，无需处理
        List<Long> spuIds = distributionConfig.getSpuIdList();
        if (CollectionUtil.isEmpty(spuIds)
                || !spuIds.contains(spuId)) {
            return;
        }
        LOGGER.info("商品[{}]删除，更新分销配置", spuId);
        spuIds.remove(spuId);
        // '系统判定'的申请条件全为空，自动切换成'人工判定'
        if (ObjectUtil.isEmpty(spuIds)
                && Objects.isNull(distributionConfig.getExpenseNumber())
                && Objects.isNull(distributionConfig.getExpenseAmount())) {
            distributionConfig.setAutoCheck(AutoCheckEnum.ARTIFICIAL.value());
        }
        // 更新配置
        SysConfigApiVO sysConfig = new SysConfigApiVO();
        sysConfig .setParamKey(Constant.DISTRIBUTION_CONFIG);
        sysConfig .setParamValue(Json.toJsonString(distributionConfig));
        configFeignClient.saveOrUpdateSysConfig(sysConfig );
    }
}
