package com.gree.mall.manager.logic.material.base;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gree.mall.manager.bean.admin.AdminUserCom;
import com.gree.mall.manager.bean.goods.GoodsCategoryBean;
import com.gree.mall.manager.bean.material.base.MaterialCategoryTree;
import com.gree.mall.manager.bean.material.base.WebsitGoodsBean;
import com.gree.mall.manager.bean.material.base.WebsitGoodsMVO;
import com.gree.mall.manager.bean.material.base.WebsitGoodsPVO;
import com.gree.mall.manager.commonmapper.MaterialMapper;
import com.gree.mall.manager.constant.Constant;
import com.gree.mall.manager.enums.material.JudgeEnum;
import com.gree.mall.manager.enums.material.NormTypeEnum;
import com.gree.mall.manager.enums.material.StateEnum;
import com.gree.mall.manager.enums.material.WebsitGoodsTypeEnum;
import com.gree.mall.manager.exception.RemoteServiceException;
import com.gree.mall.manager.logic.brand.BrandLogic;
import com.gree.mall.manager.logic.common.CommonLogic;
import com.gree.mall.manager.logic.common.SysDictCompanyLogic;
import com.gree.mall.manager.logic.goods.GoodsCategoryLogic;
import com.gree.mall.manager.plus.entity.*;
import com.gree.mall.manager.plus.service.*;
import com.gree.mall.manager.utils.CommonUtils;
import com.gree.mall.manager.utils.excel.ExcelUtils;
import com.gree.mall.manager.zfire.bean.WebsitGoodsParamBean;
import com.gree.mall.manager.zfire.util.FieldUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class WebsitGoodsLogic {

    private final CommonLogic commonLogic;
    private final MaterialMapper materialMapper;
    private final WebsitGoodsService websitGoodsService;
    private final WebsitStockService websitStockService;
    private final SysDictCompanyService sysDictCompanyService;
    private final SysDictCompanyLogic sysDictCompanyLogic;
    private final GoodsCategoryService goodsCategoryService;
    private final GoodsCategoryLogic goodsCategoryLogic;
    private final WebsitGoodsCategoryService websitGoodsCategoryService;
    private final MaterialCategoryLogic materialCategoryLogic;
    private final BrandService brandService;
    private final BrandLogic brandLogic;

    public IPage<WebsitGoodsMVO> mPage(WebsitGoodsParamBean zfireParamBean) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        FieldUtils.materialParam(zfireParamBean, WebsitGoodsMVO.class, adminUser);
        IPage<WebsitGoodsMVO> page = materialMapper.mPage(new Page(zfireParamBean.getPageNum(), zfireParamBean.getPageSize()), zfireParamBean);
        if (Objects.nonNull(zfireParamBean.getIsShowStockQty()) && zfireParamBean.getIsShowStockQty() && page.getRecords().size() > 0) {
            List<WebsitStock> stocks = websitStockService.lambdaQuery()
                    .in(WebsitStock::getGoodsId, page.getRecords().stream().map(WebsitGoodsMVO::getGoodsId).collect(Collectors.toList()))
                    .eq(WebsitStock::getCompanyWechatId, adminUser.getCompanyWechatId())
                    .eq(WebsitStock::getWebsitId, zfireParamBean.getWebsitId())
                    .eq(WebsitStock::getStorageId, zfireParamBean.getStorageId())
                    .list();
            if (CollectionUtil.isNotEmpty(stocks)) {
                Map<String, BigDecimal> stockMap = stocks.stream().collect(Collectors.toMap(WebsitStock::getGoodsId, WebsitStock::getQty));
                for (WebsitGoodsMVO vo : page.getRecords()) {
                    vo.setStockQty(stockMap.getOrDefault(vo.getGoodsId(), BigDecimal.ZERO));
                }
            }
        }
        return page;
    }

    public IPage<WebsitGoodsPVO> pPage(WebsitGoodsParamBean zfireParamBean) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        FieldUtils.materialParam(zfireParamBean, WebsitGoodsPVO.class, adminUser);
        IPage<WebsitGoodsPVO> page = materialMapper.pPage(new Page(zfireParamBean.getPageNum(), zfireParamBean.getPageSize()), zfireParamBean);
        if (Objects.nonNull(zfireParamBean.getIsShowStockQty()) && zfireParamBean.getIsShowStockQty() && page.getRecords().size() > 0) {
            List<WebsitStock> stocks = websitStockService.lambdaQuery()
                    .in(WebsitStock::getGoodsId, page.getRecords().stream().map(WebsitGoodsPVO::getGoodsId).collect(Collectors.toList()))
                    .eq(WebsitStock::getCompanyWechatId, adminUser.getCompanyWechatId())
                    .eq(WebsitStock::getWebsitId, zfireParamBean.getWebsitId())
                    .eq(WebsitStock::getStorageId, zfireParamBean.getStorageId())
                    .list();
            if (CollectionUtil.isNotEmpty(stocks)) {
                Map<String, BigDecimal> stockMap = stocks.stream().collect(Collectors.toMap(WebsitStock::getGoodsId, WebsitStock::getQty));
                for (WebsitGoodsPVO vo : page.getRecords()) {
                    vo.setStockQty(stockMap.getOrDefault(vo.getGoodsId(), BigDecimal.ZERO));
                }
            }
        }
        return page;
    }

    public WebsitGoodsBean detail(String id) {
        WebsitGoods goods = websitGoodsService.getById(id);
        WebsitGoodsBean bean = new WebsitGoodsBean();
        BeanUtils.copyProperties(goods, bean);

        if (StringUtils.isNotBlank(goods.getBrandRelaName())) {
            String[] brandRelaNames = goods.getBrandRelaName().split("/");
            bean.setBrandList(Arrays.asList(brandRelaNames));
        }

        if (StringUtils.isNotBlank(goods.getProductRelaName())) {
            String[] productRelaNames = goods.getProductRelaName().split("/");
            bean.setCategoryList(Arrays.asList(productRelaNames));
        }
        return bean;
    }

    @Transactional(rollbackFor = Exception.class)
    public void add(HttpServletRequest request, WebsitGoodsBean bean) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        if (StringUtils.isBlank(bean.getGoodsType())) {
            throw new RemoteServiceException("商品类型不能为空");
        }
        if (bean.getGoodsType().equals(WebsitGoodsTypeEnum.P.getKey())
                && StringUtils.isBlank(bean.getNormType())) {
            throw new RemoteServiceException("收费类型不能为空");
        }
        if (bean.getGoodsType().equals(WebsitGoodsTypeEnum.P.getKey())
                && bean.getNormType().equals(NormTypeEnum.M.getKey())
                && StringUtils.isBlank(bean.getPartType())) {
            throw new RemoteServiceException("配件类型不能为空");
        }
        if (bean.getGoodsType().equals(WebsitGoodsTypeEnum.P.getKey())
                && bean.getNormType().equals(NormTypeEnum.M.getKey())
                && StringUtils.isBlank(bean.getMaterialGroupName())) {
            throw new RemoteServiceException("物料组不能为空");
        }

        bean.setGoodsId(null);
        if (Objects.nonNull(adminUser.getAdminCompanyWechat())) {
            bean.setCompanyWechatId(adminUser.getAdminCompanyWechat().getCompanyWechatId());
            bean.setCompanyWechatName(adminUser.getAdminCompanyWechat().getCompanyName());
        }

        WebsitGoods goods = new WebsitGoods();
        BeanUtils.copyProperties(bean, goods);

        if (StringUtils.isBlank(goods.getNormType())) {
            goods.setNormType(NormTypeEnum.M.getKey());
        }
        if (StringUtils.isNotBlank(goods.getGoodsCategoryId())) {
            WebsitGoodsCategory category = websitGoodsCategoryService.getById(goods.getGoodsCategoryId());
            goods.setParentCategoryId(category.getParentCategoryId());
        }


        // 库存单位不为空时,调用添加处理
        this.stockUnitEmptyAdd(goods);

        this.handlePartsInfo(request, goods, bean);

        // 检查辅材名称、配件代码唯一
        this.checkMaterialUnique(goods);

        if (goods.getGoodsType().equals(WebsitGoodsTypeEnum.M.getKey())) {
            goods.setGoodsId(commonLogic.generateMaterialNo(goods.getCompanyWechatId(), Constant.FC, Constant.FC, 13));
        }
        goods.insert();
    }

    private void checkMaterialUnique(WebsitGoods goods) {
        Integer count = websitGoodsService.lambdaQuery()
                .eq(WebsitGoods::getCompanyWechatId, goods.getCompanyWechatId())
                .ne(StringUtils.isNotBlank(goods.getGoodsId()), WebsitGoods::getGoodsId, goods.getGoodsId())
                .eq(goods.getGoodsType().equals(WebsitGoodsTypeEnum.M.getKey()), WebsitGoods::getGoodsName, goods.getGoodsName())
                .eq(goods.getGoodsType().equals(WebsitGoodsTypeEnum.P.getKey()), WebsitGoods::getGoodsCode, goods.getGoodsCode())
                .eq(WebsitGoods::getGoodsType, goods.getGoodsType())
                .eq(WebsitGoods::getNormType, goods.getNormType())
                .count();
        if (count > 0) {
            if (goods.getGoodsType().equals(WebsitGoodsTypeEnum.M.getKey())) {
                throw new RemoteServiceException("已存在相同名称的辅材，请检查");
            } else {
                if (StringUtils.isNotBlank(goods.getGoodsCode())) {
                    throw new RemoteServiceException("已存在相同编码的配件，请检查");
                }
            }
        }
    }

    private void stockUnitEmptyAdd(WebsitGoods goods) {
        if (goods.getGoodsType().equals(WebsitGoodsTypeEnum.M.getKey())) {
            if (StringUtils.isBlank(goods.getGoodsStockUnit())) {
                throw new RemoteServiceException("库存单位不能为空");
            }
            if (StringUtils.isBlank(goods.getGoodsSalesUnit())) {
                throw new RemoteServiceException("销售单位不能为空");
            }
        }

        String type = goods.getGoodsType().equals(WebsitGoodsTypeEnum.M.getKey()) ? "ASSIST_UNIT" : "PARTS_UNIT";
        Integer count = sysDictCompanyService.lambdaQuery()
                .eq(SysDictCompany::getDictType, type)
                .eq(SysDictCompany::getDictValue, goods.getGoodsStockUnit())
                .count();

        if (count == 0) {
            SysDictCompany company = new SysDictCompany();
            company.setDictType(type)
                    .setDictValue(goods.getGoodsStockUnit());
            sysDictCompanyLogic.saveOpenDict(company);
        }

    }

    private void handlePartsInfo(HttpServletRequest request, WebsitGoods goods, WebsitGoodsBean bean) {
        if (goods.getGoodsType().equals(WebsitGoodsTypeEnum.P.getKey())) {
            if (goods.getNormType().equals(NormTypeEnum.M.getKey())) {
                if (Objects.isNull(goods.getFirstPrice())) {
                    throw new RemoteServiceException("优惠价1不能为空");
                }
                if (Objects.isNull(goods.getSecondPrice())) {
                    throw new RemoteServiceException("优惠价2不能为空");
                }
                if (CollectionUtil.isNotEmpty(bean.getBrandList())) {
                    List<Brand> brandList = brandService.lambdaQuery()
                            .eq(Brand::getCompanyWechatId, bean.getCompanyWechatId())
                            .in(Brand::getBrandName, bean.getBrandList())
                            .list();

                    if (brandList.size() < bean.getBrandList().size()) {
                        Map<String, String> dictValueMap = brandList.stream().collect(Collectors.toMap(Brand::getBrandName, Brand::getBrandName));
                        for (String brand : bean.getBrandList()) {
                            if (!dictValueMap.containsKey(brand)) {
                                Brand company = new Brand();
                                company.setBrandName(brand);
                                brandLogic.save(company, request);
                            }
                        }
                    }

                    String brandRelaId = bean.getBrandList().stream().map(String::toString)
                            .collect(Collectors.joining("/"));
                    String brandRelaName = bean.getBrandList().stream().map(String::toString)
                            .collect(Collectors.joining("/"));
                    if (StringUtils.isBlank(brandRelaId)) {
                        throw new RemoteServiceException("适用品牌不能为空");
                    }
                    goods.setBrandRelaId(brandRelaId)
                            .setBrandRelaName(brandRelaName);
                } else {
                    throw new RemoteServiceException("适用品牌不能为空");
                }
                if (CollectionUtil.isNotEmpty(bean.getCategoryList())) {
                    List<GoodsCategory> categoryList = goodsCategoryService.lambdaQuery()
                            .eq(GoodsCategory::getType, 2)
                            .eq(GoodsCategory::getLevel, 1)
                            .in(GoodsCategory::getName, bean.getCategoryList())
                            .list();

                    if (categoryList.size() < bean.getCategoryList().size()) {
                        Map<String, String> nameMap = categoryList.stream().collect(Collectors.toMap(GoodsCategory::getName, GoodsCategory::getName));
                        for (String name : bean.getCategoryList()) {
                            if (!nameMap.containsKey(name)) {
                                GoodsCategoryBean categoryBean = new GoodsCategoryBean();
                                categoryBean.setType(2)
                                        .setLevel(1)
                                        .setName(name);
                                goodsCategoryLogic.add(categoryBean, request);
                            }
                        }
                    }

                    String categoryRelaId = bean.getCategoryList().stream().map(String::toString)
                            .collect(Collectors.joining("/"));
                    String categoryRelaName = bean.getCategoryList().stream().map(String::toString)
                            .collect(Collectors.joining("/"));
                    if (StringUtils.isBlank(categoryRelaId)) {
                        throw new RemoteServiceException("适用品牌不能为空");
                    }
                    goods.setProductRelaId(categoryRelaId)
                            .setProductRelaName(categoryRelaName);
                } else {
                    throw new RemoteServiceException("适用品牌不能为空");
                }
            }

            if (goods.getNormType().equals(NormTypeEnum.M.getKey()) && Objects.isNull(goods.getNormAmount())) {
                throw new RemoteServiceException("收费标准不能为空");
            }
//
//            if (Objects.isNull(goods.getSelfWorkerAmount())) {
//                if (goods.getNormType().equals(NormTypeEnum.M.getKey())) {
//                    throw new RemoteServiceException("自有库存师傅分账金额不能为空");
//                } else {
//                    throw new RemoteServiceException("师傅分账比例不能为空");
//                }
//            }

//            if (goods.getNormType().equals(NormTypeEnum.M.getKey()) && Objects.isNull(goods.getOutWorkerAmount())) {
//                throw new RemoteServiceException("外购配件师傅分账金额不能为空");
//            }

            // 检查收费标准和分账金额
            BigDecimal selWorkerAmount = goods.getNormAmount();
            BigDecimal selWebsitAmount = BigDecimal.ZERO;
//            BigDecimal outWorkerAmount = BigDecimal.ZERO;
//            BigDecimal outWebsitAmount = BigDecimal.ZERO;
//            if (goods.getNormType().equals(NormTypeEnum.M.getKey())) {
//                if (goods.getSelfWorkerAmount().compareTo(BigDecimal.ZERO) > 0) {
//
//                    if (goods.getSelfWorkerAmount().compareTo(goods.getNormAmount()) > 0) {
//                        throw new RemoteServiceException("自有库存师傅分账金额不能大于收费标准");
//                    }
//
//                    selWorkerAmount = goods.getSelfWorkerAmount();
//                    selWebsitAmount = goods.getNormAmount().subtract(selWorkerAmount);
//                } else {
//                    selWebsitAmount = goods.getNormAmount();
//                }
//
//            } else {
//                if (goods.getSelfWorkerAmount().add(goods.getSelfWebsitAmount()).compareTo(BigDecimal.valueOf(100)) > 0) {
//                    throw new RemoteServiceException("分账比例不能大于100%");
//                }
//                selWorkerAmount = goods.getSelfWorkerAmount();
//                selWebsitAmount = goods.getSelfWebsitAmount();
//            }

//            if (Objects.nonNull(goods.getOutWorkerAmount())
//                    && goods.getOutWorkerAmount().compareTo(BigDecimal.ZERO) > 0) {
//                if (goods.getOutWorkerAmount().compareTo(goods.getNormAmount()) > 0) {
//                    throw new RemoteServiceException("外购库存师傅分账金额不能大于收费标准");
//                }
//                outWorkerAmount = goods.getOutWorkerAmount();
//                outWebsitAmount = goods.getNormAmount().subtract(outWorkerAmount);
//            } else {
//                outWebsitAmount = goods.getNormAmount();
//            }

            goods.setSelfWorkerAmount(selWorkerAmount)
                    .setSelfWebsitAmount(selWebsitAmount)
//                    .setOutWorkerAmount(outWorkerAmount)
//                    .setOutWebsitAmount(outWebsitAmount)
            ;

        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void edit(HttpServletRequest request, WebsitGoodsBean bean) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        if (StringUtils.isBlank(bean.getGoodsType())) {
            throw new RemoteServiceException("商品类型不能为空");
        }

        WebsitGoods oldGoods = websitGoodsService.getById(bean.getGoodsId());

        WebsitGoods goods = new WebsitGoods();
        BeanUtils.copyProperties(bean, goods);
        goods.setCompanyWechatId(oldGoods.getCompanyWechatId())
                .setCompanyWechatName(oldGoods.getCompanyWechatName());

        if (StringUtils.isNotBlank(goods.getGoodsCategoryId())) {
            WebsitGoodsCategory category = websitGoodsCategoryService.getById(goods.getGoodsCategoryId());
            goods.setParentCategoryId(category.getParentCategoryId());
        }

        // 库存单位不为空时,调用添加处理
        this.stockUnitEmptyAdd(goods);

        this.handlePartsInfo(request, goods, bean);

        this.checkMaterialUnique(goods);


        goods.updateById();
    }

    @Transactional(rollbackFor = Exception.class)
    public void batchUpdateStatus(List<String> ids, StateEnum stateEnum) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        if (Objects.isNull(stateEnum)) {
            throw new RemoteServiceException("状态不能为空");
        }
        String companyWechatId = Objects.nonNull(adminUser.getAdminCompanyWechat()) ? adminUser.getAdminCompanyWechat().getCompanyWechatId() : null;
        websitGoodsService.lambdaUpdate()
                .set(WebsitGoods::getStatus, stateEnum.getKey())
                .set(WebsitGoods::getUpdateBy, adminUser.getJoinNickName())
                .set(WebsitGoods::getUpdateTime, DateUtil.date())
                .eq(WebsitGoods::getCompanyWechatId, companyWechatId)
                .in(WebsitGoods::getGoodsId, ids)
                .update();
    }

    public Object materialImportData(MultipartFile file) throws Exception {

        AdminUserCom adminUser = commonLogic.getAdminUser();

        String companyWechatId = Objects.nonNull(adminUser.getAdminCompanyWechat()) ? adminUser.getAdminCompanyWechat().getCompanyWechatId() : null;
        String companyName = Objects.nonNull(adminUser.getAdminCompanyWechat()) ? adminUser.getAdminCompanyWechat().getCompanyName() : null;

        List<Object> objects = ExcelUtils.importExcel(file);
        List<WebsitGoods> goodsList = new ArrayList<>();

        List<MaterialCategoryTree> categoryTrees = materialCategoryLogic.materialCategoryTree(null);

        Map<String, MaterialCategoryTree> treeMap = categoryTrees.stream()
                .collect(Collectors.toMap(MaterialCategoryTree::getCategoryName, Function.identity()));

        List<String> unitList = sysDictCompanyService.lambdaQuery()
                .eq(SysDictCompany::getDictType, "ASSIST_UNIT")
                .list()
                .stream()
                .map(SysDictCompany::getDictValue)
                .collect(Collectors.toList());

        for (int i = 0; i < objects.size(); i++) {
            List<Object> row = (List<Object>) objects.get(i);
            CommonUtils.initList2(row, 14);
            if (Objects.isNull(row.get(0))) {
                throw new RemoteServiceException("第" + (i+1) + "行, 大类不能为空");
            }
            if (Objects.isNull(row.get(1))) {
                throw new RemoteServiceException("第" + (i+1) + "行, 小类不能为空");
            }
            if (Objects.isNull(row.get(2))) {
                throw new RemoteServiceException("第" + (i+1) + "行, 辅材名称不能为空");
            }
            if (Objects.isNull(row.get(3))) {
                throw new RemoteServiceException("第" + (i+1) + "行, 库存单位不能为空");
            }
            if (Objects.isNull(row.get(4))) {
                throw new RemoteServiceException("第" + (i+1) + "行, 销售单位不能为空");
            }
            if (Objects.isNull(row.get(5))) {
                throw new RemoteServiceException("第" + (i+1) + "行, 采购价格不能为空");
            }
            if (Objects.isNull(row.get(6))) {
                throw new RemoteServiceException("第" + (i+1) + "行, 销售价格不能为空");
            }
            if (Objects.isNull(row.get(7))) {
                throw new RemoteServiceException("第" + (i+1) + "行, 进价最小值不能为空");
            }
            if (Objects.isNull(row.get(8))) {
                throw new RemoteServiceException("第" + (i+1) + "行, 进价最大值不能为空");
            }

            String parentCategoryStr = (String) row.get(0);
            String categoryStr = (String) row.get(1);
            String goodsNameStr = (String) row.get(2);
            String unitStr = (String) row.get(3);
            String saleUnitStr = (String) row.get(4);
            String costStr = (String) row.get(5);
            String salesStr = (String) row.get(6);
            String costMiniStr = (String) row.get(7);
            String costMaxStr = (String) row.get(8);
            String goodsCodeStr = (String) row.get(9);
            String specificationStr = (String) row.get(10);
            String remark = (String) row.get(11);
            String manageWorkerStock = (String) row.get(12);
            String salesConvertQty = (String) row.get(13);

            if (!treeMap.containsKey(parentCategoryStr)) {
                throw new RemoteServiceException("第" + (i+1) + "行, 大类信息不存在");
            }
            MaterialCategoryTree categoryTree = treeMap.get(parentCategoryStr);
            if (CollectionUtil.isEmpty(categoryTree.getChild())) {
                throw new RemoteServiceException("第" + (i+1) + "行, 小类信息不存在");
            }
            Map<String, MaterialCategoryTree> childMap = categoryTree.getChild()
                    .stream()
                    .collect(Collectors.toMap(MaterialCategoryTree::getCategoryName, Function.identity()));
            if (!childMap.containsKey(categoryStr)) {
                throw new RemoteServiceException("第" + (i+1) + "行, 小类信息不存在");
            }
            MaterialCategoryTree child = childMap.get(categoryStr);

            Integer count = websitGoodsService.lambdaQuery()
                    .eq(WebsitGoods::getCompanyWechatId, companyWechatId)
                    .eq(WebsitGoods::getGoodsType, WebsitGoodsTypeEnum.M.getKey())
                    .eq(WebsitGoods::getGoodsName, goodsNameStr)
                    .count();

            if (count > 0) {
                throw new RemoteServiceException("第" + (i+1) + "行, 辅材名称重复");
            }

            if (!unitList.contains(unitStr)) {
                throw new RemoteServiceException("第" + (i+1) + "行, 库存单位信息不存在");
            }

            if (!unitList.contains(saleUnitStr)) {
                throw new RemoteServiceException("第" + (i+1) + "行, 销售单位信息不存在");
            }

            WebsitGoods goods = new WebsitGoods();

            goods.setCompanyWechatId(companyWechatId);
            goods.setCompanyWechatName(companyName);
            goods.setGoodsType(WebsitGoodsTypeEnum.M.getKey());
            goods.setGoodsName(goodsNameStr);
            goods.setGoodsCode(goodsCodeStr);
            goods.setParentCategoryId(categoryTree.getCategoryId());
            goods.setGoodsCategoryId(child.getCategoryId());
            goods.setGoodsSpecification(specificationStr);
            goods.setRemark(remark);
            goods.setCost(new BigDecimal(costStr));
            goods.setMarketPrice(new BigDecimal(salesStr));
            goods.setCostRangeMini(new BigDecimal(costMiniStr));
            goods.setCostRangeMax(new BigDecimal(costMaxStr));

            goods.setGoodsStockUnit(StrUtil.trim(unitStr));
            goods.setGoodsSalesUnit(StrUtil.trim(saleUnitStr));
            if (StringUtils.isBlank(manageWorkerStock) || manageWorkerStock.equals(JudgeEnum.YES.getRemark())) {
                goods.setManageWorkerStock(JudgeEnum.YES.getKey());
            } else {
                goods.setManageWorkerStock(JudgeEnum.NO.getKey());
            }

            if (StringUtils.isNotBlank(salesConvertQty)) {
                BigDecimal convertQty = new BigDecimal(salesConvertQty);
                goods.setGoodsSalesConvertQty(convertQty);
            }

            goods.setNormType(NormTypeEnum.M.getKey());

            goodsList.add(goods);
        }

        if (CollectionUtil.isNotEmpty(goodsList)) {
            // 检查导入名称唯一
            Map<String, List<WebsitGoods>> keyMap = goodsList.stream()
                    .collect(Collectors.groupingBy(WebsitGoods::getGoodsName));
            for (Map.Entry<String, List<WebsitGoods>> entry : keyMap.entrySet()) {
                if (entry.getValue().size() > 1) {
                    WebsitGoods product = entry.getValue().get(0);
                    throw new RemoteServiceException("导入文档里的 " + product.getGoodsName() + ", 辅材名称不能重复");
                }
            }
            for (WebsitGoods goods : goodsList) {
                this.checkMaterialUnique(goods);
            }

            for (WebsitGoods goods : goodsList) {
                goods.setGoodsId(commonLogic.generateMaterialNo(goods.getCompanyWechatId(), Constant.FC, Constant.FC, 13));
            }

            websitGoodsService.saveBatch(goodsList);
        }

        return null;
    }

    public Object partsImportData(MultipartFile file) throws IOException {
        AdminUserCom adminUser = commonLogic.getAdminUser();

        String companyWechatId = Objects.nonNull(adminUser.getAdminCompanyWechat()) ? adminUser.getAdminCompanyWechat().getCompanyWechatId() : null;
        String companyName = Objects.nonNull(adminUser.getAdminCompanyWechat()) ? adminUser.getAdminCompanyWechat().getCompanyName() : null;

        List<Object> objects = ExcelUtils.importExcel(file);
        List<WebsitGoods> goodsList = new ArrayList<>();

        List<String> unitList = sysDictCompanyService.lambdaQuery()
                .eq(SysDictCompany::getCompanyWechatId, companyWechatId)
                .eq(SysDictCompany::getDictType, "PARTS_UNIT")
                .list()
                .stream()
                .map(SysDictCompany::getDictValue)
                .collect(Collectors.toList());

        Map<String, String> brandMap = brandService.lambdaQuery()
                .eq(Brand::getCompanyWechatId, companyWechatId)
                .list()
                .stream()
                .collect(Collectors.toMap(Brand::getBrandName, Brand::getBrandName));

        Map<String, String> categoryMap = goodsCategoryService.lambdaQuery()
                .eq(GoodsCategory::getCompanyWechatId, companyWechatId)
                .eq(GoodsCategory::getType, 2)
                .eq(GoodsCategory::getLevel, 1)
                .list()
                .stream()
                .collect(Collectors.toMap(GoodsCategory::getName, GoodsCategory::getName));

        for (int i = 0; i < objects.size(); i++) {
            List<Object> row = (List<Object>) objects.get(i);
            CommonUtils.initList2(row, 12);
            if (row.size() < 7) {
                row.add(null);
                row.add(null);
            }
            if (row.size() < 8) {
                row.add(null);
            }
            if (Objects.isNull(row.get(0))) {
                throw new RemoteServiceException("第" + (i+1) + "行, 配件名称不能为空");
            }
            if (Objects.isNull(row.get(1))) {
                throw new RemoteServiceException("第" + (i+1) + "行, 单位不能为空");
            }
            if (Objects.isNull(row.get(2))) {
                throw new RemoteServiceException("第" + (i+1) + "行, 市场价格不能为空");
            }
            if (Objects.isNull(row.get(3))) {
                throw new RemoteServiceException("第" + (i+1) + "行, 适用品牌不能为空");
            }
            if (Objects.isNull(row.get(4))) {
                throw new RemoteServiceException("第" + (i+1) + "行, 适用产品大类不能为空");
            }
            if (Objects.isNull(row.get(5))) {
                throw new RemoteServiceException("第" + (i+1) + "行, 配件类型不能为空");
            }
            if (Objects.isNull(row.get(6))) {
                throw new RemoteServiceException("第" + (i+1) + "行, 物料组不能为空");
            }
//            if (Objects.isNull(row.get(6))) {
//                throw new RemoteServiceException("第" + (i+1) + "行, 自有库存师傅分账金额不能为空");
//            }
//            if (Objects.isNull(row.get(7))) {
//                throw new RemoteServiceException("第" + (i+1) + "行, 外购库存师傅分账金额不能为空");
//            }

            String goodsNameStr = (String) row.get(0);
            String unitStr = (String) row.get(1);
            String salesStr = (String) row.get(2);
//            String normAmountStr = (String) row.get(3);
            String brandStr = (String) row.get(3);
            String categoryStr = (String) row.get(4);
//            String selfAmountStr = (String) row.get(6);
            String partType = (String) row.get(5);
            String materialGroupName = (String) row.get(6);
            String goodsCodeStr = (String) row.get(7);
            String remark = (String) row.get(8);

//            Integer count = websitGoodsService.lambdaQuery()
//                    .eq(WebsitGoods::getCompanyWechatId, companyWechatId)
//                    .eq(WebsitGoods::getGoodsType, WebsitGoodsTypeEnum.P.getKey())
//                    .eq(WebsitGoods::getNormType, NormTypeEnum.M.getKey())
//                    .eq(WebsitGoods::getGoodsName, goodsNameStr)
//                    .count();
//
//            if (count > 0) {
//                throw new RemoteServiceException("第" + (i+1) + "行, 配件名称重复");
//            }

            if (!unitList.contains(unitStr)) {
                throw new RemoteServiceException("第" + (i+1) + "行, 单位信息不存在");
            }

            List<String> brandList = Arrays.stream(brandStr.split("/")).collect(Collectors.toList());
            for (String brand : brandList) {
                if (brand.equals("通用")) {
                    brandStr = "通用";
                    break;
                }
                if (!brandMap.containsKey(brand)) {
                    throw new RemoteServiceException("第" + (i + 1) + "行, 品牌信息不存在");
                }
            }

            List<String> categoryList = Arrays.stream(categoryStr.split("/")).collect(Collectors.toList());
            for (String c : categoryList) {
                if (c.equals("通用")) {
                    categoryStr = "通用";
                    break;
                }
                if (!categoryMap.containsKey(c)) {
                    throw new RemoteServiceException("第" + (i + 1) + "行, 产品大类信息不存在");
                }
            }

//            BigDecimal normAmount = new BigDecimal(normAmountStr);
//            BigDecimal selfAmount = new BigDecimal(selfAmountStr);
//            BigDecimal outAmount = new BigDecimal(outAmountStr);
//
//            if (selfAmount.compareTo(normAmount) > 0) {
//                throw new RemoteServiceException("第" + (i + 1) + "行, 自有库存师傅分账金额不能大于收费标准");
//            }

            if (!"空调-冰箱-生活电器".contains(partType)) {
                throw new RemoteServiceException("第" + (i + 1) + "行, 配件类型错误");
            }


            WebsitGoods goods = new WebsitGoods();

            goods.setCompanyWechatId(companyWechatId);
            goods.setCompanyWechatName(companyName);
            goods.setGoodsType(WebsitGoodsTypeEnum.P.getKey());
            goods.setGoodsName(goodsNameStr);
            goods.setGoodsCode(goodsCodeStr);
            goods.setRemark(remark);
            goods.setMarketPrice(new BigDecimal(salesStr));
//            goods.setNormAmount(normAmount);
//            goods.setSelfWorkerAmount(normAmount);
//            goods.setSelfWebsitAmount(normAmount.subtract(selfAmount));
//            goods.setOutWorkerAmount(outAmount);
//            goods.setOutWebsitAmount(normAmount.subtract(outAmount));
            goods.setBrandRelaName(brandStr);
            goods.setProductRelaName(categoryStr);


            // 库存单位与销售单位一致
            goods.setGoodsStockUnit(StrUtil.trim(unitStr));
            goods.setGoodsSalesUnit(StrUtil.trim(unitStr));
            goods.setMaterialGroupName(StrUtil.trim(materialGroupName));
            goods.setManageWorkerStock(JudgeEnum.YES.getKey());
            goods.setNormType(NormTypeEnum.M.getKey());
            goods.setPartType(partType);

            goodsList.add(goods);
        }

        if (CollectionUtil.isNotEmpty(goodsList)) {
            // 检查list唯一
            this.checkListUniqueParts(goodsList);
            // 检查数据库唯一
            for (WebsitGoods goods : goodsList) {
                this.checkMaterialUnique(goods);
            }
            websitGoodsService.saveBatch(goodsList);
        }

        return null;
    }

    public Object partsImportData2(MultipartFile file) throws IOException {
        AdminUserCom adminUser = commonLogic.getAdminUser();

        String companyWechatId = Objects.nonNull(adminUser.getAdminCompanyWechat()) ? adminUser.getAdminCompanyWechat().getCompanyWechatId() : null;
        String companyName = Objects.nonNull(adminUser.getAdminCompanyWechat()) ? adminUser.getAdminCompanyWechat().getCompanyName() : null;

        List<Object> objects = ExcelUtils.importExcel(file);
        List<WebsitGoods> goodsList = new ArrayList<>();

        List<String> unitList = sysDictCompanyService.lambdaQuery()
                .eq(SysDictCompany::getCompanyWechatId, companyWechatId)
                .eq(SysDictCompany::getDictType, "PARTS_UNIT")
                .list()
                .stream()
                .map(SysDictCompany::getDictValue)
                .collect(Collectors.toList());

        for (int i = 0; i < objects.size(); i++) {
            List<Object> row = (List<Object>) objects.get(i);
            if (row.size() < 4) {
                row.add(null);
                row.add(null);
            }
            if (row.size() < 5) {
                row.add(null);
            }
            if (Objects.isNull(row.get(0))) {
                throw new RemoteServiceException("第" + (i+1) + "行, 配件名称不能为空");
            }
            if (Objects.isNull(row.get(1))) {
                throw new RemoteServiceException("第" + (i+1) + "行, 单位不能为空");
            }
            if (Objects.isNull(row.get(2))) {
                throw new RemoteServiceException("第" + (i+1) + "行, 师傅分账比例(%)不能为空");
            }

            String goodsNameStr = (String) row.get(0);
            String unitStr = (String) row.get(1);
            String selfAmountStr = (String) row.get(2);
            String goodsCodeStr = (String) row.get(3);
            String remark = (String) row.get(4);

//            Integer count = websitGoodsService.lambdaQuery()
//                    .eq(WebsitGoods::getCompanyWechatId, companyWechatId)
//                    .eq(WebsitGoods::getGoodsType, WebsitGoodsTypeEnum.P.getKey())
//                    .eq(WebsitGoods::getNormType, NormTypeEnum.S.getKey())
//                    .eq(WebsitGoods::getGoodsName, goodsNameStr)
//                    .count();
//
//            if (count > 0) {
//                throw new RemoteServiceException("第" + (i+1) + "行, 配件名称重复");
//            }

            if (!unitList.contains(unitStr)) {
                throw new RemoteServiceException("第" + (i+1) + "行, 单位信息不存在");
            }

            BigDecimal selfAmount = new BigDecimal(selfAmountStr);

            if (selfAmount.compareTo(BigDecimal.valueOf(100)) > 0) {
                throw new RemoteServiceException("第" + (i+1) + "行, 师傅分账比例(%)不能大于100");
            }

            WebsitGoods goods = new WebsitGoods();

            goods.setCompanyWechatId(companyWechatId);
            goods.setCompanyWechatName(companyName);
            goods.setGoodsType(WebsitGoodsTypeEnum.P.getKey());
            goods.setGoodsName(goodsNameStr);
            goods.setGoodsCode(goodsCodeStr);
            goods.setRemark(remark);
            goods.setSelfWorkerAmount(selfAmount);
            goods.setSelfWebsitAmount(new BigDecimal("100").subtract(selfAmount));


            // 库存单位与销售单位一致
            goods.setGoodsStockUnit(StrUtil.trim(unitStr));
            goods.setGoodsSalesUnit(StrUtil.trim(unitStr));
            goods.setManageWorkerStock(JudgeEnum.YES.getKey());
            goods.setNormType(NormTypeEnum.S.getKey());

            goodsList.add(goods);
        }

        if (CollectionUtil.isNotEmpty(goodsList)) {
            // 检查list唯一
            this.checkListUniqueParts(goodsList);
            // 检查数据库唯一
            for (WebsitGoods goods : goodsList) {
                this.checkMaterialUnique(goods);
            }
            websitGoodsService.saveBatch(goodsList);
        }
        return null;
    }

    private void checkListUniqueParts(List<WebsitGoods> items) {
        Map<String, List<WebsitGoods>> keyMap = items.stream()
                .filter(v -> StringUtils.isNotBlank(v.getGoodsCode()))
                .collect(Collectors.groupingBy(WebsitGoods::getGoodsCode));
        if (CollectionUtil.isNotEmpty(keyMap)) {
            for (Map.Entry<String, List<WebsitGoods>> entry : keyMap.entrySet()) {
                if (entry.getValue().size() > 1) {
                    WebsitGoods product = entry.getValue().get(0);
                    throw new RemoteServiceException("导入文档里的 " + product.getGoodsName() + ", 配件发现重复编码");
                }
            }
        }
    }
}
