package com.slodon.b2b2c.model.goods;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.slodon.b2b2c.core.constant.*;
import com.slodon.b2b2c.core.uid.GoodsIdGenerator;
import com.slodon.b2b2c.core.util.AssertUtil;
import com.slodon.b2b2c.core.util.StringUtil;
import com.slodon.b2b2c.dao.read.goods.GoodsPlatformBindReserveNameReadMapper;
import com.slodon.b2b2c.dao.read.goods.GoodsPlatformPictureReadMapper;
import com.slodon.b2b2c.dao.read.goods.GoodsSpecReadMapper;
import com.slodon.b2b2c.dao.read.goods.GoodsSpecValueReadMapper;
import com.slodon.b2b2c.dao.read.seller.StoreGradeReadMapper;
import com.slodon.b2b2c.dao.read.seller.StoreInnerLabelReadMapper;
import com.slodon.b2b2c.dao.read.seller.StoreReadMapper;
import com.slodon.b2b2c.dao.write.goods.GoodsBindReserveNameWriteMapper;
import com.slodon.b2b2c.dao.write.goods.GoodsSpecValueWriteMapper;
import com.slodon.b2b2c.dao.write.goods.GoodsSpecWriteMapper;
import com.slodon.b2b2c.dao.write.seller.StoreLabelBindGoodsWriteMapper;
import com.slodon.b2b2c.dao.write.seller.StoreWriteMapper;
import com.slodon.b2b2c.enums.SeoTypeConstant;
import com.slodon.b2b2c.enums.WebSiteConstant;
import com.slodon.b2b2c.goods.dto.GoodsPlatformImportDTO;
import com.slodon.b2b2c.goods.dto.GoodsPublishFrontParamDTO;
import com.slodon.b2b2c.goods.dto.GoodsPublishInsertDTO;
import com.slodon.b2b2c.goods.example.*;
import com.slodon.b2b2c.goods.pojo.*;
import com.slodon.b2b2c.member.example.GoodsAnnexExample;
import com.slodon.b2b2c.model.seller.StoreModel;
import com.slodon.b2b2c.model.seller.StoreNameModel;
import com.slodon.b2b2c.model.seller.VendorModel;
import com.slodon.b2b2c.seller.example.StoreLabelBindGoodsExample;
import com.slodon.b2b2c.seller.example.StoreNameExample;
import com.slodon.b2b2c.seller.example.VendorExample;
import com.slodon.b2b2c.seller.pojo.*;
import com.slodon.b2b2c.system.pojo.SysSeo;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @program: slodonc
 * 商户管理商品操作
 */
@Component
@Slf4j
public class GoodsSellerModel {

    @Resource
    private GoodsModel goodsModel;
    @Resource
    private GoodsExtendModel goodsExtendModel;
    @Resource
    private GoodsPictureModel goodsPictureModel;
    @Resource
    private ProductModel productModel;
    @Resource
    private GoodsBindLabelModel goodsBindLabelModel;
    @Resource
    private GoodsBindAttributeValueModel goodsBindAttributeValueModel;
    @Resource
    private GoodsCategoryModel goodsCategoryModel;
    @Resource
    private GoodsBrandModel goodsBrandModel;
    @Resource
    private GoodsBindReserveNameWriteMapper goodsBindReserveNameWriteMapper;
    @Resource
    private StoreReadMapper storeReadMapper;
    @Resource
    private StoreGradeReadMapper storeGradeReadMapper;
    @Resource
    private StoreInnerLabelReadMapper storeInnerLabelReadMapper;
    @Resource
    private StoreWriteMapper storeWriteMapper;
    @Resource
    private StoreLabelBindGoodsWriteMapper storeLabelBindGoodsWriteMapper;
    @Resource
    private GoodsPlatformPictureReadMapper goodsPlatformPictureReadMapper;
    @Resource
    private GoodsPlatformBindReserveNameReadMapper goodsPlatformBindReserveNameReadMapper;
    @Resource
    private GoodsSpecReadMapper goodsSpecReadMapper;
    @Resource
    private GoodsSpecWriteMapper goodsSpecWriteMapper;
    @Resource
    private GoodsSpecValueReadMapper goodsSpecValueReadMapper;
    @Resource
    private GoodsSpecValueWriteMapper goodsSpecValueWriteMapper;
    @Resource
    private RedisTemplate<String, Object> objectRedisTemplate;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private RabbitTemplate rabbitTemplate;

    @Resource
    private StoreModel storeModel;
    @Resource
    private GoodsAnnexModel goodsAnnexModel;

    @Resource
    private StoreNameModel storeNameModel;

    @Resource
    private VendorModel vendorModel;

    //region 发布商品

    /**
     * 商家发布商品
     * -校验sku是否重复
     * -保存商品信息
     * -保存商品扩展信息
     * -保存货品信息
     * -保存商品属性绑定表（检索属性）
     * -保存商品标签绑定表
     * -保存商品图片表
     * -保存商品绑定店铺内部分类表
     * -增加店铺商品数量(商品状态为上架时操作)
     *
     * @param vendor    店铺管理员
     * @param insertDTO 商品信息
     */
    @Transactional(rollbackFor = Exception.class)
    public Goods saveGoods(Vendor vendor, GoodsPublishInsertDTO insertDTO) {
        List<GoodsPublishFrontParamDTO.ProductInfo> productList = insertDTO.getProductList();//货品列表
        //-校验sku是否重复
        this.checkSku(productList,insertDTO.getWebSite());

        //-保存商品信息
        Goods goods = this.insertGoods(vendor, insertDTO);

        //-保存商品扩展信息
        this.insertGoodsExtend(insertDTO, goods, vendor);

        //-保存货品信息
        this.insertProduct(productList, goods);

        //-保存商品属性绑定表（检索属性）
        this.insertGoodsBindAttribute(insertDTO.getAttributeAndParameter(), goods.getGoodsId());

        //-保存商品标签绑定表
        this.insertGoodsBindLabels(insertDTO.getGoodsLabelList(), goods.getGoodsId());

        //-保存商品图片表
        this.insertGoodsPicture(insertDTO.getSpecInfoList(), insertDTO.getImageList(), goods, vendor);

        //-保存新的商品附件表（goods_annex） insertDTO.getGoodsAnnexList()拿到前台的获取到的附件名称/附件路径的list
        this.insertGoodsAnnex(insertDTO.getGoodsAnnexList(),goods,vendor);

        //-保存商品绑定店铺内部分类表
        this.insertGoodsBindStoreInnerLabels(insertDTO.getStoreInnerLabelList(), goods.getGoodsId(), vendor);

        //-保存虚拟商品用户预留信息名称表
        this.insertGoodsBindReserveName(insertDTO.getReserveInfoList(), goods.getGoodsId(), insertDTO.getIsVirtualGoods());

        //-增加店铺商品数量(商品状态为上架时操作)
        this.addStoreGoodsNum(vendor.getStoreId(), goods.getState());

        return goods;
    }

    /**
     * 校验sku是否重复
     *
     * @param productList
     */
    private void checkSku(List<GoodsPublishFrontParamDTO.ProductInfo> productList,String webSite) {
        Set<String> set = new HashSet<>();//用于校验自身sku是否重复
        productList.forEach(productInfo -> {
            if (!StringUtils.isEmpty(productInfo.getProductCode())) {
                AssertUtil.isTrue(!set.add(productInfo.getProductCode()), "商品货号重复");
                ProductExample example = new ProductExample();
                example.setProductCode(productInfo.getProductCode());
                example.setProductIdNotEquals(((GoodsPublishInsertDTO.ProductInsertInfo) productInfo).getProductId());
                example.setWebSite(webSite);
                int count = productModel.countByExample(example);
                AssertUtil.isTrue(count > 0, "商品货号[" + productInfo.getProductCode() + "]已存在，请重新输入");
            }
        });
    }

    /**
     * 发布商品-插入商品
     *
     * @param vendor    店铺管理员
     * @param insertDTO 商品信息
     * @return
     */
    private Goods insertGoods(Vendor vendor, GoodsPublishInsertDTO insertDTO) {
        long goodsId = GoodsIdGenerator.goodsIdGenerator();//商品id
        long defaultProductId = GoodsIdGenerator.productIdGenerator();//生成一个默认货品id
        GoodsPublishInsertDTO.ProductInsertInfo defaultProduct = insertDTO.getDefaultProduct();//默认货品

        //查询分类信息
        GoodsCategory goodsCategory3 = goodsCategoryModel.getGoodsCategoryByCategoryId(insertDTO.getCategoryId3());
        AssertUtil.notNull(goodsCategory3, "分类有误");
        GoodsCategory goodsCategory2 = goodsCategoryModel.getGoodsCategoryByCategoryId(goodsCategory3.getPid());
        GoodsCategory goodsCategory1 = goodsCategoryModel.getGoodsCategoryByCategoryId(goodsCategory2.getPid());

        Goods goods = new Goods();
        goods.setWebSite(insertDTO.getWebSite());
        goods.setGoodsId(goodsId);
        goods.setGoodsName(insertDTO.getGoodsName());
        goods.setGoodsNameCn(insertDTO.getGoodsNameCn());
        goods.setGoodsBrief(insertDTO.getGoodsBrief());
        if (!StringUtil.isNullOrZero(insertDTO.getBrandId())) {
            //查询品牌信息
            GoodsBrand goodsBrand = goodsBrandModel.getGoodsBrandByBrandId(insertDTO.getBrandId());
            AssertUtil.notNull(goodsBrand, "品牌有误");
            goods.setBrandId(insertDTO.getBrandId());
            goods.setBrandName(goodsBrand.getBrandName());
        }
        Store storeDb = storeReadMapper.getByPrimaryKey(vendor.getStoreId());
        if (storeDb.getIsOwnStore().equals(StoreConst.NO_OWN_STORE)) {
            //判断发布的商品是否还能被推荐
            if (insertDTO.getStoreIsRecommend() == 1) {
                //查询该店铺已推荐的商品数
                GoodsExample goodsRecommendExample = new GoodsExample();
                goodsRecommendExample.setStoreId(vendor.getStoreId());
                goodsRecommendExample.setStateNotEquals(GoodsConst.GOODS_STATE_DELETE);
                goodsRecommendExample.setStoreIsRecommend(GoodsConst.IS_RECOMMEND_YES);
                goodsRecommendExample.setWebSite(insertDTO.getWebSite());
                List<Goods> goodsRecommends = goodsModel.getGoodsList(goodsRecommendExample, null);
                //获取该店铺推荐限制数
                StoreGrade storeGradeDb = storeGradeReadMapper.getByPrimaryKey(storeDb.getStoreGradeId());
                AssertUtil.isTrue(goodsRecommends.size() >= storeGradeDb.getRecommendLimit(), "店铺已达到推荐数限制，不能设为推荐");
            }
        }
        goods.setCategoryId1(goodsCategory1.getCategoryId());
        goods.setCategoryId2(goodsCategory2.getCategoryId());
        goods.setCategoryId3(goodsCategory3.getCategoryId());
        goods.setCategoryPath(goodsCategory1.getCategoryName() + "->" + goodsCategory2.getCategoryName() + "->" + goodsCategory3.getCategoryName());
        goods.setMarketPrice(defaultProduct.getMarketPrice());
        goods.setGoodsPrice(defaultProduct.getProductPrice());
        goods.setGoodsStock(defaultProduct.getProductStock());
        goods.setVirtualSales(insertDTO.getVirtualSales());
        goods.setIsSpec(CollectionUtils.isEmpty(insertDTO.getSpecInfoList()) ? GoodsConst.IS_SPEC_NO : GoodsConst.IS_SPEC_YES);
        goods.setMainSpecId(insertDTO.getMainSpecId());
        goods.setIsSelf(vendor.getStore().getIsOwnStore());
        goods.setState(this.dealGoodsState(insertDTO.getSellNow()));
        goods.setOnlineTime(goods.getState().equals(GoodsConst.GOODS_STATE_UPPER) ? new Date() : null);
        goods.setStoreId(vendor.getStoreId());
        goods.setStoreName(vendor.getStore().getStoreName());
        if (WebSiteConstant.MEMBER_DISTRIBUTOR.equals(insertDTO.getWebSite())) {
            StoreNameExample storeNameExample = new StoreNameExample();
            storeNameExample.setStoreId(vendor.getStoreId());
            storeNameExample.setWebSite(insertDTO.getWebSite());
            StoreName storeName = storeNameModel.getStoreNameByExample(storeNameExample);
            goods.setStoreName(storeName != null ? storeName.getStoreName() : "");
        }
        goods.setStoreIsRecommend(insertDTO.getStoreIsRecommend());
        goods.setMainImage(defaultProduct.getMainImage());
        goods.setGoodsVideo(insertDTO.getGoodsVideo());
        goods.setBarCode(defaultProduct.getBarCode());
        goods.setServiceLabelIds(insertDTO.getGoodsLabelIds());
        goods.setDefaultProductId(defaultProductId);
        goods.setIsVatInvoice(insertDTO.getIsVatInvoice());
        goods.setIsVirtualGoods(insertDTO.getIsVirtualGoods());
        goods.setAfterSaleService(insertDTO.getAfterSaleService());
        goods.setCreateTime(new Date());
        goods.setUpdateTime(new Date());
        goods.setGoodsMoney(StringUtil.isEmpty(insertDTO.getGoodsMoney())?"面议":insertDTO.getGoodsMoney());
        goods.setGoodsSummary(insertDTO.getGoodsSummary());
        goods.setGoodsMinOrder(insertDTO.getGoodsMinOrder());
        goodsModel.saveGoods(goods);

        //以下为新增SEO表
        SysSeo sysSeo = new SysSeo();
        sysSeo.setWebSite(insertDTO.getWebSite());
        sysSeo.setTenant(0L);
        sysSeo.setType(SeoTypeConstant.SEO_TYPE_GOODS);
        sysSeo.setName("商品SEO");
//        sysSeo.setCode(SeoTypeConstant.SEO_TYPE_GOODS+"_"+insertDTO.getGoodsId());
        sysSeo.setTargetId(goodsId);
        sysSeo.setTitle(insertDTO.getSeoTitle());
        sysSeo.setRemark(insertDTO.getSeoDesc());
        sysSeo.setKeywords(insertDTO.getSeoKeyWords());

        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = simpleDateFormat.format(date);

        sysSeo.setCode(SeoTypeConstant.SEO_TYPE_GOODS+"_"+goodsId);
        sysSeo.setCreateUid(vendor.getVendorId());
        sysSeo.setCreateTime(time);
        storeModel.saveSeo(sysSeo);


        return goods;
    }

    /**
     * 发布商品-插入商品扩展表
     *
     * @param insertDTO
     * @param goods
     * @param vendor
     */
    private void insertGoodsExtend(GoodsPublishInsertDTO insertDTO, Goods goods, Vendor vendor) {
        GoodsExtend goodsExtend = new GoodsExtend();
        goodsExtend.setExtendId(GoodsIdGenerator.goodsExtendIdGenerator());
        goodsExtend.setGoodsId(goods.getGoodsId());
        goodsExtend.setMainSpecId(goods.getMainSpecId());
        if (!CollectionUtils.isEmpty(insertDTO.getSpecInfoList())) {
            goodsExtend.setSpecJson(JSON.toJSONString(insertDTO.getSpecInfoList()));
        }
        if (insertDTO.getAttributeAndParameter() != null) {
            if (!CollectionUtils.isEmpty(insertDTO.getAttributeAndParameter().getAttributeList())) {
                //检索属性
                goodsExtend.setAttributeJson(JSON.toJSONString(insertDTO.getAttributeAndParameter().getAttributeList()));
            }
            if (insertDTO.getAttributeAndParameter().getParameterGroup() != null) {
                //自定义参数
                goodsExtend.setGoodsParameter(JSON.toJSONString(insertDTO.getAttributeAndParameter().getParameterGroup()));
            }
        }
        goodsExtend.setOnlineTime(goods.getOnlineTime());
        goodsExtend.setCreateVendorId(vendor.getVendorId());
        goodsExtend.setCreateTime(new Date());
        goodsExtend.setProvinceCode(insertDTO.getProvinceCode());
        goodsExtend.setCityCode(insertDTO.getCityCode());
        goodsExtend.setFreightId(insertDTO.getFreightId());
        goodsExtend.setFreightFee(insertDTO.getFreightFee());
        goodsExtend.setRelatedTemplateIdTop(insertDTO.getRelatedTemplateIdTop());
        goodsExtend.setRelatedTemplateIdBottom(insertDTO.getRelatedTemplateIdBottom());
        goodsExtend.setGoodsDetails(insertDTO.getGoodsDetails());
        goodsExtendModel.saveGoodsExtend(goodsExtend);
    }


    /**
     * 发布商品-插入货品信息
     *
     * @param productList 货品列表
     * @param goods       商品信息
     */
    private void insertProduct(List<GoodsPublishFrontParamDTO.ProductInfo> productList, Goods goods) {
        productList.forEach(productInfo -> {
            GoodsPublishInsertDTO.ProductInsertInfo productInsertInfo = (GoodsPublishInsertDTO.ProductInsertInfo) productInfo;
            this.doInsertProduct(goods, productInsertInfo);
        });
    }

    /**
     * 执行插入货品操作
     *
     * @param goods
     * @param productInsertInfo
     */
    private void doInsertProduct(Goods goods, GoodsPublishInsertDTO.ProductInsertInfo productInsertInfo) {
        Product product = new Product();
        if (productInsertInfo.getIsDefault() == GoodsConst.PRODUCT_IS_DEFAULT_YES) {
            //默认货品
            product.setProductId(goods.getDefaultProductId());
        } else {
            //非默认货品，生成货品id
            product.setProductId(GoodsIdGenerator.productIdGenerator());
        }
        product.setGoodsId(goods.getGoodsId());
        product.setWebSite(goods.getWebSite());
        product.setGoodsName(goods.getGoodsName());
        product.setGoodsNameCn(goods.getGoodsNameCn());
        product.setSpecValues(productInsertInfo.getSpecValues());
        product.setSpecValueIds(productInsertInfo.getSpecValueIds());
        product.setBrandId(goods.getBrandId());
        product.setBrandName(goods.getBrandName());
        product.setStoreId(goods.getStoreId());
        product.setStoreName(goods.getStoreName());
        product.setCategoryId1(goods.getCategoryId1());
        product.setCategoryId2(goods.getCategoryId2());
        product.setCategoryId3(goods.getCategoryId3());
        product.setCategoryPath(goods.getCategoryPath());
        product.setProductPrice(productInsertInfo.getProductPrice());
        product.setMarketPrice(productInsertInfo.getMarketPrice());
        product.setProductStock(productInsertInfo.getProductStock());
        product.setProductStockWarning(productInsertInfo.getProductStockWarning());
        product.setProductCode(productInsertInfo.getProductCode());
        product.setBarCode(productInsertInfo.getBarCode());
        product.setWeight(productInsertInfo.getWeight());
        product.setLength(productInsertInfo.getLength());
        product.setWidth(productInsertInfo.getWidth());
        product.setHeight(productInsertInfo.getHeight());
        product.setMainImage(productInsertInfo.getMainImage());
        product.setState(productInsertInfo.getState());
        product.setIsDefault(productInsertInfo.getIsDefault());
        productModel.saveProduct(product);
    }

    /**
     * 发布商品-保存商品属性绑定表（检索属性）
     *
     * @param attributeAndParameter
     * @param goodsId
     */
    private void insertGoodsBindAttribute(GoodsPublishFrontParamDTO.AttributeAndParameter attributeAndParameter, Long goodsId) {
        if (attributeAndParameter == null) {
            return;
        }
        if (CollectionUtils.isEmpty(attributeAndParameter.getAttributeList())) {
            return;
        }
        attributeAndParameter.getAttributeList().forEach(attribute -> {
            GoodsBindAttributeValue goodsBindAttributeValue = new GoodsBindAttributeValue();
            goodsBindAttributeValue.setGoodsId(goodsId);
            goodsBindAttributeValue.setAttributeId(attribute.getAttributeId());
            goodsBindAttributeValue.setAttributeName(attribute.getAttributeName());
            goodsBindAttributeValue.setAttributeValueId(attribute.getAttributeValueId());
            goodsBindAttributeValue.setAttributeValue(attribute.getAttributeValue());
            goodsBindAttributeValueModel.saveGoodsBindAttributeValue(goodsBindAttributeValue);
        });
    }

    /**
     * 发布商品-保存商品标签绑定表
     *
     * @param labelInfoList
     * @param goodsId
     */
    private void insertGoodsBindLabels(List<GoodsPublishFrontParamDTO.GoodsLabelInfo> labelInfoList, Long goodsId) {
        if (CollectionUtils.isEmpty(labelInfoList)) {
            return;
        }
        labelInfoList.forEach(goodsLabelInfo -> {
            GoodsBindLabel goodsBindLabel = new GoodsBindLabel();
            goodsBindLabel.setGoodsId(goodsId);
            goodsBindLabel.setLabelId(goodsLabelInfo.getGoodsLabelId());
            goodsBindLabel.setLabelName(goodsLabelInfo.getGoodsLabelName());
            goodsBindLabel.setCreateTime(new Date());
            goodsBindLabelModel.saveGoodsBindLabel(goodsBindLabel);
        });
    }

    /**
     * 发布商品-保存商品图片
     *
     * @param specInfoList
     * @param imageInfoList
     * @param goods
     */
    private void insertGoodsPicture(List<GoodsPublishFrontParamDTO.SpecInfo> specInfoList, List<GoodsPublishFrontParamDTO.ImageInfo> imageInfoList, Goods goods, Vendor vendor) {
        if (StringUtil.isNullOrZero(goods.getMainSpecId())) {
            //没有主规格
            imageInfoList.forEach(imageInfo -> {
                this.insertPicture(imageInfo, goods.getGoodsId(), vendor, 0);
            });
        } else {
            //有主规格
            specInfoList.forEach(specInfo -> {
                if (specInfo.getIsMainSpec() == GoodsConst.IS_MAIN_SPEC_YES) {
                    specInfo.getSpecValueList().forEach(specValueInfo -> {
                        specValueInfo.getImageList().forEach(imageInfo -> {
                            this.insertPicture(imageInfo, goods.getGoodsId(), vendor, specValueInfo.getSpecValueId());
                        });
                    });
                }
            });
        }
    }

    /**
     * 保存图片
     *
     * @param imageInfo
     * @param goodsId
     * @param vendor
     */
    private void insertPicture(GoodsPublishFrontParamDTO.ImageInfo imageInfo, Long goodsId, Vendor vendor, Integer specValueId) {
        GoodsPicture goodsPicture = new GoodsPicture();
        goodsPicture.setGoodsId(goodsId);
        goodsPicture.setImagePath(imageInfo.getImage());
        goodsPicture.setSort(1);
        goodsPicture.setCreateId(vendor.getVendorId());
        goodsPicture.setCreateTime(new Date());
        goodsPicture.setStoreId(vendor.getStoreId());
        goodsPicture.setIsMain(imageInfo.getIsMain());
        goodsPicture.setSpecValueId(specValueId);
        goodsPictureModel.saveGoodsPicture(goodsPicture);
    }

    /**
     * 发布商品-保存商品绑定店铺内部分类表
     *
     * @param storeInnerLabelList
     * @param goodsId
     * @param vendor
     */
    private void insertGoodsBindStoreInnerLabels(List<GoodsPublishFrontParamDTO.StoreInnerLabelInfo> storeInnerLabelList, Long goodsId, Vendor vendor) {
        if (CollectionUtils.isEmpty(storeInnerLabelList)) {
            return;
        }
        storeInnerLabelList.forEach(storeInnerLabelInfo -> {
            //查询上级分类信息
            StoreInnerLabel storeInnerLabel = storeInnerLabelReadMapper.getByPrimaryKey(storeInnerLabelInfo.getInnerLabelId());
            AssertUtil.notNull(storeInnerLabel, "店铺内部分类不存在");
            StoreLabelBindGoods storeLabelBindGoods = new StoreLabelBindGoods();
            storeLabelBindGoods.setParentInnerLabelId(storeInnerLabel.getParentInnerLabelId());
            storeLabelBindGoods.setInnerLabelId(storeInnerLabelInfo.getInnerLabelId());
            if (storeInnerLabel.getParentInnerLabelId() == 0) {
                storeLabelBindGoods.setInnerLabelPath(storeInnerLabel.getInnerLabelName());
            } else {
                StoreInnerLabel parentStoreInnerLabel = storeInnerLabelReadMapper.getByPrimaryKey(storeInnerLabel.getParentInnerLabelId());
                AssertUtil.notNull(parentStoreInnerLabel, "店铺内部分类不存在");
                storeLabelBindGoods.setInnerLabelPath(parentStoreInnerLabel.getInnerLabelName() + "->" + storeInnerLabel.getInnerLabelName());
            }
            storeLabelBindGoods.setGoodsId(goodsId);
            storeLabelBindGoods.setStoreId(vendor.getStoreId());
            storeLabelBindGoods.setCreateTime(new Date());
            storeLabelBindGoods.setCreateVendorId(vendor.getVendorId());
            storeLabelBindGoods.setCreateVendorName(vendor.getVendorName());
            int count = storeLabelBindGoodsWriteMapper.insert(storeLabelBindGoods);
            AssertUtil.isTrue(count == 0, "添加店铺内商品-标签绑定关系失败，请重试");
        });
    }

    /**
     * 发布商品-保存虚拟商品用户预留信息名称表
     *
     * @param reserveInfoList 用户预留信息名称列表
     * @param goodsId         商品id
     * @param isVirtualGoods  是否是虚拟商品：1-实物商品；2-虚拟商品
     */
    private void insertGoodsBindReserveName(List<GoodsPublishFrontParamDTO.GoodsReserveNameInfo> reserveInfoList, Long goodsId, Integer isVirtualGoods) {
        if (isVirtualGoods == GoodsConst.IS_VIRTUAL_GOODS_1 || CollectionUtils.isEmpty(reserveInfoList)) {
            return;
        }
        reserveInfoList.forEach(reserveNameInfo -> {
            GoodsBindReserveName goodsBindReserveName = new GoodsBindReserveName();
            goodsBindReserveName.setReserveName(reserveNameInfo.getReserveName());
            goodsBindReserveName.setReserveType(reserveNameInfo.getReserveType());
            goodsBindReserveName.setIsRequired(reserveNameInfo.getIsRequired());
            goodsBindReserveName.setGoodsId(goodsId);
            int count = goodsBindReserveNameWriteMapper.insert(goodsBindReserveName);
            AssertUtil.isTrue(count == 0, "添加虚拟商品用户预留信息名称表失败，请重试");
        });
    }

    /**
     * 增加店铺商品数量(商品状态为上架时操作)
     *
     * @param storeId
     * @param goodsState
     */
    private void addStoreGoodsNum(Long storeId, Integer goodsState) {
        if (!goodsState.equals(GoodsConst.GOODS_STATE_UPPER)) {
            //非上架状态，不处理
            return;
        }
        Store storeDb = storeReadMapper.getByPrimaryKey(storeId);
        Store update = new Store();
        update.setStoreId(storeId);
        update.setGoodsNumber(storeDb.getGoodsNumber() + 1);
        storeWriteMapper.updateByPrimaryKeySelective(update);
    }

    /**
     * 处理商品状态
     *
     * @param sellNow 是否立即售卖，true==是，false==放入仓库
     * @return
     */
    private Integer dealGoodsState(Boolean sellNow) {
        //查询系统配置，是否需要审核，true==需要审核
        boolean needAudit = GoodsConst.GOODS_PUBLISH_NEED_AUDIT_YES.equals(stringRedisTemplate.opsForValue().get("goods_publish_need_audit"));
        if (sellNow) {
            //立即售卖
            return needAudit ? GoodsConst.GOODS_STATE_SELL_NOW_TO_AUDIT : GoodsConst.GOODS_STATE_UPPER;
        } else {
            //放入仓库
            return needAudit ? GoodsConst.GOODS_STATE_LOWER_BY_STORE : GoodsConst.GOODS_STATE_WAREHOUSE_NO_AUDIT;
        }
    }
    //endregion

    //region 编辑商品

    /**
     * 编辑商品
     * -对比货品列表信息，构造要增、删、改的货品列表
     * -校验sku是否重复
     * -更新商品信息
     * -更新商品扩展信息
     * -更新货品信息
     * -保存新的商品属性绑定表（检索属性）
     * -保存新的商品标签绑定表
     * -保存新的商品图片表
     * -保存商品绑定店铺内部分类表
     * -增加/减少店铺商品数量(商品状态为上架时操作)
     *
     * @param vendor
     * @param insertDTO
     * @param goodsDb
     */
    @Transactional(rollbackFor = Exception.class)
    public Goods editGoods(Vendor vendor, GoodsPublishInsertDTO insertDTO, Goods goodsDb) {
        List<GoodsPublishFrontParamDTO.ProductInfo> productList = insertDTO.getProductList();//前端传来的货品列表
        List<GoodsPublishInsertDTO.ProductInsertInfo> addProductList = new ArrayList<>();//要新增的货品
        List<GoodsPublishInsertDTO.ProductInsertInfo> updateProductList = new ArrayList<>();//要删除的货品
        List<Product> deleteProductList = new ArrayList<>();//要删除的货品（伪删除）

        //-对比货品列表信息，构造要增、删、改的货品列表
        this.compareSpecWithDb(goodsDb.getGoodsId(), productList, addProductList, updateProductList, deleteProductList);

        //-校验sku是否重复
        this.checkSku(productList, goodsDb.getWebSite());

        //-更新商品信息
        Goods updateGoods = this.updateGoods(insertDTO, vendor,goodsDb.getState());

        //-更新商品扩展信息
        this.updateGoodsExtend(insertDTO, updateGoods);

        //-更新货品信息
        this.updateProduct(updateGoods, addProductList, updateProductList, deleteProductList);

        //-保存新的商品属性绑定表（检索属性）
        this.updateGoodsBindAttribute(insertDTO.getAttributeAndParameter(), updateGoods.getGoodsId());

        //-保存新的商品标签绑定表
        this.updateGoodsBindLabel(insertDTO.getGoodsLabelList(), updateGoods.getGoodsId());

        //-保存新的商品图片表
        this.updateGoodsPicture(insertDTO.getSpecInfoList(), insertDTO.getImageList(), updateGoods, vendor);

        //-保存新的商品附件表（goods_annex） insertDTO.getGoodsAnnexList()拿到前台的获取到的附件名称/附件路径的list
//        if(!CollectionUtils.isEmpty(insertDTO.getGoodsAnnexList())){
            this.updateGoodsAnnex(insertDTO.getGoodsAnnexList(),updateGoods,vendor);
//        }

        //-保存商品绑定店铺内部分类表
        this.updateGoodsBindStoreInnerLabels(insertDTO.getStoreInnerLabelList(), updateGoods.getGoodsId(), vendor);

        //-保存虚拟商品用户预留信息名称表
        this.updateGoodsBindReserveName(insertDTO.getReserveInfoList(), updateGoods.getGoodsId(), insertDTO.getIsVirtualGoods());

        //-增加/减少店铺商品数量(商品状态为上架时操作)
        this.updateStoreGoodsNum(goodsDb.getState(), updateGoods.getState(), vendor.getStoreId());

        if (goodsDb.getState().equals(GoodsConst.GOODS_STATE_UPPER)) {
            //原商品的状态为上架，删除商品缓存数据
            objectRedisTemplate.opsForHash().delete(RedisConst.GOODS_DETAIL, String.valueOf(goodsDb.getGoodsId()));
        }
        return updateGoods;
    }

    /**
     * 编辑后的货品列表与数据库中的货品列表做规格比对，构造新增、编辑、删除操作的货品列表
     *
     * @param goodsId           商品id
     * @param paramProductList  前端传来的货品列表
     * @param addProductList    最终要新增的货品
     * @param updateProductList 最终要编辑的货品
     * @param deleteProductList 最终要伪删除的货品
     */
    private void compareSpecWithDb(Long goodsId, List<GoodsPublishFrontParamDTO.ProductInfo> paramProductList,
                                   List<GoodsPublishInsertDTO.ProductInsertInfo> addProductList,
                                   List<GoodsPublishInsertDTO.ProductInsertInfo> updateProductList,
                                   List<Product> deleteProductList) {
        //数据库中的货品列表
        ProductExample productExample = new ProductExample();
        productExample.setGoodsId(goodsId);
        List<Product> dbProductList = productModel.getProductList(productExample, null);
        AssertUtil.notEmpty(dbProductList, "商品信息有误");

        //构造新增和更新的货品
        paramProductList.forEach(paramProduct -> {
            GoodsPublishInsertDTO.ProductInsertInfo paramInsertProduct = (GoodsPublishInsertDTO.ProductInsertInfo) paramProduct;
            boolean compared = false;//数据库中是否有此货品
            for (Product dbProduct : dbProductList) {
                if (compareSpec(paramInsertProduct, dbProduct)) {
                    //匹配成功，更新此货品
                    paramInsertProduct.setProductId(dbProduct.getProductId());
                    updateProductList.add(paramInsertProduct);
                    compared = true;
                    break;
                }
            }
            if (!compared) {
                //未匹配成功，添加此货品
                addProductList.add(paramInsertProduct);
            }
        });

        //构造要删除的列表
        dbProductList.forEach(dbProduct -> {
            boolean delete = true;//是否要删除
            for (GoodsPublishInsertDTO.ProductInsertInfo updateProduct : updateProductList) {
                if (dbProduct.getProductId().equals(updateProduct.getProductId())) {
                    //匹配成功，不需要删除
                    delete = false;
                    break;
                }
            }
            if (delete) {
                Product deleteProduct = new Product();
                deleteProduct.setProductId(dbProduct.getProductId());
                deleteProduct.setState(GoodsConst.PRODUCT_STATE_0);//删除状态
                deleteProduct.setIsDefault(GoodsConst.PRODUCT_IS_DEFAULT_NO);//给为非默认
                deleteProduct.setProductCode("");//清除sku code
                deleteProductList.add(deleteProduct);
            }
        });

    }

    /**
     * 前端货品与数据或货品比对
     *
     * @param paramProduct
     * @param dbProduct
     * @return
     */
    private boolean compareSpec(GoodsPublishInsertDTO.ProductInsertInfo paramProduct, Product dbProduct) {
        String s1 = paramProduct.getSpecValueIds();
        String s2 = dbProduct.getSpecValueIds();
        String[] arr1 = s1 == null ? "".split(",") : s1.split(",");//数组元素的格式为  规格id:规格值id
        String[] arr2 = s2 == null ? "".split(",") : s2.split(",");
        Arrays.sort(arr1);
        Arrays.sort(arr2);
        return Arrays.equals(arr1, arr2);
    }

    /**
     * 编辑商品-更新商品信息
     *
     * @param insertDTO
     * @param vendor
     * @return
     */
    private Goods updateGoods(GoodsPublishInsertDTO insertDTO, Vendor vendor,int state) {
        GoodsPublishInsertDTO.ProductInsertInfo defaultProduct = insertDTO.getDefaultProduct();
        //构造默认货品id
        long defaultProductId = StringUtil.isNullOrZero(defaultProduct.getProductId())
                ? GoodsIdGenerator.productIdGenerator() : defaultProduct.getProductId();
        //查询分类信息
        GoodsCategory goodsCategory3 = goodsCategoryModel.getGoodsCategoryByCategoryId(insertDTO.getCategoryId3());
        AssertUtil.notNull(goodsCategory3, "分类有误");
        GoodsCategory goodsCategory2 = goodsCategoryModel.getGoodsCategoryByCategoryId(goodsCategory3.getPid());
        GoodsCategory goodsCategory1 = goodsCategoryModel.getGoodsCategoryByCategoryId(goodsCategory2.getPid());

        Goods goods = new Goods();
        goods.setGoodsId(insertDTO.getGoodsId());
        goods.setGoodsName(insertDTO.getGoodsName());
        goods.setGoodsNameCn(insertDTO.getGoodsNameCn());
        goods.setGoodsBrief(StringUtils.isEmpty(insertDTO.getGoodsBrief()) ? "" : insertDTO.getGoodsBrief());//为传商品广告时，要清除原数据
        if (!StringUtil.isNullOrZero(insertDTO.getBrandId())) {
            //查询品牌信息
            GoodsBrand goodsBrand = goodsBrandModel.getGoodsBrandByBrandId(insertDTO.getBrandId());
            AssertUtil.notNull(goodsBrand, "品牌有误");
            goods.setBrandId(insertDTO.getBrandId());
            goods.setBrandName(goodsBrand.getBrandName());
        } else {
            //未选择品牌，要把之前的品牌信息清除
            goods.setBrandId(0);
            goods.setBrandName("");
        }
        Store storeDb = storeReadMapper.getByPrimaryKey(vendor.getStoreId());
        AssertUtil.notNull(storeDb, "未获取到店铺信息");
        if (storeDb.getIsOwnStore().equals(StoreConst.NO_OWN_STORE)) {
            //判断编辑的商品是否还能被推荐
            if (insertDTO.getStoreIsRecommend() == 1) {
                //查询该店铺已推荐的商品数
                GoodsExample goodsRecommendExample = new GoodsExample();
                goodsRecommendExample.setStoreId(vendor.getStoreId());
                goodsRecommendExample.setStateNotEquals(GoodsConst.GOODS_STATE_DELETE);
                goodsRecommendExample.setStoreIsRecommend(GoodsConst.IS_RECOMMEND_YES);
                List<Goods> goodsRecommends = goodsModel.getGoodsList(goodsRecommendExample, null);
                //获取该店铺推荐限制数
                StoreGrade storeGradeDb = storeGradeReadMapper.getByPrimaryKey(storeDb.getStoreGradeId());
                AssertUtil.isTrue(goodsRecommends.size() >= storeGradeDb.getRecommendLimit(), "店铺已达到推荐数限制，不能设为推荐");
            }
        }
        goods.setCategoryId1(goodsCategory1.getCategoryId());
        goods.setCategoryId2(goodsCategory2.getCategoryId());
        goods.setCategoryId3(goodsCategory3.getCategoryId());
        goods.setCategoryPath(goodsCategory1.getCategoryName() + "->" + goodsCategory2.getCategoryName() + "->" + goodsCategory3.getCategoryName());
        goods.setMarketPrice(StringUtil.isNullOrZero(defaultProduct.getMarketPrice()) ? new BigDecimal("0.00") : defaultProduct.getMarketPrice());
        goods.setGoodsStock(defaultProduct.getProductStock());
        goods.setGoodsPrice(defaultProduct.getProductPrice());
        goods.setIsSpec(CollectionUtils.isEmpty(insertDTO.getSpecInfoList()) ? GoodsConst.IS_SPEC_NO : GoodsConst.IS_SPEC_YES);
        goods.setMainSpecId(insertDTO.getMainSpecId());
        goods.setVirtualSales(insertDTO.getVirtualSales());
        if (state==GoodsConst.GOODS_STATE_LOWER_BY_SYSTEM) {
            goods.setState(GoodsConst.GOODS_STATE_LOWER_BY_SYSTEM);
        }else{
            goods.setState(this.dealGoodsState(insertDTO.getSellNow()));
        }
        goods.setIsSelf(vendor.getStore().getIsOwnStore());
        goods.setOnlineTime(goods.getState().equals(GoodsConst.GOODS_STATE_UPPER) ? new Date() : null);
        goods.setStoreId(vendor.getStoreId());
        goods.setStoreName(vendor.getStore().getStoreName());
        if (WebSiteConstant.MEMBER_DISTRIBUTOR.equals(insertDTO.getWebSite())) {
            StoreNameExample storeNameExample = new StoreNameExample();
            storeNameExample.setStoreId(vendor.getStoreId());
            storeNameExample.setWebSite(insertDTO.getWebSite());
            StoreName storeName = storeNameModel.getStoreNameByExample(storeNameExample);
            goods.setStoreName(storeName != null ? storeName.getStoreName() : "");
        }
        goods.setStoreIsRecommend(insertDTO.getStoreIsRecommend());
        goods.setMainImage(defaultProduct.getMainImage());
        goods.setGoodsVideo(StringUtils.isEmpty(insertDTO.getGoodsVideo()) ? "" : insertDTO.getGoodsVideo());
        goods.setBarCode(StringUtils.isEmpty(defaultProduct.getBarCode()) ? "" : defaultProduct.getBarCode());
        goods.setServiceLabelIds(StringUtils.isEmpty(insertDTO.getGoodsLabelIds()) ? "" : insertDTO.getGoodsLabelIds());
        goods.setDefaultProductId(defaultProductId);
        goods.setIsVatInvoice(insertDTO.getIsVatInvoice());
        goods.setAfterSaleService(insertDTO.getAfterSaleService());
        goods.setUpdateTime(new Date());
        goods.setGoodsMoney(StringUtil.isEmpty(insertDTO.getGoodsMoney())?"面议":insertDTO.getGoodsMoney());
        goods.setGoodsSummary(insertDTO.getGoodsSummary());
        goods.setGoodsMinOrder(insertDTO.getGoodsMinOrder());
        goodsModel.updateGoods(goods);


        //以下为新增SEO表
        SysSeo sysSeo = new SysSeo();
        sysSeo.setTenant(0L);
        sysSeo.setType(SeoTypeConstant.SEO_TYPE_GOODS);
        sysSeo.setName("商品SEO");
        sysSeo.setWebSite(insertDTO.getWebSite());
//        sysSeo.setCode(SeoTypeConstant.SEO_TYPE_GOODS+"_"+insertDTO.getGoodsId());
        sysSeo.setTargetId(insertDTO.getGoodsId());
        sysSeo.setTitle(insertDTO.getSeoTitle());
        sysSeo.setRemark(insertDTO.getSeoDesc());
        sysSeo.setKeywords(insertDTO.getSeoKeyWords());

        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = simpleDateFormat.format(date);

        //判断此条seoId对应的记录是否为空
        SysSeo seoInfo = storeModel.getRecordByTargetIdAndType(sysSeo.getTargetId(),sysSeo.getType());
        if(seoInfo !=null){
            sysSeo.setUpdateUid(vendor.getVendorId());
            sysSeo.setUpdateTime(time);
//            storeModel.updateSeoByTargetIdAndType(sysSeo,sysSeo.getTargetId(),sysSeo.getType());
            storeModel.updateSeo(sysSeo,sysSeo.getTargetId(),sysSeo.getType());
        }else{
            sysSeo.setCode(SeoTypeConstant.SEO_TYPE_GOODS+"_"+insertDTO.getGoodsId());
            sysSeo.setCreateUid(vendor.getVendorId());
            sysSeo.setCreateTime(time);
            storeModel.saveSeo(sysSeo);
        }

        return goods;
    }

    /**
     * 编辑商品-更新商品扩展表
     *
     * @param insertDTO
     * @param updateGoods
     */
    private void updateGoodsExtend(GoodsPublishInsertDTO insertDTO, Goods updateGoods) {
        GoodsExtend goodsExtend = new GoodsExtend();
        goodsExtend.setMainSpecId(updateGoods.getMainSpecId());
        if (!CollectionUtils.isEmpty(insertDTO.getSpecInfoList())) {
            goodsExtend.setSpecJson(JSON.toJSONString(insertDTO.getSpecInfoList()));
        } else {
            goodsExtend.setSpecJson("");
        }
        if (insertDTO.getAttributeAndParameter() != null) {
            if (!CollectionUtils.isEmpty(insertDTO.getAttributeAndParameter().getAttributeList())) {
                //检索属性
                goodsExtend.setAttributeJson(JSON.toJSONString(insertDTO.getAttributeAndParameter().getAttributeList()));
            } else {
                goodsExtend.setAttributeJson("");//未选择属性时，清除原有属性信息
            }
            if (insertDTO.getAttributeAndParameter().getParameterGroup() != null) {
                //自定义参数
                goodsExtend.setGoodsParameter(JSON.toJSONString(insertDTO.getAttributeAndParameter().getParameterGroup()));
            } else {
                goodsExtend.setGoodsParameter("");
            }
        } else {
            goodsExtend.setAttributeJson("");
            goodsExtend.setGoodsParameter("");
        }
        goodsExtend.setOnlineTime(updateGoods.getOnlineTime());
        goodsExtend.setProvinceCode(insertDTO.getProvinceCode());
        goodsExtend.setCityCode(insertDTO.getCityCode());
        goodsExtend.setFreightId(insertDTO.getFreightId());
        goodsExtend.setFreightFee(insertDTO.getFreightFee());
        goodsExtend.setRelatedTemplateIdTop(StringUtil.isNullOrZero(insertDTO.getRelatedTemplateIdTop()) ? 0 : insertDTO.getRelatedTemplateIdTop());
        goodsExtend.setRelatedTemplateIdBottom(StringUtil.isNullOrZero(insertDTO.getRelatedTemplateIdBottom()) ? 0 : insertDTO.getRelatedTemplateIdBottom());
        goodsExtend.setGoodsDetails(StringUtils.isEmpty(insertDTO.getGoodsDetails()) ? "" : insertDTO.getGoodsDetails());
        goodsExtend.setAuditReason("");
        goodsExtend.setOfflineReason("");
        goodsExtend.setOfflineComment("");

        GoodsExtendExample extendExample = new GoodsExtendExample();
        extendExample.setGoodsId(updateGoods.getGoodsId());
        Integer count = goodsExtendModel.updateGoodsExtendByExample(goodsExtend, extendExample);
        AssertUtil.isTrue(count == 0, "更新商品扩展信息失败");
    }

    /**
     * 编辑商品-更新货品信息
     *
     * @param updateGoods
     * @param addProductList
     * @param updateProductList
     * @param deleteProductList
     */
    private void updateProduct(Goods updateGoods, List<GoodsPublishInsertDTO.ProductInsertInfo> addProductList,
                               List<GoodsPublishInsertDTO.ProductInsertInfo> updateProductList,
                               List<Product> deleteProductList) {
        //新增
        this.updateProductAdd(updateGoods, addProductList);
        //编辑
        this.updateProductUpdate(updateGoods, updateProductList);
        //删除
        this.updateProductDelete(deleteProductList);
    }

    /**
     * 编辑商品-更新货品信息-新增货品
     *
     * @param updateGoods
     * @param addProductList
     */
    private void updateProductAdd(Goods updateGoods, List<GoodsPublishInsertDTO.ProductInsertInfo> addProductList) {
        if (CollectionUtils.isEmpty(addProductList)) {
            return;
        }
        addProductList.forEach(productInsertInfo -> {
            this.doInsertProduct(updateGoods, productInsertInfo);
        });
    }

    /**
     * 编辑商品-更新货品信息-更新货品
     *
     * @param updateGoods
     * @param updateProductList
     */
    private void updateProductUpdate(Goods updateGoods, List<GoodsPublishInsertDTO.ProductInsertInfo> updateProductList) {
        if (CollectionUtils.isEmpty(updateProductList)) {
            return;
        }
        updateProductList.forEach(productInsertInfo -> {
            Product product = new Product();
            product.setProductId(productInsertInfo.getProductId());
            product.setGoodsName(updateGoods.getGoodsName());
            product.setGoodsNameCn(updateGoods.getGoodsNameCn());
            product.setSpecValues(productInsertInfo.getSpecValues());
            product.setSpecValueIds(productInsertInfo.getSpecValueIds());
            product.setBrandId(StringUtil.isNullOrZero(updateGoods.getBrandId()) ? 0 : updateGoods.getBrandId());
            product.setBrandName(StringUtil.isNullOrZero(updateGoods.getBrandId()) ? "" : updateGoods.getBrandName());
            product.setCategoryId1(updateGoods.getCategoryId1());
            product.setCategoryId2(updateGoods.getCategoryId2());
            product.setCategoryId3(updateGoods.getCategoryId3());
            product.setCategoryPath(updateGoods.getCategoryPath());
            product.setProductPrice(productInsertInfo.getProductPrice());
            product.setMarketPrice(StringUtil.isNullOrZero(productInsertInfo.getMarketPrice()) ? new BigDecimal("0.00") : productInsertInfo.getMarketPrice());
            product.setProductStock(productInsertInfo.getProductStock());
            product.setProductStockWarning(productInsertInfo.getProductStockWarning());
            product.setProductCode(StringUtils.isEmpty(productInsertInfo.getProductCode()) ? "" : productInsertInfo.getProductCode());
            product.setBarCode(StringUtils.isEmpty(productInsertInfo.getBarCode()) ? "" : productInsertInfo.getBarCode());
            product.setWeight(StringUtil.isNullOrZero(productInsertInfo.getWeight()) ? BigDecimal.ZERO : productInsertInfo.getWeight());
            product.setLength(StringUtil.isNullOrZero(productInsertInfo.getLength()) ? BigDecimal.ZERO : productInsertInfo.getLength());
            product.setWidth(StringUtil.isNullOrZero(productInsertInfo.getWidth()) ? BigDecimal.ZERO : productInsertInfo.getWidth());
            product.setHeight(StringUtil.isNullOrZero(productInsertInfo.getHeight()) ? BigDecimal.ZERO : productInsertInfo.getHeight());
            product.setMainImage(productInsertInfo.getMainImage());
            product.setState(productInsertInfo.getState());
            product.setIsDefault(productInsertInfo.getIsDefault());
            productModel.updateProduct(product);
        });
    }

    /**
     * 编辑商品-更新货品信息-删除货品
     *
     * @param deleteProductList
     */
    private void updateProductDelete(List<Product> deleteProductList) {
        if (CollectionUtils.isEmpty(deleteProductList)) {
            return;
        }
        deleteProductList.forEach(product -> {
            productModel.updateProduct(product);
        });
    }

    /**
     * 编辑商品-更新商品属性绑定表
     *
     * @param attributeAndParameter
     * @param goodsId
     */
    private void updateGoodsBindAttribute(GoodsPublishFrontParamDTO.AttributeAndParameter attributeAndParameter, Long goodsId) {
        //删除原有的绑定关系
        goodsBindAttributeValueModel.deleteGoodsBindAttributeValueByGoodsId(goodsId);
        //新增绑定关系
        this.insertGoodsBindAttribute(attributeAndParameter, goodsId);
    }

    /**
     * 编辑商品-更新商品标签绑定表
     *
     * @param goodsLabelInfoList
     * @param goodsId
     */
    private void updateGoodsBindLabel(List<GoodsPublishFrontParamDTO.GoodsLabelInfo> goodsLabelInfoList, Long goodsId) {
        //删除原有的绑定关系
        goodsBindLabelModel.deleteGoodsBindLabelByGoodsId(goodsId);
        //新增绑定关系
        this.insertGoodsBindLabels(goodsLabelInfoList, goodsId);
    }

    /**
     * 编辑商品-更新商品图片
     *
     * @param specInfoList  规格列表
     * @param imageInfoList 图片列表
     * @param goods         商品信息
     * @param vendor        商户管理员
     */
    private void updateGoodsPicture(List<GoodsPublishFrontParamDTO.SpecInfo> specInfoList, List<GoodsPublishFrontParamDTO.ImageInfo> imageInfoList, Goods goods, Vendor vendor) {
        //删除原有图片
        goodsPictureModel.deleteGoodsPictureGoodsId(goods.getGoodsId());
        //新增图片
        this.insertGoodsPicture(specInfoList, imageInfoList, goods, vendor);
    }

    /**
     * 编辑商品-更新商品附件
     * @param annexInfoList 前台传过来的附件信息
     * @param goods
     * @param vendor
     */
    private void updateGoodsAnnex(List<GoodsPublishFrontParamDTO.AnnexInfo> annexInfoList, Goods goods, Vendor vendor){
        //先将页面上的附件的status置为0，下一步再重新回填
        goodsAnnexModel.deleteAndUpdateGoodsAnnex(annexInfoList,goods,vendor);

    }

    /**
     * 编辑商品-更新商品附件
     * @param annexInfoList 前台传过来的附件信息
     * @param goods
     * @param vendor
     */
    private void insertGoodsAnnex(List<GoodsPublishFrontParamDTO.AnnexInfo> annexInfoList, Goods goods, Vendor vendor){
        goodsAnnexModel.insertGoodsAnnex(annexInfoList,goods,vendor);
    }


    /**
     * 编辑商品-更新商品绑定店铺内部分类
     *
     * @param storeInnerLabelList
     * @param goodsId
     * @param vendor
     */
    private void updateGoodsBindStoreInnerLabels(List<GoodsPublishFrontParamDTO.StoreInnerLabelInfo> storeInnerLabelList, Long goodsId, Vendor vendor) {
        //删除原有绑定关系
        StoreLabelBindGoodsExample example = new StoreLabelBindGoodsExample();
        example.setGoodsId(goodsId);
        storeLabelBindGoodsWriteMapper.deleteByExample(example);

        //新增绑定关系
        this.insertGoodsBindStoreInnerLabels(storeInnerLabelList, goodsId, vendor);
    }

    /**
     * 编辑商品-更新虚拟商品用户预留信息名称
     *
     * @param reserveInfoList 用户预留信息名称列表
     * @param goodsId         商品id
     * @param isVirtualGoods  是否是虚拟商品：1-实物商品；2-虚拟商品
     */
    private void updateGoodsBindReserveName(List<GoodsPublishFrontParamDTO.GoodsReserveNameInfo> reserveInfoList, Long goodsId, Integer isVirtualGoods) {
        //删除原有绑定关系
        GoodsBindReserveNameExample example = new GoodsBindReserveNameExample();
        example.setGoodsId(goodsId);
        goodsBindReserveNameWriteMapper.deleteByExample(example);

        //新增绑定关系
        this.insertGoodsBindReserveName(reserveInfoList, goodsId, isVirtualGoods);
    }

    /**
     * 编辑商品-更新店铺商品数量
     *
     * @param oldGoodsState 原商品状态
     * @param newGoodsState 新商品状态
     * @param storeId       店铺id
     */
    private void updateStoreGoodsNum(Integer oldGoodsState, Integer newGoodsState, Long storeId) {
        Store storeDb = storeReadMapper.getByPrimaryKey(storeId);
        int goodsNum = storeDb.getGoodsNumber();
        if (oldGoodsState.equals(GoodsConst.GOODS_STATE_UPPER)) {
            //原商品的状态为上架，店铺商品数量--
            goodsNum--;
        }
        if (newGoodsState.equals(GoodsConst.GOODS_STATE_UPPER)) {
            //新的商品状态为上架,店铺商品数量++
            goodsNum++;
        }
        if (!storeDb.getGoodsNumber().equals(goodsNum)) {
            //商品数量发生变化才更新
            Store update = new Store();
            update.setStoreId(storeId);
            update.setGoodsNumber(goodsNum);
            storeWriteMapper.updateByPrimaryKeySelective(update);
        }
    }

    //endregion


    /**
     * 商品上架
     *
     * @param goodsIds
     * @return storeId
     */
    public Integer upperShelfGoods(Long storeId, String goodsIds) {
        //商品上架
        //11-放入仓库无需审核 12-放入仓库审核通过 的商品才能上架
        Goods goodsUpdate = new Goods();
        goodsUpdate.setState(GoodsConst.GOODS_STATE_UPPER);
        goodsUpdate.setOnlineTime(new Date());
        goodsUpdate.setUpdateTime(new Date());
        GoodsExample example = new GoodsExample();
        example.setGoodsIdIn(goodsIds);
        example.setStateIn(GoodsConst.GOODS_STATE_WAREHOUSE_NO_AUDIT + "," + GoodsConst.GOODS_STATE_WAREHOUSE_AUDIT_PASS + "," + GoodsConst.GOODS_STATE_LOWER_BY_STORE);
        example.setStoreId(storeId);
        List<Goods> goodsList = goodsModel.getGoodsList(example, null);
        int num = goodsModel.updateGoodsByExample(goodsUpdate, example);
        goodsList.forEach(goods -> {
            VendorExample vendorExample = new VendorExample();
            vendorExample.setStoreId(goods.getStoreId());
            vendorExample.setIsStoreAdmin(VendorConst.IS_STORE_ADMIN_1);
            List<Vendor> vendorList  =vendorModel.getVendorList(vendorExample, null);
            AssertUtil.isTrue(CollectionUtils.isEmpty(vendorList), "获取店铺信息失败");
            goods.setState(GoodsConst.GOODS_STATE_UPPER);
            productModel.upsertProduct(goods, vendorList.get(0));
        });
        return num;
    }

    public Integer illegalUpperShelf(Long storeId, String goodsIds) {
        //违规商品 重新上架
        //11-放入仓库无需审核 12-放入仓库审核通过 的商品才能上架
        GoodsExample example = new GoodsExample();
        example.setGoodsIdIn(goodsIds);
        example.setStateIn(String.valueOf(GoodsConst.GOODS_STATE_LOWER_BY_SYSTEM));
        example.setStoreId(storeId);
        List<Goods> goodsList = goodsModel.getGoodsList(example, null);

        Goods goodsUpdate = new Goods();
        goodsUpdate.setState(GoodsConst.GOODS_STATE_SELL_NOW_TO_AUDIT);
        goodsUpdate.setOnlineTime(new Date());
        goodsUpdate.setUpdateTime(new Date());
        int num = goodsModel.updateGoodsByExample(goodsUpdate, example);
        goodsList.forEach(goods -> {
            VendorExample vendorExample = new VendorExample();
            vendorExample.setStoreId(goods.getStoreId());
            vendorExample.setIsStoreAdmin(VendorConst.IS_STORE_ADMIN_1);
            List<Vendor> vendorList  =vendorModel.getVendorList(vendorExample, null);
            AssertUtil.isTrue(CollectionUtils.isEmpty(vendorList), "获取店铺信息失败");
            goods.setState(GoodsConst.GOODS_STATE_SELL_NOW_TO_AUDIT);
            productModel.upsertProduct(goods, vendorList.get(0));
        });
        return num;
    }

    /**
     * 商品下架
     *
     * @param storeId  店铺id
     * @param goodsIds 商品id集合
     */
    public Integer lockupGoods(Long storeId, String goodsIds) {
        //商品下架（商户自行下架）
        Goods goodsUpdate = new Goods();
        goodsUpdate.setState(GoodsConst.GOODS_STATE_LOWER_BY_STORE);
        goodsUpdate.setUpdateTime(new Date());
        GoodsExample example = new GoodsExample();
        example.setGoodsIdIn(goodsIds);
        example.setState(GoodsConst.GOODS_STATE_UPPER);
        example.setStoreId(storeId);
        List<Goods> goodsList = goodsModel.getGoodsList(example, null);
        int number = goodsModel.updateGoodsByExample(goodsUpdate, example);
        goodsList.forEach(goods -> {
            VendorExample vendorExample = new VendorExample();
            vendorExample.setStoreId(goods.getStoreId());
            vendorExample.setIsStoreAdmin(VendorConst.IS_STORE_ADMIN_1);
            List<Vendor> vendorList = vendorModel.getVendorList(vendorExample, null);
            AssertUtil.isTrue(CollectionUtils.isEmpty(vendorList), "获取店铺信息失败");
            goods.setState(GoodsConst.GOODS_STATE_LOWER_BY_STORE);
            productModel.upsertProduct(goods, vendorList.get(0));
        });
        return number;
    }

    /**
     * 根据goodsId更新商品公共信息表（SPU） 修改商品状态为删除
     *
     * @param storeId
     * @param goodsIds
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public Integer deleteGoods(Long storeId, String goodsIds) {
        int number = 0;
        //删除商品
        Goods goodsUpdate = new Goods();
        goodsUpdate.setIsDelete(GoodsConst.GOODS_IS_DELETE_YES);
        goodsUpdate.setState(GoodsConst.GOODS_STATE_DELETE);
        goodsUpdate.setUpdateTime(new Date());
        GoodsExample example = new GoodsExample();
        example.setGoodsIdIn(goodsIds);
//        example.setStateIn(GoodsConst.GOODS_STATE_WAREHOUSE_NO_AUDIT + "," + GoodsConst.GOODS_STATE_LOWER_BY_STORE + "," + GoodsConst.GOODS_STATE_LOWER_BY_SYSTEM);
        example.setStoreId(storeId);
        //先查询出待删除的商品列表
        List<Goods> goodsList = goodsModel.getGoodsList(example, null);

        number = goodsModel.updateGoodsByExample(goodsUpdate, example);
        goodsList.forEach(goods -> {
            VendorExample vendorExample = new VendorExample();
            vendorExample.setStoreId(storeId);
            vendorExample.setIsStoreAdmin(VendorConst.IS_STORE_ADMIN_1);
            List<Vendor> vendorList = vendorModel.getVendorList(vendorExample, null);
            AssertUtil.isTrue(CollectionUtils.isEmpty(vendorList), "获取店铺信息失败");
            //设置状态为删除
            goods.setState(GoodsConst.GOODS_STATE_DELETE);
            productModel.upsertProduct(goods, vendorList.get(0));
        });
        return number;
    }

    /**
     * 平台库商品导入
     *
     * @param platformImportDTO   前端传参信息
     * @param goodsPlatformDb     平台库商品信息
     * @param productPlatformList 平台库货品列表信息
     * @param vendor              商户信息
     */
    @Transactional(rollbackFor = Exception.class)
    public void goodsPlatformImport(GoodsPlatformImportDTO platformImportDTO, GoodsPlatform goodsPlatformDb,
                                    List<ProductPlatform> productPlatformList, Vendor vendor) {
        //默认选中的第一条数据为默认货品
        Long platformProductId = Long.parseLong(platformImportDTO.getPlatformProductIds().split(",")[0]);
        ProductPlatform productPlatform = null;
        for (ProductPlatform productPlatformDb : productPlatformList) {
            if (platformProductId.equals(productPlatformDb.getPlatformProductId())) {
                productPlatform = productPlatformDb;
                break;
            }
        }
        if (productPlatform == null) {
            productPlatform = productPlatformList.get(0);
            platformProductId = productPlatform.getPlatformProductId();
        }

        //-导入商品信息
        Goods goods = this.importGoods(vendor, platformImportDTO, goodsPlatformDb, productPlatform);

        //-导入商品扩展信息
        this.importGoodsExtend(platformImportDTO, goodsPlatformDb, goods, vendor);

        //-导入货品信息
        this.importProduct(platformImportDTO, productPlatformList, goods, platformProductId);

        //-导入商品属性绑定表（检索属性）
        this.importGoodsBindAttribute(goodsPlatformDb.getAttributeJson(), goods.getGoodsId());

        //-导入商品图片表
        this.importGoodsPicture(goodsPlatformDb.getPlatformGoodsId(), goods.getGoodsId(), vendor);

        //-导入虚拟商品用户预留信息名称表
        this.importGoodsBindReserveName(goodsPlatformDb.getPlatformGoodsId(), goods.getGoodsId(), goods.getIsVirtualGoods());

        //-增加店铺商品数量(商品状态为上架时操作)
        this.addStoreGoodsNum(vendor.getStoreId(), goods.getState());
    }

    /**
     * 导入商品
     *
     * @param vendor            店铺管理员
     * @param platformImportDTO 前端传参信息
     * @param goodsPlatformDb   平台库商品信息
     * @param productPlatform   默认货品信息
     * @return
     */
    private Goods importGoods(Vendor vendor, GoodsPlatformImportDTO platformImportDTO, GoodsPlatform goodsPlatformDb,
                              ProductPlatform productPlatform) {
        //商品id
        long goodsId = GoodsIdGenerator.goodsIdGenerator();
        //生成一个默认货品id
        long defaultProductId = GoodsIdGenerator.productIdGenerator();

        Goods goods = new Goods();
        goods.setGoodsId(goodsId);
        goods.setGoodsName(goodsPlatformDb.getGoodsName());
        goods.setGoodsBrief(goodsPlatformDb.getGoodsBrief());
        goods.setBrandId(goodsPlatformDb.getBrandId());
        goods.setBrandName(goodsPlatformDb.getBrandName());
        goods.setCategoryId1(goodsPlatformDb.getCategoryId1());
        goods.setCategoryId2(goodsPlatformDb.getCategoryId2());
        goods.setCategoryId3(goodsPlatformDb.getCategoryId3());
        goods.setCategoryPath(goodsPlatformDb.getCategoryPath());
        goods.setMarketPrice(goodsPlatformDb.getMarketPrice());
        goods.setGoodsPrice(this.dealChangePrice(productPlatform.getProductPrice(), platformImportDTO.getChangeValue(), platformImportDTO.getChangeType()));
        goods.setGoodsStock(platformImportDTO.getProductStock());
        goods.setIsSpec(goodsPlatformDb.getIsSpec());
        goods.setMainSpecId(goodsPlatformDb.getMainSpecId());
        goods.setIsSelf(vendor.getStore().getIsOwnStore());
        goods.setState(this.dealGoodsState(platformImportDTO.getImportState()));
        goods.setOnlineTime(goods.getState().equals(GoodsConst.GOODS_STATE_UPPER) ? new Date() : null);
        goods.setStoreId(vendor.getStoreId());
        goods.setStoreName(vendor.getStore().getStoreName());
        goods.setStoreIsRecommend(0);
        goods.setMainImage(productPlatform.getMainImage());
        goods.setGoodsVideo(goodsPlatformDb.getGoodsVideo());
        goods.setBarCode(productPlatform.getBarCode());
        goods.setDefaultProductId(defaultProductId);
        goods.setIsVirtualGoods(goodsPlatformDb.getIsVirtualGoods());
        goods.setAfterSaleService(goodsPlatformDb.getAfterSaleService());
        goods.setPlatformGoodsId(goodsPlatformDb.getPlatformGoodsId());
        goods.setCreateTime(new Date());
        goods.setUpdateTime(new Date());
        goodsModel.saveGoods(goods);
        return goods;
    }

    /**
     * 处理变动价格
     *
     * @param productPrice
     * @param changeValue
     * @param changeType
     * @return
     */
    public BigDecimal dealChangePrice(BigDecimal productPrice, BigDecimal changeValue, Integer changeType) {
        if (StringUtil.isNullOrZero(changeType)) {
            return productPrice;
        }
        if (changeType == GoodsPlatformConst.CHANGE_TYPE_2) {
            productPrice = productPrice.subtract(changeValue);
        } else if (changeType == GoodsPlatformConst.CHANGE_TYPE_3) {
            productPrice = productPrice.multiply(changeValue);
        } else if (changeType == GoodsPlatformConst.CHANGE_TYPE_4) {
            productPrice = productPrice.divide(changeValue).setScale(2, RoundingMode.HALF_UP);
        } else {
            productPrice = productPrice.add(changeValue);
        }
        return productPrice;
    }

    /**
     * 导入商品扩展信息
     *
     * @param platformImportDTO 前端传参信息
     * @param goodsPlatformDb   平台库商品信息
     * @param goods             商品信息
     * @param vendor            商户信息
     */
    private void importGoodsExtend(GoodsPlatformImportDTO platformImportDTO, GoodsPlatform goodsPlatformDb, Goods goods, Vendor vendor) {
        GoodsExtend goodsExtend = new GoodsExtend();
        goodsExtend.setExtendId(GoodsIdGenerator.goodsExtendIdGenerator());
        goodsExtend.setGoodsId(goods.getGoodsId());
        goodsExtend.setMainSpecId(goods.getMainSpecId());
        goodsExtend.setSpecJson(this.dealSpecJson(goodsPlatformDb.getSpecJson(), vendor));
        goodsExtend.setAttributeJson(goodsPlatformDb.getAttributeJson());
        goodsExtend.setGoodsParameter(goodsPlatformDb.getGoodsParameter());
        goodsExtend.setOnlineTime(goods.getOnlineTime());
        goodsExtend.setCreateVendorId(vendor.getVendorId());
        goodsExtend.setCreateTime(new Date());
        goodsExtend.setFreightId(platformImportDTO.getFreightId());
        goodsExtend.setFreightFee(platformImportDTO.getFreightFee());
        goodsExtend.setGoodsDetails(goodsPlatformDb.getGoodsDetails());
        goodsExtendModel.saveGoodsExtend(goodsExtend);
    }

    /**
     * 处理规格信息
     *
     * @param specJson 规格json信息
     * @param vendor   商户信息
     * @return
     */
    public String dealSpecJson(String specJson, Vendor vendor) {
        if (StringUtil.isEmpty(specJson)) {
            return null;
        }
        //原始数据
        List<GoodsPublishFrontParamDTO.SpecInfo> dbSpecInfoList = JSON.parseArray(specJson, GoodsPublishFrontParamDTO.SpecInfo.class);
        //重新组装规格信息
        List<GoodsPublishFrontParamDTO.SpecInfo> specInfoList = new ArrayList<>();
        for (GoodsPublishFrontParamDTO.SpecInfo specInfo : dbSpecInfoList) {
            //店铺是否有此规格,没有则插入，返回规格id
            Integer specId = this.importGoodsSpec(specInfo.getSpecName(), vendor);
            GoodsPublishFrontParamDTO.SpecInfo info = new GoodsPublishFrontParamDTO.SpecInfo();
            info.setSpecId(specId);
            info.setSpecName(specInfo.getSpecName());
            info.setIsMainSpec(specInfo.getIsMainSpec());
            List<GoodsPublishFrontParamDTO.SpecInfo.SpecValueInfo> specValueList = new ArrayList<>();
            for (GoodsPublishFrontParamDTO.SpecInfo.SpecValueInfo specValueInfo : specInfo.getSpecValueList()) {
                //店铺是否有此规格值,没有则插入，返回规格值id
                Integer specValueId = this.importGoodsSpecValue(specId, specValueInfo.getSpecValue(), vendor.getVendorId(), vendor.getStoreId());
                GoodsPublishFrontParamDTO.SpecInfo.SpecValueInfo valueInfo = new GoodsPublishFrontParamDTO.SpecInfo.SpecValueInfo();
                valueInfo.setSpecValueId(specValueId);
                valueInfo.setSpecValue(specValueInfo.getSpecValue());
                valueInfo.setImageList(specValueInfo.getImageList());
                specValueList.add(valueInfo);
            }
            info.setSpecValueList(specValueList);
            specInfoList.add(info);
        }
        return JSON.toJSONString(specInfoList);
    }

    /**
     * 导入规格信息
     *
     * @param specName 规格名称
     * @param vendor   商户信息
     * @return
     */
    public Integer importGoodsSpec(String specName, Vendor vendor) {
        //判断属性名称是否重复
        GoodsSpecExample example = new GoodsSpecExample();
        example.setStoreId(vendor.getStoreId());
        example.setSpecName(specName);
        List<GoodsSpec> list = goodsSpecReadMapper.listByExample(example);
        if (!CollectionUtils.isEmpty(list)) {
            return list.get(0).getSpecId();
        } else {
            //插入规格
            GoodsSpec goodsSpec = new GoodsSpec();
            goodsSpec.setSpecName(specName);
            goodsSpec.setSpecType(GoodsConst.SPEC_TYPE_1);
            goodsSpec.setStoreId(vendor.getStoreId());
            goodsSpec.setCreateId(vendor.getVendorId());
            goodsSpec.setCreateName(vendor.getVendorName());
            goodsSpec.setCreateTime(new Date());
            goodsSpec.setUpdateId(vendor.getVendorId());
            goodsSpec.setUpdateName(vendor.getVendorName());
            goodsSpec.setUpdateTime(new Date());
            goodsSpec.setState(GoodsConst.IS_SPEC_YES);
            goodsSpec.setSort(1);
            int count = goodsSpecWriteMapper.insert(goodsSpec);
            AssertUtil.isTrue(count == 0, "添加规格失败，请重试");
            return goodsSpec.getSpecId();
        }
    }

    /**
     * 导入规格值信息
     *
     * @param specId    规格id
     * @param specValue 规格值
     * @param creatId   创建人id
     * @return
     */
    public Integer importGoodsSpecValue(Integer specId, String specValue, Long creatId, Long storeId) {
        //判断规则值是否重复
        GoodsSpecValueExample example = new GoodsSpecValueExample();
        example.setSpecId(specId);
        example.setSpecValue(specValue);
        List<GoodsSpecValue> list = goodsSpecValueReadMapper.listByExample(example);
        if (!CollectionUtils.isEmpty(list)) {
            return list.get(0).getSpecValueId();
        } else {
            //插入规格值
            GoodsSpecValue goodsSpecValue = new GoodsSpecValue();
            goodsSpecValue.setSpecValue(specValue);
            goodsSpecValue.setSpecId(specId);
            goodsSpecValue.setStoreId(storeId);
            goodsSpecValue.setCreateId(creatId);
            goodsSpecValue.setCreateTime(new Date());
            int count = goodsSpecValueWriteMapper.insert(goodsSpecValue);
            AssertUtil.isTrue(count == 0, "添加规格值失败，请重试");
            return goodsSpecValue.getSpecValueId();
        }
    }

    /**
     * 导入货品信息
     *
     * @param platformImportDTO   前端传参信息
     * @param productPlatformList 平台库货品列表
     * @param goods               商品信息
     * @param platformProductId   平台库货品id
     */
    private void importProduct(GoodsPlatformImportDTO platformImportDTO, List<ProductPlatform> productPlatformList,
                               Goods goods, Long platformProductId) {
        //选中的规格列表
        List<String> list = Arrays.asList(platformImportDTO.getPlatformProductIds().split(","));
        productPlatformList.forEach(productPlatform -> {
            Product product = new Product();
            if (platformProductId.equals(productPlatform.getPlatformProductId())) {
                //默认货品
                product.setProductId(goods.getDefaultProductId());
                product.setIsDefault(GoodsConst.PRODUCT_IS_DEFAULT_YES);
            } else {
                //非默认货品，生成货品id
                product.setProductId(GoodsIdGenerator.productIdGenerator());
                product.setIsDefault(GoodsConst.PRODUCT_IS_DEFAULT_NO);
            }
            product.setGoodsId(goods.getGoodsId());
            product.setGoodsName(goods.getGoodsName());
            product.setSpecValues(productPlatform.getSpecValues());
            product.setSpecValueIds(this.dealSpecValueIds(productPlatform.getSpecValues(), goods.getStoreId()));
            product.setBrandId(productPlatform.getBrandId());
            product.setBrandName(productPlatform.getBrandName());
            product.setStoreId(goods.getStoreId());
            product.setStoreName(goods.getStoreName());
            product.setCategoryId1(productPlatform.getCategoryId1());
            product.setCategoryId2(productPlatform.getCategoryId2());
            product.setCategoryId3(productPlatform.getCategoryId3());
            product.setCategoryPath(productPlatform.getCategoryPath());
            product.setProductPrice(this.dealChangePrice(productPlatform.getProductPrice(), platformImportDTO.getChangeValue(), platformImportDTO.getChangeType()));
            product.setMarketPrice(productPlatform.getMarketPrice());
            product.setProductStock(platformImportDTO.getProductStock());
            product.setBarCode(productPlatform.getBarCode());
            product.setWeight(productPlatform.getWeight());
            product.setLength(productPlatform.getLength());
            product.setWidth(productPlatform.getWidth());
            product.setHeight(productPlatform.getHeight());
            product.setMainImage(productPlatform.getMainImage());
            //判断是否是选中的规格，不是的话禁用
            if (list.contains(productPlatform.getPlatformProductId().toString())) {
                product.setState(GoodsConst.PRODUCT_STATE_1);
            } else {
                product.setState(GoodsConst.PRODUCT_STATE_2);
            }
            productModel.saveProduct(product);
        });
    }

    /**
     * 处理规格值id
     *
     * @param specValues 规格值信息
     * @param storeId    店铺id
     * @return
     */
    public String dealSpecValueIds(String specValues, Long storeId) {
        StringBuilder specIds = new StringBuilder();
        if (StringUtil.isEmpty(specValues)) {
            return specIds.toString();
        }
        String[] specValueArray = specValues.split(",");
        for (String specValue : specValueArray) {
            if (StringUtil.isEmpty(specValue)) {
                continue;
            }
            //查询规则值id
            GoodsSpecValueExample example = new GoodsSpecValueExample();
            example.setStoreId(storeId);
            example.setSpecValue(specValue);
            List<GoodsSpecValue> list = goodsSpecValueWriteMapper.listByExample(example);
            specIds.append(",").append(list.get(0).getSpecValueId());
        }
        return specIds.toString().substring(1);
    }

    /**
     * 导入商品属性信息
     *
     * @param attributeJson 属性json信息
     * @param goodsId
     */
    private void importGoodsBindAttribute(String attributeJson, Long goodsId) {
        if (StringUtil.isEmpty(attributeJson)) {
            return;
        }
        List<GoodsPublishFrontParamDTO.AttributeAndParameter.Attribute> attributeList = JSON.parseArray(attributeJson,
                GoodsPublishFrontParamDTO.AttributeAndParameter.Attribute.class);
        attributeList.forEach(attribute -> {
            GoodsBindAttributeValue goodsBindAttributeValue = new GoodsBindAttributeValue();
            goodsBindAttributeValue.setGoodsId(goodsId);
            goodsBindAttributeValue.setAttributeId(attribute.getAttributeId());
            goodsBindAttributeValue.setAttributeName(attribute.getAttributeName());
            goodsBindAttributeValue.setAttributeValueId(attribute.getAttributeValueId());
            goodsBindAttributeValue.setAttributeValue(attribute.getAttributeValue());
            goodsBindAttributeValueModel.saveGoodsBindAttributeValue(goodsBindAttributeValue);
        });
    }

    /**
     * 导入图片信息
     *
     * @param platformGoodsId
     * @param goodsId
     * @param vendor
     */
    private void importGoodsPicture(Long platformGoodsId, Long goodsId, Vendor vendor) {
        //查询平台库商品图片信息
        GoodsPlatformPictureExample example = new GoodsPlatformPictureExample();
        example.setPlatformGoodsId(platformGoodsId);
        example.setOrderBy("picture_id asc");
        List<GoodsPlatformPicture> list = goodsPlatformPictureReadMapper.listByExample(example);
        AssertUtil.notEmpty(list, "商品图片不存在");
        list.forEach(goodsPlatformPicture -> {
            GoodsPicture goodsPicture = new GoodsPicture();
            goodsPicture.setGoodsId(goodsId);
            goodsPicture.setImagePath(goodsPlatformPicture.getImagePath());
            goodsPicture.setSort(1);
            goodsPicture.setCreateId(vendor.getVendorId());
            goodsPicture.setCreateTime(new Date());
            goodsPicture.setStoreId(vendor.getStoreId());
            goodsPicture.setIsMain(goodsPlatformPicture.getIsMain());
            goodsPicture.setSpecValueId(goodsPlatformPicture.getSpecValueId());
            goodsPictureModel.saveGoodsPicture(goodsPicture);
        });
    }

    /**
     * 导入虚拟商品用户预留信息名称信息
     *
     * @param platformGoodsId 平台库商品id
     * @param goodsId         商品id
     * @param isVirtualGoods  是否是虚拟商品：1-实物商品；2-虚拟商品
     */
    private void importGoodsBindReserveName(Long platformGoodsId, Long goodsId, Integer isVirtualGoods) {
        if (isVirtualGoods == GoodsConst.IS_VIRTUAL_GOODS_1) {
            return;
        }
        GoodsPlatformBindReserveNameExample example = new GoodsPlatformBindReserveNameExample();
        example.setPlatformGoodsId(platformGoodsId);
        example.setOrderBy("reserve_name_id asc");
        List<GoodsPlatformBindReserveName> list = goodsPlatformBindReserveNameReadMapper.listByExample(example);
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        list.forEach(reserveNameInfo -> {
            GoodsBindReserveName goodsBindReserveName = new GoodsBindReserveName();
            goodsBindReserveName.setReserveName(reserveNameInfo.getReserveName());
            goodsBindReserveName.setReserveType(reserveNameInfo.getReserveType());
            goodsBindReserveName.setIsRequired(reserveNameInfo.getIsRequired());
            goodsBindReserveName.setGoodsId(goodsId);
            int count = goodsBindReserveNameWriteMapper.insert(goodsBindReserveName);
            AssertUtil.isTrue(count == 0, "添加虚拟商品用户预留信息名称表失败，请重试");
        });
    }

}