package com.gree.mall.manager.logic.goods;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gree.mall.manager.bean.ExcelData;
import com.gree.mall.manager.bean.admin.AdminUserCom;
import com.gree.mall.manager.bean.goods.*;
import com.gree.mall.manager.commonmapper.CustomGoodsMapper;
import com.gree.mall.manager.commonmapper.GoodsCheckMapper;
import com.gree.mall.manager.constant.Constant;
import com.gree.mall.manager.enums.*;
import com.gree.mall.manager.exception.RemoteServiceException;
import com.gree.mall.manager.logic.common.CommonLogic;
import com.gree.mall.manager.logic.user.UserLogic;
import com.gree.mall.manager.plus.entity.*;
import com.gree.mall.manager.plus.service.*;
import com.gree.mall.manager.utils.DateUtils;
import com.gree.mall.manager.utils.StringUtil;
import com.gree.mall.manager.utils.excel.ExcelUtils;
import com.gree.mall.manager.zfire.bean.ZfireParamBean;
import com.gree.mall.manager.zfire.util.FieldUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Slf4j
@Component
public class GoodsLogic {
    @Resource
    CommonLogic commonLogic;

    @Resource
    CustomGoodsMapper customGoodsMapper;
    @Resource
    GoodsService goodsService;
    @Resource
    GoodsSpecService goodsSpecService;
    @Autowired
    GoodsTagRelaService goodsTagRelaService;
    @Autowired
    GoodsCategoryService goodsCategoryService;

    @Resource
    SecKillActivityService secKillActivityService;
    @Resource
    SecKillActivitySpecService secKillActivitySpecService;
    @Autowired
    private CarouselMapService carouselMapService;
    @Autowired
    private GoodsCheckMapper goodsCheckMapper;
    @Autowired
    private GoodsTemplateService goodsTemplateService;
    @Autowired
    private CommonFileService commonFileService;
    @Value("${goods.share.limit.percent}")
    private String percentLimit;
    @Autowired
    GoodsPackagePopService goodsPackagePopService;
    @Autowired
    GoodsPackageUserRelaService goodsPackageUserRelaService;
    @Autowired
    UserLogic userLogic;
    @Autowired
    AdminCompanyWechatService adminCompanyWechatService;
    @Autowired
    FreightTemplateService freightTemplateService;
    @Autowired
    FreightTemplateDetailService freightTemplateDetailService;

    @Autowired
    GoodsCompanyService goodsCompanyService;

    @Autowired
    AdminCompanyService adminCompanyService;

    /**
     * 商品列表
     *
     * @param flag
     * @param keyword
     * @param startPrice
     * @param endPrice
     * @param startShare
     * @param endShare
     * @param goodsSortJson
     * @param categoryId
     * @param status
     * @param pageNum
     * @param pageSize
     * @return
     */
    public IPage<GoodsSpecBean> page(String flag, String keyword, BigDecimal startPrice, BigDecimal endPrice,
                                     BigDecimal startShare, BigDecimal endShare,
                                     String goodsSortJson, String categoryId, Boolean status,List<String> goodsTypes,
                                     Integer pageNum, Integer pageSize, HttpServletRequest request) {

        //获取当前登录微信企业微信id
        AdminUserCom adminUser = commonLogic.getAdminUser(request);
        List<String> companyIds = adminUser.getAdminCompanyIds();

        String sortStr = null;
        if (goodsSortJson != null && !goodsSortJson.trim().equals("")) {
            JSONArray goodsSortBeanArray = JSON.parseArray(StringEscapeUtils.unescapeJava(goodsSortJson));
            sortStr = GoodsSortBean.convertColumn(goodsSortBeanArray);
        }
        List<String> categoryIds = new ArrayList<>();
        if (StringUtils.isNotEmpty(categoryId)) {
            categoryIds.add(categoryId);
        }
        if(CollectionUtils.isEmpty(goodsTypes)){
            goodsTypes = new ArrayList<>();
            goodsTypes.add(GoodsTypeEnum.COMMON.toString());
        }

        IPage<GoodsSpecBean> goodsSpecBeanIPage = customGoodsMapper.pageList(new Page<>(pageNum, pageSize), flag, keyword, startPrice,
                endPrice, startShare, endShare, sortStr, categoryIds, status, goodsTypes,adminUser.getAdminCompanyIds());

        //商品规格
        for (GoodsSpecBean goodsSpecBean : goodsSpecBeanIPage.getRecords()) {
            String goodsId = goodsSpecBean.getGoodsId();
            List<GoodsSpec> list = goodsSpecService.lambdaQuery().eq(GoodsSpec::getGoodsId, goodsId).list();
            goodsSpecBean.setGoodsSpecs(list);
        }
        return goodsSpecBeanIPage;
    }


    /**
     * 套购商品列表
     * @param keyword
     * @param startPrice
     * @param endPrice
     * @param startShare
     * @param endShare
     * @param goodsSortJson
     * @param categoryId
     * @param status
     * @param pageNum
     * @param pageSize
     * @param request
     * @return
     */
    public IPage<GoodsPackageList> packageList( String keyword, BigDecimal startPrice, BigDecimal endPrice,
                                     BigDecimal startShare, BigDecimal endShare,
                                     String goodsSortJson, String categoryId, Boolean status,
                                     Integer pageNum, Integer pageSize, HttpServletRequest request) {

        //获取当前登录微信企业微信id
        AdminUserCom adminUser = commonLogic.getAdminUser(request);
        List<String> companyIds = adminUser.getAdminCompanyIds();

        String sortStr = null;
        if (goodsSortJson != null && !goodsSortJson.trim().equals("")) {
            JSONArray goodsSortBeanArray = JSON.parseArray(StringEscapeUtils.unescapeJava(goodsSortJson));
            sortStr = GoodsSortBean.convertColumn(goodsSortBeanArray);
        }
        List<String> categoryIds = new ArrayList<>();
        if (StringUtils.isNotEmpty(categoryId)) {
            categoryIds.add(categoryId);
        }

        IPage<GoodsPackageList> goodsPackageListIPage = customGoodsMapper.queryGoodsPackageList(new Page<>(pageNum, pageSize), keyword, startPrice,
                endPrice, startShare, endShare, sortStr, categoryIds, status, companyIds);

        return goodsPackageListIPage;
    }


    /**
     * 根据类型查询商品
     * @param categoryIds
     * @param request
     * @return
     */
    public List<GoodsSpecBean> listbycategory(List<String> categoryIds, HttpServletRequest request) {

        //获取当前登录微信企业微信id
        AdminUserCom adminUser = commonLogic.getAdminUser(request);
        List<String> companyIds = adminUser.getAdminCompanyIds();


        IPage<GoodsSpecBean> goodsSpecBeanIPage = customGoodsMapper.pageList(new Page<>(1, -1), null, null, null,
                null, null, null, null, categoryIds, null, null,companyIds);
        //添加规格
        List<GoodsSpecBean> records = goodsSpecBeanIPage.getRecords();
        for (GoodsSpecBean record : records) {
            List<GoodsSpec> goodsSpecs = goodsSpecService.lambdaQuery()
                    .eq(GoodsSpec::getGoodsId, record.getGoodsId())
                    .eq(GoodsSpec::getDel, false)
                    .list();
            record.setGoodsSpecs(goodsSpecs);
        }
        goodsSpecBeanIPage.setRecords(records);
        return goodsSpecBeanIPage.getRecords();
    }


    /**
     * 商品上下架
     *
     * @param goodsId
     * @param status
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateStatus(String goodsId, Boolean status) throws RemoteServiceException {
        if (!status) {
            List<SecKillActivitySpec> secKillActivitySpecs = secKillActivitySpecService.lambdaQuery()
                    .eq(SecKillActivitySpec::getGoodsId, goodsId)
                    .list();
            Integer activityCount = 0;
            for (SecKillActivitySpec secKillActivitySpec : secKillActivitySpecs) {

                activityCount += secKillActivityService.lambdaQuery()
                        .eq(SecKillActivity::getSecKillId, secKillActivitySpec.getSecKillId())
                        .ge(SecKillActivity::getEndTime, new Date())
                        .eq(SecKillActivity::getStatus, true)
                        .eq(SecKillActivity::getDel, false)
                        .count();
            }

            if (activityCount > 0) {
                throw new RemoteServiceException("商品处于秒杀活动中，操作失败!");
            }
        }
        goodsService.lambdaUpdate()
                .eq(Goods::getGoodsId, goodsId)
                .set(Goods::getStatus, status)
                .update();

        if (!status) {
            carouselMapService.lambdaUpdate().eq(CarouselMap::getGoodsId, goodsId).remove();
        }
    }


    /**
     * 删除商品
     *
     * @param goodsId
     */
    @Transactional(rollbackFor = Exception.class)
    public void delete(String goodsId) throws RemoteServiceException {
        //检查是否存在秒杀活动
        List<SecKillActivitySpec> secKillActivitySpecs = secKillActivitySpecService.lambdaQuery()
                .eq(SecKillActivitySpec::getGoodsId, goodsId)
                .list();
        Integer activityCount = 0;
        for (SecKillActivitySpec secKillActivitySpec : secKillActivitySpecs) {

            activityCount += secKillActivityService.lambdaQuery()
                    .eq(SecKillActivity::getSecKillId, secKillActivitySpec.getSecKillId())
                    .ge(SecKillActivity::getEndTime, new Date())
                    .eq(SecKillActivity::getStatus, true)
                    .eq(SecKillActivity::getDel, false)
                    .count();
        }

        if (activityCount > 0) {
            throw new RemoteServiceException("商品处于秒杀活动中，操作删除失败!");
        }

        //检查是否在上架状态
        Integer count = goodsService.lambdaQuery()
                .eq(Goods::getGoodsId, goodsId)
                .eq(Goods::getStatus, true)
                .count();
        if (count > 0) {
            throw new RemoteServiceException("商品处于上架状态，操作删除失败!");
        }

        goodsService.lambdaUpdate()
                .eq(Goods::getGoodsId, goodsId)
                .remove();
        goodsSpecService.lambdaUpdate().eq(GoodsSpec::getGoodsId, goodsId).remove();
    }


    /**
     * 批量修改分类
     * @param goodsCategoryUpdateBean
     */
    public void updateCategory(GoodsCategoryUpdateBean goodsCategoryUpdateBean){
        goodsService.lambdaUpdate()
                .set(Goods::getCategoryId,goodsCategoryUpdateBean.getCategoryId())
                .in(Goods::getGoodsId,goodsCategoryUpdateBean.getGoodsIds())
                .update();
    }

    /**
     * 商品详情
     * @param goodsId
     * @return
     */
    public GoodsBean detail(String goodsId) throws RemoteServiceException {
        Goods goods = goodsService.getById(goodsId);
        List<GoodsSpec> goodsSpecs = goodsSpecService.lambdaQuery()
                .eq(GoodsSpec::getGoodsId, goodsId)
                .eq(GoodsSpec::getDel, false)
                .list();

        //商品库存
        Integer goodsStock = goodsSpecs.stream().collect(Collectors.summingInt(x -> x.getStockNum()));

        GoodsBean goodsBean = new GoodsBean();
        if (goods == null) {
            throw new RemoteServiceException("商品不存在");
        }
        BeanUtils.copyProperties(goods, goodsBean);
        goodsBean.setGoodsSpecs(goodsSpecs);
        goodsBean.setImages(commonLogic.queryFileByObjId(goods.getGoodsId(), Constant.Img.GOODS_IMG));
        goodsBean.setStock(goodsStock);
        List<GoodsTemplate> goodsTemplates = goodsTemplateService.lambdaQuery()
                .eq(GoodsTemplate::getGoodsId, goodsId)
                .orderByDesc(GoodsTemplate::getCreateTime)
                .list();
        if (goodsTemplates != null && goodsTemplates.size() > 0) {
            goodsBean.setTemplateId(goodsTemplates.get(0).getTemplateId());
        }
        //查询商品标签
        List<GoodsTagRela> goodsTagRela = goodsTagRelaService.lambdaQuery().eq(GoodsTagRela::getGoodsId, goodsId)
                .eq(GoodsTagRela::getType,1).list();
        if(goodsTagRela.size() > 0){
            List<String> tagList = goodsTagRela.stream().map(GoodsTagRela::getGoodsTagName).collect(Collectors.toList());
            goodsBean.setTags(tagList);
        }

        List<GoodsTagRela> goodsTagRelas = goodsTagRelaService.lambdaQuery().eq(GoodsTagRela::getGoodsId, goodsId)
                .eq(GoodsTagRela::getType,2).list();
        if(goodsTagRelas.size() > 0){
            List<String> tagList = goodsTagRelas.stream().map(GoodsTagRela::getGoodsTagName).collect(Collectors.toList());
            goodsBean.setTagsLabel(tagList);
        }
        if(StringUtils.equals(goodsBean.getGoodsType(),GoodsTypeEnum.PACKAGE.toString())) {
            //套购商品--指定人员列表
            goodsBean.setUsers(this.getPackageUseUserList(goodsBean.getGoodsId(), null));
        }
        return goodsBean;
    }

    /**
     * 套购商品-商品配置列表
     */
    public List<GoodsPackageBean> popList(String goodsId,Integer type){
        //套购商品
        Goods goods = goodsService.getById(goodsId);
        if(!StringUtils.equals(goods.getGoodsType(),GoodsTypeEnum.PACKAGE.toString())){
            throw new RemoteServiceException("非套餐商品");
        }

        //套购商品--商品配置
        List<GoodsPackagePop> list = goodsPackagePopService.lambdaQuery()
                .eq(GoodsPackagePop::getGoodsPackageId, goodsId)
                .eq(GoodsPackagePop::getType,type).list();

        Map<String,List<GoodsPackagePopBean>> map = new LinkedHashMap<>();
        for (GoodsPackagePop bean : list) {
            List<GoodsPackagePopBean> goodsPackagePops = map.get(bean.getGoodsId());
            if(goodsPackagePops == null){
                goodsPackagePops = new ArrayList<>();
            }
            GoodsPackagePopBean newBean = new GoodsPackagePopBean();
            BeanUtils.copyProperties(bean,newBean);

            GoodsSpec goodsSpec = goodsSpecService.getById(bean.getGoodsSpecId());
            newBean.setSpecName(goodsSpec.getName());
            newBean.setSpecValue(goodsSpec.getSpecValue());
            newBean.setStock(goodsSpec.getStockNum());

            goodsPackagePops.add(newBean);
            map.put(bean.getGoodsId(),goodsPackagePops);
        }
        //商品
        List<GoodsPackageBean> goodsList = new ArrayList<>();
        for(String gdsId : map.keySet()){

            Goods nGoods = goodsService.getById(gdsId);

            GoodsPackagePopBean goodsPackagePop = map.get(gdsId).get(0);
            GoodsPackageBean bean = new GoodsPackageBean();
            bean.setImgUrl(nGoods.getImgUrl());
            bean.setGoodsName(nGoods.getGoodsName());
            bean.setGoodsPackagePopList(map.get(gdsId));
            bean.setSortNum(goodsPackagePop.getSortNum());
            goodsList.add(bean);
        }
      return goodsList;
    }



    /**
     * 添加商品
     *
     * @param goodsBean
     */
    @Transactional(rollbackFor = Exception.class)
    public void add(GoodsBean goodsBean, HttpServletRequest request) throws RemoteServiceException {
        if (StringUtils.equals(goodsBean.getGoodsType(), GoodsTypeEnum.COMMON.toString())
                && (goodsBean.getGoodsSpecs() == null || goodsBean.getGoodsSpecs().size() == 0)) {
            //如果是规格没有抛出异常
            throw new RemoteServiceException("至少要有一个规格!");
        }
        if (StringUtils.isNotBlank(goodsBean.getUmsDiscountCode()) && !UMSDiscountCodeEnum.existDiscountCodeByCode(goodsBean.getUmsDiscountCode())) {
            throw new RemoteServiceException("补贴品类不存在");
        }
        goodsBean.setGoodsId(IdWorker.getIdStr());
        Date creatDate = new Date();
        List<GoodsSpec> goodsSpecList = goodsBean.getGoodsSpecs();
        if (CollectionUtils.isNotEmpty(goodsSpecList)) {
            Collections.sort(goodsSpecList, (o1, o2) -> o1.getPrice().compareTo(o2.getPrice()));
            goodsBean.setGoodsPrice(goodsSpecList.get(0).getPrice());
        }
        goodsBean.setUpdateTime(new Date());
        goodsBean.setCreateTime(creatDate);

        List<GoodsCompany> goodsCompanies = new ArrayList<>();

        if (!StringUtil.isEmpty(goodsBean.getPutCompanyId())) {
            goodsBean.setPutCompanyId(goodsBean.getPutCompanyId());
            String[] split = StringUtils.split(goodsBean.getPutCompanyId(), ",");

            String name ="";
            for (String s : split) {
                AdminCompany adminCompany = adminCompanyService.getById(s);
                name = name+adminCompany.getAdminCompanyId()+",";

                GoodsCompany goodsCompany = new GoodsCompany();
                goodsCompany.setGoodsId(goodsBean.getGoodsId());
                goodsCompany.setConpanyName(adminCompany.getAdminCompanyId());
                goodsCompany.setCompanyId(adminCompany.getAdminCompanyId());

                goodsCompanies.add(goodsCompany);
            }
            String result = name.substring(0, name.length() - 1);
            goodsBean.setPutCompanyName(result);

            goodsCompanyService.saveBatch(goodsCompanies);
        }

        GoodsCategory goodsCategory = goodsCategoryService.getById(goodsBean.getCategoryId());
        GoodsCategory goodsCategoryPid = goodsCategoryService.getById(goodsCategory.getParentId());
        goodsBean.setCategoryName(goodsCategory.getName());
        goodsBean.setCategoryPname(goodsCategoryPid.getName());
        goodsBean.setCategoryPid(goodsCategoryPid.getCategoryId());
        goodsService.save(goodsBean);



        if (CollectionUtils.isNotEmpty(goodsBean.getGoodsSpecs())) {
            goodsSpecList = goodsBean.getGoodsSpecs()
                    .stream()
                    .map(goodsSpec -> goodsSpec.setGoodsId(goodsBean.getGoodsId())
                            .setCreateTime(creatDate)
                            .setDel(false)
                            .setShareAmount(limitShareAmount(goodsSpec.getPrice(), goodsSpec.getShareAmount())) //限制金额40%
                            .setShareAmount(limitShareAmount(goodsSpec.getPrice(), goodsSpec.getSharePercent() != null  //分销比列不为0覆盖分销金额
                                    && goodsSpec.getSharePercent().compareTo(new Double("0.00")) > 0 ?
                                    goodsSpec.getPrice().multiply(new BigDecimal(goodsSpec.getSharePercent() / 100.0))
                                            .setScale(2, BigDecimal.ROUND_DOWN)
                                    : goodsSpec.getShareAmount()))
                            .setInnerShareAmount(getInnerShareAmount(goodsSpec))//需最后设置
                    )
                    .collect(Collectors.toList());
        }

        if (StringUtils.isNotEmpty(goodsBean.getTemplateId())) {
            goodsTemplateService.lambdaUpdate()
                    .eq(GoodsTemplate::getGoodsId,goodsBean.getGoodsId()).remove();
            GoodsTemplate goodsTemplate = new GoodsTemplate();
            goodsTemplate.setGoodsId(goodsBean.getGoodsId());
            goodsTemplate.setTemplateId(goodsBean.getTemplateId());
            goodsTemplate.setCreateTime(new Date());
            goodsTemplateService.save(goodsTemplate);
        }

        //批量保存商品规格
        if(CollectionUtils.isNotEmpty(goodsSpecList))
            goodsSpecService.saveBatch(goodsSpecList);

        //保存轮播图
        if (goodsBean.getImages() != null && goodsBean.getImages().size() > 0) {
            List<String> imageIdList = goodsBean.getImages().stream().map(CommonFile::getId).collect(Collectors.toList());
            commonLogic.bindFile(goodsBean.getGoodsId(), Constant.Img.GOODS_IMG, imageIdList);
        }
        //save tags
        this.saveGoodsTagRela(goodsBean.getTags(),goodsBean.getGoodsId(),1);
        this.saveGoodsTagRela(goodsBean.getTagsLabel(),goodsBean.getGoodsId(),2);

        //套购商品处理
        this.saveGoodsPackage(goodsBean);
    }

    /**
     * 保存标签
     */
    public void saveGoodsTagRela(List<String> tags,String goodsId,Integer type){

        if(CollectionUtils.isEmpty(tags)){
            goodsTagRelaService.lambdaUpdate().eq(GoodsTagRela::getGoodsId,goodsId).eq(GoodsTagRela::getType,type).remove();
            return;
        }
        //先删后加
        goodsTagRelaService.lambdaUpdate().eq(GoodsTagRela::getGoodsId,goodsId).eq(GoodsTagRela::getType,type).remove();
        for(String tag:tags){
            GoodsTagRela goodsTagRela = new GoodsTagRela();
            goodsTagRela.setGoodsTagName(tag);
            goodsTagRela.setCreateTime(new Date());
            goodsTagRela.setGoodsId(goodsId);
            goodsTagRela.setType(type);
            goodsTagRela.insert();
        }

    }


    /**
     *  限制最大分账
     * @param price
     * @param shareAmount
     * @return
     */
    private BigDecimal limitShareAmount(BigDecimal price, BigDecimal shareAmount) {
        BigDecimal shareLimit = price.multiply(new BigDecimal(percentLimit));
        return shareAmount.compareTo(shareLimit) < 1 ?
                shareAmount.setScale(2, BigDecimal.ROUND_DOWN)
                : shareLimit.setScale(2, BigDecimal.ROUND_DOWN);
    }

    /**
     * 获取内部分销金额
     */
    private BigDecimal getInnerShareAmount(GoodsSpec goodsSpec) {
        BigDecimal innerShareAmount = goodsSpec.getInnerShareAmount();
        Double innerSharePercent = goodsSpec.getInnerSharePercent();
        BigDecimal price = goodsSpec.getPrice();

        //以内部分销比列为准
        if (innerSharePercent != null && innerSharePercent.compareTo(new Double("0.00")) > 0) {
            // price * innerSharePercent/100 = 内部分销金额
            innerShareAmount = price.multiply(new BigDecimal(innerSharePercent / 100.0)).setScale(2, BigDecimal.ROUND_DOWN);

            return limitShareAmount(price, innerShareAmount);
        }
        //没有比列有金额以金额为准
        else if (innerShareAmount != null) {
            goodsSpec.setInnerSharePercent(new Double("0.00"));
            return limitShareAmount(price, innerShareAmount);
        }

        goodsSpec.setInnerSharePercent(goodsSpec.getSharePercent());
        return goodsSpec.getShareAmount();
    }

    /**
     * 编辑商品
     *
     * @param goodsBean
     */
    @Transactional(rollbackFor = Exception.class)
    public void update(GoodsBean goodsBean, HttpServletRequest request) throws RemoteServiceException {

        //检查是否存在秒杀活动
        if (StringUtils.equals(goodsBean.getGoodsType(),GoodsTypeEnum.COMMON.toString())
                && (goodsBean.getGoodsSpecs() == null || goodsBean.getGoodsSpecs().size() == 0)) {
            throw new RemoteServiceException("至少要有一个规格!");
        }

        GoodsCategory goodsCategory = goodsCategoryService.getById(goodsBean.getCategoryId());
        GoodsCategory goodsCategoryPid = goodsCategoryService.getById(goodsCategory.getParentId());
        goodsBean.setCategoryName(goodsCategory.getName());
        goodsBean.setCategoryPname(goodsCategoryPid.getName());
        goodsBean.setCategoryPid(goodsCategoryPid.getCategoryId());

        //设置企业微信id
        AdminUserCom adminUser = commonLogic.getAdminUser(request);
        List<GoodsCompany> goodsCompanies = new ArrayList<>();

        goodsCompanyService.lambdaUpdate().eq(GoodsCompany::getGoodsId,goodsBean.getGoodsId()).remove();
        if (!StringUtil.isEmpty(goodsBean.getPutCompanyId())) {
            goodsBean.setPutCompanyId(goodsBean.getPutCompanyId());
            String[] split = StringUtils.split(goodsBean.getPutCompanyId(), ",");

            String name ="";
            for (String s : split) {
                AdminCompany adminCompany = adminCompanyService.getById(s);
                name = name+adminCompany.getAdminCompanyId()+",";

                GoodsCompany goodsCompany = new GoodsCompany();
                goodsCompany.setGoodsId(goodsBean.getGoodsId());
                goodsCompany.setConpanyName(adminCompany.getAdminCompanyId());
                goodsCompany.setCompanyId(adminCompany.getAdminCompanyId());

                goodsCompanies.add(goodsCompany);
            }
            String result = name.substring(0, name.length() - 1);
            goodsBean.setPutCompanyName(result);

            goodsCompanyService.saveBatch(goodsCompanies);
        }

        List<GoodsSpec> notRemoveList = new ArrayList<>();
        //查找未删除的规格
        if(CollectionUtils.isNotEmpty(goodsBean.getGoodsSpecs())) {
            notRemoveList = goodsBean.getGoodsSpecs().stream()
                    .filter(goodsSpec -> StringUtils.isNotEmpty(goodsSpec.getGoodsSpecId()))
                    .map(goodsSpec -> goodsSpec.setGoodsId(goodsBean.getGoodsId())
                            .setShareAmount(limitShareAmount(goodsSpec.getPrice(), goodsSpec.getShareAmount()))  //限制金额40%
                            .setShareAmount(limitShareAmount(goodsSpec.getPrice(),      //比列>0 覆盖分销金额
                                    goodsSpec.getSharePercent() != null && goodsSpec.getSharePercent().compareTo(new Double("0.00")) > 0 ?
                                            goodsSpec.getPrice().multiply(new BigDecimal(goodsSpec.getSharePercent() / 100.0)).setScale(2, BigDecimal.ROUND_DOWN)
                                            : goodsSpec.getShareAmount()
                            ))
                            .setInnerShareAmount(getInnerShareAmount(goodsSpec))//需最后设置
                    )
                    .collect(Collectors.toList());


            //更新主表信息
            List<GoodsSpec> goodsSpecList = goodsBean.getGoodsSpecs();
            Collections.sort(goodsSpecList, (o1, o2) -> o1.getPrice().compareTo(o2.getPrice()));

            goodsBean.setGoodsPrice(goodsSpecList.get(0).getPrice());
        }
        goodsBean.setUpdateTime(new Date());
        goodsService.updateById(goodsBean);

        if (StringUtils.isNotEmpty(goodsBean.getTemplateId())) {
            goodsTemplateService.lambdaUpdate()
                    .eq(GoodsTemplate::getGoodsId,goodsBean.getGoodsId()).remove();
            GoodsTemplate goodsTemplate = new GoodsTemplate();
            goodsTemplate.setGoodsId(goodsBean.getGoodsId());
            goodsTemplate.setTemplateId(goodsBean.getTemplateId());
            goodsTemplate.setCreateTime(new Date());
            goodsTemplateService.save(goodsTemplate);
        }


        //未删除的规格id
        List<String> goodsSpecIds = notRemoveList.stream().map(GoodsSpec::getGoodsSpecId).collect(Collectors.toList());

        //更新轮播图
        List<String> imageIdList = goodsBean.getImages().stream()
                .map(CommonFile::getId)
                .collect(Collectors.toList());
        commonLogic.bindFile(goodsBean.getGoodsId(), Constant.Img.GOODS_IMG, imageIdList);
        //更改不在未删除规格list里面的规格id为删除状态
        goodsSpecService.lambdaUpdate()
                .eq(GoodsSpec::getGoodsId, goodsBean.getGoodsId())
                .notIn(!CollectionUtils.isEmpty(goodsSpecIds), GoodsSpec::getGoodsSpecId, goodsSpecIds)
                .set(GoodsSpec::getDel, true)
                .update();

        if (notRemoveList.size() > 0) {
            //更改存在的规格内容
            goodsSpecService.updateBatchById(notRemoveList);
        }
        //查找规格id为空的 添加到从表
        if(CollectionUtils.isNotEmpty(goodsBean.getGoodsSpecs())) {
            List<GoodsSpec> addGoodsSpecList = goodsBean.getGoodsSpecs().stream()
                    .filter(goodsSpec -> StringUtils.isEmpty(goodsSpec.getGoodsSpecId()))
                    .map(goodsSpec -> goodsSpec.setGoodsId(goodsBean.getGoodsId())
                            .setShareAmount(limitShareAmount(goodsSpec.getPrice(), goodsSpec.getSharePercent() != null
                                    && goodsSpec.getSharePercent().compareTo(new Double("0.00")) > 0 ?
                                    goodsSpec.getPrice().multiply(new BigDecimal(goodsSpec.getSharePercent() / 100.0)).setScale(2, BigDecimal.ROUND_DOWN)
                                    : goodsSpec.getShareAmount()))
                            .setCreateTime(new Date())
                            .setInnerShareAmount(getInnerShareAmount(goodsSpec))//需最后设置
                    )
                    .collect(Collectors.toList());
            if (addGoodsSpecList.size() > 0) {
                goodsSpecService.saveBatch(addGoodsSpecList);
            }
        }
        //save tags
        this.saveGoodsTagRela(goodsBean.getTags(),goodsBean.getGoodsId(),1);
        this.saveGoodsTagRela(goodsBean.getTagsLabel(),goodsBean.getGoodsId(),2);

        //套购商品处理
        this.saveGoodsPackage(goodsBean);
    }

    /**
     * 添加套购商品
     */
    public void saveGoodsPackage(GoodsBean goodsBean){
        if(!StringUtils.equals(goodsBean.getGoodsType(),GoodsTypeEnum.PACKAGE.toString())){
            return;
        }
        if(StringUtils.isEmpty(goodsBean.getPackagePop()) || goodsBean.getPackagePop().indexOf(":") == -1){
            throw new RemoteServiceException("请填写正确的比例,例如 2:1");
        }
        List<GoodsPackagePop> goodsPackagePops = goodsBean.getGoodsPackagePops();
        if(CollectionUtils.isEmpty(goodsPackagePops)){
            throw new RemoteServiceException("请配置套购的比例商品");
        }
        List<GoodsPackagePop> distinctList = goodsPackagePops.stream().distinct().collect(Collectors.toList());
        if(goodsPackagePops.size() != distinctList.size()){
            throw new RemoteServiceException("禁止配置重复的机型");
        }
        //计算最低销售价格，最低分佣金额
        BigDecimal totalMinPrice = BigDecimal.valueOf(0);
        BigDecimal totalMinShareAmount = BigDecimal.valueOf(0);
        //判断条件的比例和对应的机型是否合格
        String[] split = goodsBean.getPackagePop().split(":");
        for (int i = 1;i <= split.length; i++) {
            int a = i;
            long count = goodsPackagePops.stream().filter(v -> v.getType().intValue() == a).count();
            if(count == 0){
                throw new RemoteServiceException("条件比例与商品配置错误");
            }
            //判断比例格式是否正确
            try {
                int i1 = Integer.parseInt(split[i - 1]);
            }catch(Exception e){
                throw new RemoteServiceException("请填写正确的比例,例如  1:2");
            }
            BigDecimal minPrice = null;
            BigDecimal minShareAmount = null;
            for(GoodsPackagePop goodsPackagePop : goodsPackagePops) {
                if(i != goodsPackagePop.getType()){
                    continue;
                }
                //计算最低销售金额和分佣金额
                BigDecimal minPrice2 = goodsPackagePop.getPrice().multiply(new BigDecimal(split[goodsPackagePop.getType() - 1])).setScale(2, BigDecimal.ROUND_HALF_UP);
                if (minPrice == null || minPrice.doubleValue() > minPrice2.doubleValue()) {
                    minPrice = minPrice2;
                }
                BigDecimal minShareAmount2 = minPrice2.multiply(goodsPackagePop.getShareRate()).setScale(2, BigDecimal.ROUND_HALF_UP);
                if (minShareAmount == null || minShareAmount.doubleValue() > minShareAmount2.doubleValue()) {
                    minShareAmount = minShareAmount2;
                }
            }
            totalMinPrice = totalMinPrice.add(minPrice);
            totalMinShareAmount = totalMinShareAmount.add(minShareAmount);
        }

        //添加配置机型
        goodsPackagePopService.lambdaUpdate().eq(GoodsPackagePop::getGoodsPackageId,goodsBean.getGoodsId()).remove();
        for(GoodsPackagePop goodsPackagePop : goodsPackagePops){
            goodsPackagePop.setGoodsPackageId(goodsBean.getGoodsId());
        }
        goodsPackagePopService.saveBatch(goodsPackagePops);
        //添加指定人员
        if(goodsBean.getPackageUserType() == 0 && CollectionUtils.isEmpty(goodsBean.getGoodsPackageUserRelas())){
            throw new RemoteServiceException("请选择指定用户");
        }
        for(GoodsPackageUserRela rela : goodsBean.getGoodsPackageUserRelas()){
            rela.setGoodsId(goodsBean.getGoodsId());
            rela.setCreateTime(new Date());
        }
        goodsBean.setPackageMinAmount(totalMinPrice);
        goodsBean.setPackageMinShareAmount(totalMinShareAmount);
        goodsBean.updateById();

        goodsPackageUserRelaService.lambdaUpdate().eq(GoodsPackageUserRela::getGoodsId,goodsBean.getGoodsId()).remove();
        goodsPackageUserRelaService.saveBatch(goodsBean.getGoodsPackageUserRelas());
    }

    /**
     * 分类统计
     */
    public GoodsTypeCount countByType(HttpServletRequest request) {
        //获取当前登录微信企业微信id
        AdminUserCom adminUser = commonLogic.getAdminUser(request);
        List<String> companyWechatIds = adminUser.getAdminCompanyIds();

        GoodsTypeCount goodsTypeCount = customGoodsMapper.countByType(companyWechatIds);
        if (goodsTypeCount == null)
            return new GoodsTypeCount();
        //查询已售罄的商品数量
        goodsTypeCount.setYsq(customGoodsMapper.ysq(companyWechatIds));
        goodsTypeCount.setHdz(customGoodsMapper.countByFlag(companyWechatIds));
        return goodsTypeCount;
    }

    /**
     * 商品上下架
     * @param goodsIdList
     * @param action
     */
    public void goodsOnOff(List<String> goodsIdList, Boolean action) {
        goodsService.lambdaUpdate()
                .in(Goods::getGoodsId, goodsIdList)
                .set(Goods::getStatus, action)
                .update();
        if (!action) {
            carouselMapService.lambdaUpdate().in(CarouselMap::getGoodsId, goodsIdList).remove();
        }
    }

    /**
     * 商品模板
     * @param goodsTemplateBean
     * @param request
     */
    public void goodsTemplate(GoodsTemplateBean goodsTemplateBean, HttpServletRequest request) {

        AdminUserCom adminUser = commonLogic.getAdminUser(request);

        if (goodsTemplateBean.getGoodsIdList() == null || goodsTemplateBean.getGoodsIdList().size() < 1) {
            return;
        }
        List<GoodsTemplate> goodsTemplateList = new ArrayList<>();
        for (String goodsId : goodsTemplateBean.getGoodsIdList()) {
            GoodsTemplate goodsTemplate = new GoodsTemplate();
            goodsTemplate.setGoodsId(goodsId);
            goodsTemplate.setTemplateId(goodsTemplateBean.getTemplateId());
            goodsTemplate.setCreateTime(new Date());
            goodsTemplateList.add(goodsTemplate);
        }
        goodsTemplateService.saveBatch(goodsTemplateList);
    }


    public Integer secCheck(String goodsId) {
        Integer count = goodsCheckMapper.checkGoodsSec(goodsId);
        return count;
    }

    public List<String> secCheckBatch(List<String> goodsIdList) {
        List<String> secGoodsIds = goodsCheckMapper.checkGoodsSecBatch(goodsIdList);
        return secGoodsIds;
    }

    @Transactional
    public Goods clone(String goodsId) {
        Goods goods = goodsService.getById(goodsId);
        if (goods != null) {
            goods.setGoodsId(null);
            goods.setCreateTime(new Date());
            goods.setPromotionGroup(false);
            goodsService.save(goods);
        }
        List<GoodsSpec> goodsSpecs = goodsSpecService.lambdaQuery()
                .eq(GoodsSpec::getGoodsId, goodsId)
                .list();
        if (goodsSpecs != null && goodsSpecs.size() > 0) {
            for (GoodsSpec goodsSpec : goodsSpecs) {
                goodsSpec.setGoodsId(goods.getGoodsId());
                goodsSpec.setGoodsSpecId(null);
                goodsSpec.setCreateTime(new Date());
                goodsSpecService.save(goodsSpec);
            }
        }
        List<CommonFile> commonFiles = commonFileService.lambdaQuery()
                .eq(CommonFile::getObjId, goodsId)
                .eq(CommonFile::getObjType, Constant.Img.GOODS_IMG)
                .list();

        if (commonFiles != null && commonFiles.size() > 0) {
            for (CommonFile commonFile : commonFiles) {
                commonFile.setObjId(goods.getGoodsId());
                commonFile.setId(null);
                commonFile.setCreateTime(new Date());
                commonFileService.save(commonFile);
            }
        }
        List<CarouselMap> carouselMaps = carouselMapService.lambdaQuery()
                .eq(CarouselMap::getGoodsId, goodsId)
                .list();
        if (carouselMaps != null && carouselMaps.size() > 0) {
            for (CarouselMap carouselMap : carouselMaps) {
                carouselMap.setGoodsId(goods.getGoodsId());
                carouselMap.setId(null);
                carouselMap.setCreateTime(new Date());
                carouselMapService.save(carouselMap);
            }
        }
        List<GoodsTemplate> goodsTemplateList = goodsTemplateService.lambdaQuery()
                .eq(GoodsTemplate::getGoodsId, goodsId)
                .list();
        if (goodsTemplateList != null && goodsTemplateList.size() > 0) {
            List<GoodsTemplate> saveGoodsTemplateList = new ArrayList<>();
            goodsTemplateList.forEach(o -> {
                o.setGoodsId(goods.getGoodsId()).setCreateTime(new Date()).setGoodsTemplateId(null);
                saveGoodsTemplateList.add(o);
            });
            goodsTemplateService.saveBatch(saveGoodsTemplateList);
        }
        return goods;
    }

    @Transactional
    public void goodsFreight(GoodsFreightBean goodsFreightBean) {
        goodsService.lambdaUpdate()
                .in(Goods::getGoodsId, goodsFreightBean.getGoodsIdList())
                .set(Goods::getFreightTemplateId, goodsFreightBean.getFreightTemplateId())
                .set(Goods::getFreightType, FreightTypeEnum.TEMPLATE.toString())
                .update();
    }

    /**
     * 用 商品规格的 分销金额 覆盖其 为null的 内部分销金额
     */
    public void syncGoodsSpecInnerShareMsg(HttpServletRequest request){

        customGoodsMapper.syncGoodsSpecInnerShareMsg(null);

    }


    /**
     * 修改商品水印和有效时间
     */
    public void updateGoodsLogo(List<String> goodsIds, String logo, String logoStartTime, String logoEndTime, boolean isChange) throws ParseException {
        goodsService.lambdaUpdate()
                .set(Goods::getLogo, logo)
                .set(Goods::getLogoStartTime, StringUtils.isNotBlank(logoStartTime) ? DateUtils.parseDate(logoStartTime) : logoStartTime)
                .set(Goods::getLogoEndTime, StringUtils.isNotBlank(logoEndTime) ? DateUtils.parseDate(logoEndTime) : logoEndTime)
                .set(isChange, Goods::getMergeImage, null)
                .in(Goods::getGoodsId, goodsIds)
                .update();

    }

    /**
     *  套购商品指定人员列表
     */
    public List<User> getPackageUseUserList(String goodsId,String mobile){
        List<GoodsPackageUserRela> list = goodsPackageUserRelaService.lambdaQuery()
                .eq(GoodsPackageUserRela::getGoodsId, goodsId)
                .like(StringUtils.isNotEmpty(mobile), GoodsPackageUserRela::getMobile, mobile).list();
        if(CollectionUtils.isEmpty(list)){
            return new ArrayList<>();
        }
        List<String> userIds = list.stream().map(GoodsPackageUserRela::getUserId).collect(Collectors.toList());
        List<User> users = userLogic.getById(userIds);
        return users;
    }

    /**
     * 套购商品-导入指定人员
     */
    public List<User> importPackageUser(List<Object> list){
        if(CollectionUtils.isEmpty(list)){
            return new ArrayList<>();
        }
        List<String> mobiles = new ArrayList<>();
        for(Object o : list){
            List<Object> row = (List<Object>) o;
            mobiles.add((String)row.get(1));
        }
        List<User> users = userLogic.getByMobile(mobiles);
        return users;
    }

    public List<Goods> getById(List<String> goodsIds){
        List<Goods> goodsList = goodsService.lambdaQuery().in(Goods::getGoodsId, goodsIds).list();
        return goodsList;
    }

    public List<GoodsSpec> getSpec(List<String> goodsIds){
        List<GoodsSpec> goodsSpecs = goodsSpecService.lambdaQuery().in(GoodsSpec::getGoodsId, goodsIds).list();
        return goodsSpecs;
    }


    /**
     * 外部商品列表
     * @param time
     * @return
     */
    public List<GoodsBean> outsideList(Date time){

        List<GoodsCategory> goodsCategoryList = goodsCategoryService.lambdaQuery().list();
        Map<String, GoodsCategory> map = goodsCategoryList.stream().collect(Collectors.toMap(GoodsCategory::getCategoryId, Function.identity()));

        List<Goods> list = goodsService.lambdaQuery().ge(time != null, Goods::getUpdateTime, time).list();
        List<GoodsBean> goodsBeans = BeanUtil.copyToList(list, GoodsBean.class);
        for(GoodsBean goodsBean : goodsBeans){
            List<GoodsSpec> list1 = goodsSpecService.lambdaQuery().eq(GoodsSpec::getGoodsId, goodsBean.getGoodsId()).list();
            goodsBean.setGoodsSpecs(list1);

            GoodsCategory goodsCategory = map.get(goodsBean.getCategoryId());
            if(goodsCategory != null){
                goodsBean.setCategory2(goodsCategory.getName());
                goodsBean.setIsVr(goodsBean.getGoodsName().indexOf("清洗") > -1);
            }
            GoodsCategory parentCategory = map.get(goodsCategory.getParentId());
            if(parentCategory != null){
                goodsBean.setCategory1(parentCategory.getName());
            }

            goodsBean.setImages(commonLogic.queryFileByObjId(goodsBean.getGoodsId(), Constant.Img.GOODS_IMG));

        }

        return goodsBeans;
    }

    public void categoryAndGoods(String sourceCompanyId, String targetCompanyId, String targetCompanyName) {
        final Integer count = goodsCategoryService.lambdaQuery()
                .count();
        if (count > 0) {
            throw new RemoteServiceException("数据已存在");
        }
        List<GoodsCategory> parentCategoryList = goodsCategoryService.lambdaQuery()
                .eq(GoodsCategory::getLevel, 1)
                .eq(GoodsCategory::getStatus, true)
                .list();

        // 遍历源父类
        for (GoodsCategory parentCategory : parentCategoryList) {
            GoodsCategory copyParentCategory = new GoodsCategory();
            // 插入目前父类
            BeanUtils.copyProperties(parentCategory, copyParentCategory);
            copyParentCategory.setCategoryId(IdWorker.getIdStr())
                    .setCreateTime(DateUtil.date())
                    .insert();

            // 查询源小类
            List<GoodsCategory> categoryList = goodsCategoryService.lambdaQuery()
                    .eq(GoodsCategory::getParentId, parentCategory.getCategoryId())
                    .eq(GoodsCategory::getLevel, 2)
                    .eq(GoodsCategory::getStatus, true)
                    .list();

            // 遍历源小类
            for (GoodsCategory goodsCategory : categoryList) {
                GoodsCategory copyCategory = new GoodsCategory();
                // 插入目前小类
                BeanUtils.copyProperties(goodsCategory, copyCategory);
                copyCategory.setCategoryId(IdWorker.getIdStr())
                        .setParentId(copyParentCategory.getCategoryId())
                        .setCreateTime(DateUtil.date())
                        .insert();

                // 查询源小类关联商品
                final List<Goods> goodsList = goodsService.lambdaQuery()
                        .eq(Goods::getCategoryId, goodsCategory.getCategoryId())
                        .eq(Goods::getStatus, true)
                        .list();

                // 遍历源商品
                for (Goods goods : goodsList) {
                    Goods copyGoods = new Goods();
                    // 插入目前商品
                    BeanUtils.copyProperties(goods, copyGoods);
                    copyGoods.setGoodsId(IdWorker.getIdStr())
                            .setCategoryId(copyCategory.getCategoryId())
                            .setSoldNum(0)
                            .setUmsDiscountCode("")
                            .setCreateTime(DateUtil.date())
                            .insert();

                    // 查询源商品关联规格
                    final List<GoodsSpec> goodsSpecList = goodsSpecService.lambdaQuery()
                            .eq(GoodsSpec::getGoodsId, goods.getGoodsId())
                            .list();

                    // 遍历源规格
                    for (GoodsSpec goodsSpec : goodsSpecList) {
                        GoodsSpec copyGoodsSpec = new GoodsSpec();
                        // 插入目前规格
                        BeanUtils.copyProperties(goodsSpec, copyGoodsSpec);
                        copyGoodsSpec.setGoodsSpecId(IdWorker.getIdStr())
                                .setGoodsId(copyGoods.getGoodsId())
                                .setShareAmount(BigDecimal.ZERO)
                                .setSharePercent((double) 0)
                                .setInnerShareAmount(BigDecimal.ZERO)
                                .setInnerSharePercent((double) 0)
                                .setStockNum(0)
                                .setCreateTime(DateUtil.date())
                                .insert();

                    }

                    // 查询源商品关联说明模板
//                    final List<GoodsTemplate> goodsTemplateList = goodsTemplateService.lambdaQuery()
//                            .eq(GoodsTemplate::getGoodsId, goods.getGoodsId())
//                            .eq(GoodsTemplate::getCompanyId, sourceCompanyId)
//                            .list();
//
//                    // 遍历源关联说明模板
//                    for (GoodsTemplate goodsTemplate : goodsTemplateList) {
//                        GoodsTemplate copyGoodsTemplate = new GoodsTemplate();
//                        // 插入目前规格
//                        BeanUtils.copyProperties(goodsTemplate, copyGoodsTemplate);
//                        copyGoodsTemplate.setGoodsTemplateId(IdWorker.getIdStr())
//                                .setGoodsId(copyGoods.getGoodsId())
//                                .setCompanyId(targetCompanyId)
//                                .setCompanyName(targetCompanyName)
//                                .setCreateTime(DateUtil.date())
//                                .insert();
//                    }

                    // 查询源商品关联图片
                    final List<CommonFile> commonFileList = commonFileService.lambdaQuery()
                            .eq(CommonFile::getObjId, goods.getGoodsId())
                            .eq(CommonFile::getObjType, "goods_img_cm")
                            .orderByAsc(CommonFile::getCreateTime)
                            .list();

                    // 遍历源规格
                    for (CommonFile commonFile : commonFileList) {
                        CommonFile copyCommonFile = new CommonFile();
                        // 插入目前规格
                        BeanUtils.copyProperties(commonFile, copyCommonFile);
                        copyCommonFile.setId(IdWorker.getIdStr())
                                .setObjId(copyGoods.getGoodsId())
                                .setCreateTime(DateUtil.date())
                                .insert();

                    }
                }
            }
        }
    }

    public void copyFreightTemplate(String sourceCompanyId, String targetCompanyId, String targetCompanyName) {
        final Integer count = freightTemplateService.lambdaQuery()
                .eq(FreightTemplate::getCompanyId, targetCompanyId)
                .count();
        if (count > 0) {
            throw new RemoteServiceException("数据已存在");
        }
        List<FreightTemplate> freightTemplateList = freightTemplateService.lambdaQuery()
                .eq(FreightTemplate::getCompanyId, sourceCompanyId)
                .list();

        // 遍历源模板
        for (FreightTemplate freightTemplate : freightTemplateList) {
            FreightTemplate copyFreightTemplate = new FreightTemplate();
            // 插入目前模板
            BeanUtils.copyProperties(freightTemplate, copyFreightTemplate);
            copyFreightTemplate.setFreightTemplateId(IdWorker.getIdStr())
                    .setCompanyId(targetCompanyId)
                    .setCompanyName(targetCompanyName)
                    .setCreateTime(DateUtil.date())
                    .insert();

            // 查询源模板关联
            List<FreightTemplateDetail> freightTemplateDetailList = freightTemplateDetailService.lambdaQuery()
                    .eq(FreightTemplateDetail::getCompanyId, sourceCompanyId)
                    .eq(FreightTemplateDetail::getFreightTemplateId, freightTemplate.getFreightTemplateId())
                    .list();

            goodsService.lambdaUpdate()
                    .set(Goods::getFreightTemplateId, copyFreightTemplate.getFreightTemplateId())
                    .eq(Goods::getFreightTemplateId, freightTemplate.getFreightTemplateId())
                    .update();

            // 遍历源模板关联
            for (FreightTemplateDetail detail : freightTemplateDetailList) {
                FreightTemplateDetail copyDetail = new FreightTemplateDetail();
                // 插入目前模板关联
                BeanUtils.copyProperties(detail, copyDetail);
                copyDetail.setFreightTemplateDetailId(IdWorker.getIdStr())
                        .setCompanyId(targetCompanyId)
                        .setCompanyName(targetCompanyName)
                        .setFreightTemplateId(copyFreightTemplate.getFreightTemplateId())
                        .setCreateTime(DateUtil.date())
                        .insert();
            }
        }
    }

    public void export(HttpServletRequest request, HttpServletResponse response, String flag, String keyword,
                       BigDecimal startPrice, BigDecimal endPrice, BigDecimal startShare, BigDecimal endShare,
                       String sortJson, String categoryId, Boolean status, List<String> goodsTypes) throws Exception {

        ExcelData excelData = new ExcelData();
        String[] titles = {"商品名称", "状态", "销售价格", "分销金额", "佣金比例", "内部分销金额", "内部佣金比例", "库存",
                "政府以旧换新补贴品类", "条形码"};

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String fileName = String.format("商品信息导出%s.xlsx", simpleDateFormat.format(new Date()));

        final IPage<GoodsSpecBean> beanIPage = this.page(flag, keyword, startPrice, endPrice,
                startShare, endShare, sortJson, categoryId, status, goodsTypes, 1, -1, request);

        List<List<Object>> rows = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(beanIPage.getRecords())) {
            for (GoodsSpecBean goodsSpecBean : beanIPage.getRecords()) {
                List<Object> row = new ArrayList<>();
                rows.add(row);

                String goodsName = goodsSpecBean.getGoodsName();

                row.add(goodsName);
                row.add(goodsSpecBean.getStatus() ? "上架" : "下架");
                row.add(goodsSpecBean.getGoodsPrice());
                row.add(goodsSpecBean.getShareAmount());
                row.add(goodsSpecBean.getSharePercent());
                row.add(goodsSpecBean.getInnerShareAmount());
                row.add(goodsSpecBean.getInnerSharePercent());
                row.add(goodsSpecBean.getStockNum());
                row.add(UMSDiscountCodeEnum.findNameByCode(goodsSpecBean.getUmsDiscountCode()));
                row.add(goodsSpecBean.getBarCode());
            }
        }

        excelData.setTitles(Arrays.asList(titles));
        excelData.setName("商品信息");
        excelData.setRows(rows);
        ExcelUtils.exportExcel(request, response, fileName, excelData, -1, null);
    }

    public IPage<GoodsVO> goodsList(Page page, ZfireParamBean zfireParam) {
        //获取当前登录企业id
        AdminUserCom adminUser = commonLogic.getAdminUser();

        //1.组装查询条件
        FieldUtils.supplyParam(zfireParam, GoodsVO.class,adminUser);

        IPage<GoodsVO> goodsVOIPage = customGoodsMapper.goodsList(page, zfireParam);
        return goodsVOIPage;
    }
}
