package com.kmall.admin.service.impl;

import com.google.common.collect.ImmutableBiMap;
import com.google.common.collect.Maps;
import com.kmall.admin.dao.*;
import com.kmall.admin.dao.mk.dist.MkDistSellAllocationDao;
import com.kmall.admin.dto.StoreGoodsDto;
import com.kmall.admin.entity.*;
import com.kmall.admin.entity.mk.dist.MkDistSellAllocationEntity;
import com.kmall.admin.service.ProductStoreRelaService;
import com.kmall.admin.utils.ShiroUtils;
import com.kmall.api.util.StockUtil;
import com.kmall.common.constant.Dict;
import com.kmall.admin.fromcomm.entity.SysUserEntity;
import com.kmall.common.utils.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

/**
 * Service实现类
 *
 * @author Scott
 * @email
 * @date 2017-12-27 19:12:46
 */
@Service("productStoreRelaService")
public class ProductStoreRelaServiceImpl implements ProductStoreRelaService {
    @Autowired
    private ProductStoreRelaDao productStoreRelaDao;
    @Autowired
    private GoodsDao goodsDao;
    @Autowired
    private GoodsSpecificationDao goodsSpecificationDao;
    @Autowired
    private ProductDao productDao;
    @Autowired
    private GoodsGalleryDao goodsGalleryDao;
    @Autowired
    private CartDao cartDao;
    @Autowired
    private BrandDao brandDao;
    @Autowired
    private FreightDao freightDao;
    @Autowired
    private CategoryDao categoryDao;
    @Autowired
    private GoodsAttributeDao goodsAttributeDao;
    @Autowired
    private AttributeDao attributeDao;
    @Autowired
    private StoreMngChangeDao storeMngChangeDao;
    @Autowired
    private MkDistSellAllocationDao mkDistSellAllocationDao;
    @Autowired
    private StoreDao storeDao;
    @Autowired
    private MerchDao merchDao;
    @Autowired
    private ThirdMerchantBizDao thirdMerchantBizDao;
    @Autowired
    private MerchUserDao merchUserDao;
    @Autowired
    private ExportExceptionDataDao exportExceptionDataDao;

    @Override
    public ProductStoreRelaEntity queryObject(Integer id) {
        ProductStoreRelaEntity productStoreRelaEntity = productStoreRelaDao.queryObject(id);

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("storeId", productStoreRelaEntity.getStoreId());
        map.put("goodsId", productStoreRelaEntity.getGoodsId());
        List<GoodsAttributeEntity> attributeEntities = goodsAttributeDao.queryList(map);
        productStoreRelaEntity.setAttributeEntityList(attributeEntities);

        return productStoreRelaEntity;
    }

    @Override
    public ProductStoreRelaEntity queryObjectByStoreAndGoodsId(Map<String, Object> params){
        return productStoreRelaDao.queryObjectByStoreAndGoodsId(params);
    }

    @Override
    public ProductStoreRelaEntity queryByStoreIdProductId(Long storeId, Long productId) {
        return productStoreRelaDao.queryByStoreIdProductId(storeId, productId);
    }

    @Override
    public List<ProductStoreRelaEntity> queryList(Map<String, Object> map) {
        return productStoreRelaDao.queryList(map);
    }

    @Override
    public int queryTotal(Map<String, Object> map) {
        return productStoreRelaDao.queryTotal(map);
    }

    @Override
    public int save(ProductStoreRelaEntity productStoreRela) {
        GoodsEntity goodsEntity = null;
        String isStockShare = "";
        Map<String, Object> valideDate = MapBeanUtil.fromObject(productStoreRela);
        ImmutableBiMap.Builder builder = new ImmutableBiMap.Builder();
        builder.put("storeId", "门店");
        builder.put("goodsId", "商品");
        builder.put("attributeCategory", "一级分类");
        builder.put("categoryId", "二级分类");
        builder.put("brandId", "品牌");
        builder.put("freightId", "运费模版");

        R r = ValidatorUtil.isEmpty(builder.build(), valideDate);
        if (Integer.valueOf(r.get("code").toString()) != 0) {
            throw new RRException(r.get("msg").toString());
        } else {
            goodsEntity = goodsDao.queryObject(productStoreRela.getGoodsId());
            isStockShare = StockUtil.getIsStockShareByGoodsEntity(goodsEntity.getIsSupplierGoods(),
                    goodsEntity.getIsStockShare(), goodsEntity.getIsStockShare());
            if(goodsEntity.getGoodsBizType().equalsIgnoreCase(Dict.orderBizType.item_00.getItem())){
                if(isStockShare.equalsIgnoreCase(Dict.isStockShare.item_0.getItem())){
                    builder.put("stockNum", "库存");
                }
            }else{
                builder.put("stockNum", "库存");
            }

            if (Dict.orderBizType.item_11.getItem().equals(goodsEntity.getGoodsBizType())) {
                // 普通商品校验商品规格
                builder.put("specification", "规格");
            }
            builder.put("retailPrice", "零售价");
//            builder.put("marketPrice", "市场价");
            r = ValidatorUtil.isEmpty(builder.build(), valideDate);
            if (Integer.valueOf(r.get("code").toString()) != 0) {
                throw new RRException(r.get("msg").toString());
            }

            //商品配置校验
            if(!StringUtils.isNotEmpty(goodsEntity.getListPicUrl())){
                throw new RRException("该商品列表图不能为空！请先在商品管理》所有商品中维护商品编号为【"+goodsEntity.getGoodsSn()+"】的商品列表图信息，再来操作门店商品数据");
            }
            if(!StringUtils.isNotEmpty(goodsEntity.getPrimaryPicUrl())){
                throw new RRException("该商品主图不能为空！请先在商品管理》所有商品中维护商品编号为【"+goodsEntity.getGoodsSn()+"】的商品主图信息，再来操作门店商品数据");
            }
            List<GoodsGalleryEntity> galleryEntityList = goodsGalleryDao.queryObjectByGoodId(goodsEntity.getId());
            if (galleryEntityList == null || galleryEntityList.size() <= 0) {
                throw new RRException("该商品轮播图不能为空！请先在商品管理》所有商品中维护商品编号为【"+goodsEntity.getGoodsSn()+"】的商品详情轮播图信息，再来操作门店商品数据");
            }
        }
        if (productStoreRela.getStoreId() != null) {
            StoreEntity store = storeDao.queryObject(productStoreRela.getStoreId().intValue());
            if (store != null) {
                productStoreRela.setMerchSn(store.getMerchSn());
            }
        }
        if(!goodsEntity.getMerchSn().equalsIgnoreCase(productStoreRela.getMerchSn())) {
            throw new RRException("该商品所属商户不属于该门店所属商户！");
        }
        //校验总库存
        checkStockNum(productStoreRela, goodsEntity, isStockShare);

        String storeId = String.valueOf(productStoreRela.getStoreId());
        String goodsId = String.valueOf(goodsEntity.getId());
        Map<String, Object> map = Maps.newHashMap();
        map.put("goodsId", goodsId);
        map.put("storeId", storeId);
        List<ProductStoreRelaEntity> storeRelaList = querySameList(map);
        if (storeRelaList != null && storeRelaList.size() > 0) {
            throw new RRException("该门店已存在此商品！");
        }

        SysUserEntity user = ShiroUtils.getUserEntity();
        ProductEntity product = productDao.queryObjectByGoodsIdAndStoreId(goodsId, "");

        if (Dict.orderBizType.item_11.getItem().equals(goodsEntity.getGoodsBizType())) {
            GoodsSpecificationEntity goodsSpecificationEntity = goodsSpecificationDao.queryByGoodsId(goodsEntity.getId());
            if(goodsSpecificationEntity != null){
                goodsSpecificationDao.delete(goodsSpecificationEntity.getId());
            }
            // 添加商品规格
            GoodsSpecificationEntity goodsSpecification = new GoodsSpecificationEntity();
            goodsSpecification.setGoodsId(goodsEntity.getId());
            goodsSpecification.setValue(productStoreRela.getSpecification());
            goodsSpecification.setSpecificationId(1);
            goodsSpecificationDao.save(goodsSpecification);

            // 修改产品
            if(product == null){
                product = new ProductEntity();
                product.setGoodsSn(goodsEntity.getGoodsSn());
                product.setGoodsSpecificationNameValue(goodsSpecification.getValue());
                product.setGoodsSpecificationIds(goodsSpecification.getId().toString());
                product.setGoodsId(goodsEntity.getId());
                product.setGoodsNumber(goodsEntity.getGoodsNumber());
                product.setGoodsDefault(0);
                productDao.save(product);
            }else{
                product.setGoodsSpecificationIds(goodsSpecification.getId().toString());
                product.setGoodsSpecificationNameValue(goodsSpecification.getValue());
                productDao.update(product);
            }
        }

        // 添加商品参数
        List<GoodsAttributeEntity> attributeEntityList = productStoreRela.getAttributeEntityList();
        if (attributeEntityList != null && attributeEntityList.size() > 0) {
            for (GoodsAttributeEntity item : attributeEntityList) {
                if (item.getIsDelete() == 0) {
                    if (item.getId() == null && item.getAttributeId() != null && com.kmall.common.utils.StringUtils.isNotEmpty(item.getValue())) {
                        item.setStoreId(Integer.parseInt(String.valueOf(productStoreRela.getStoreId())));
                        item.setGoodsId(goodsEntity.getId());
                        item.setMerchSn(goodsEntity.getMerchSn());
                        goodsAttributeDao.save(item);
                    } else if (item.getId() == null && item.getAttributeId() != null && com.kmall.common.utils.StringUtils.isNullOrEmpty(item.getValue())) {
                        throw new RRException("商品属性【" + attributeDao.queryObject(item.getAttributeId()).getName() + "】值不能为空！");
                    } else if (item.getId() == null && item.getAttributeId() == null) {
                        continue;
                    }
                }
            }
        }

        //新增库存操作记录
        StoreMngChangeEntity storeMngChangeEntity = new StoreMngChangeEntity();
        storeMngChangeEntity.setChangeType(Dict.changeType.item_2.getItem());
        storeMngChangeEntity.setChangeReason("新增门店商品");
        storeMngChangeEntity.setGoodsId(Integer.parseInt(String.valueOf(productStoreRela.getGoodsId())));
        storeMngChangeEntity.setStoreId(Integer.parseInt(String.valueOf(productStoreRela.getStoreId())));
        storeMngChangeEntity.setMerchSn(productStoreRela.getMerchSn());
        storeMngChangeEntity.setCreateTime(new Date());
        storeMngChangeEntity.setModTime(new Date());
        storeMngChangeEntity.setStoreChangeNum(productStoreRela.getStockNum());
        storeMngChangeEntity.setStoreOriginalNum(0);
        storeMngChangeEntity.setStoreValidNum(productStoreRela.getStockNum());
        storeMngChangeEntity.setCreaterSn(user.getUsername());
        storeMngChangeEntity.setModerSn(user.getUsername());
        storeMngChangeEntity.setIsValid(0);
        storeMngChangeDao.save(storeMngChangeEntity);

        //更新门店商品是否有修改字段为是
        updateLoadGoodsByStoreId(storeId, user);

        productStoreRela.setAttributeCategory(categoryDao.queryObject(productStoreRela.getCategoryId()).getParentId());
        productStoreRela.setProductId(product.getId());
        productStoreRela.setGoodsBizType(goodsEntity.getGoodsBizType());
        productStoreRela.setSku(goodsEntity.getSku());
        productStoreRela.setCreaterSn(user.getUserId().toString());
        productStoreRela.setCreateTime(new Date());
        productStoreRela.setModerSn(user.getUserId().toString());
        productStoreRela.setModTime(new Date());
        productStoreRela.setGoodsBizType(goodsEntity.getGoodsBizType());
        return productStoreRelaDao.save(productStoreRela);
    }

    public List<ProductStoreRelaEntity> querySameList(Map<String, Object> map) {
        return productStoreRelaDao.querySameList(map);
    }

    @Override
    public int update(ProductStoreRelaEntity productStoreRela) {
        GoodsEntity goodsEntity = null;
        String isStockShare = "";
        Map<String, Object> valideDate = MapBeanUtil.fromObject(productStoreRela);
        ImmutableBiMap.Builder builder = new ImmutableBiMap.Builder();
        builder.put("storeId", "门店");
        builder.put("goodsId", "商品");
//        builder.put("stockNum", "库存");
        builder.put("attributeCategory", "一级分类");
        builder.put("categoryId", "二级分类");
        builder.put("brandId", "品牌");
        builder.put("freightId", "运费模版");

        R r = ValidatorUtil.isEmpty(builder.build(), valideDate);
        if (Integer.valueOf(r.get("code").toString()) != 0) {
            throw new RRException(r.get("msg").toString());
        } else {
            StoreEntity store = storeDao.queryObject(productStoreRela.getStoreId().intValue());
            if (store != null) {
                productStoreRela.setMerchSn(store.getMerchSn());
            }else{
                throw new RRException("门店信息不存在！");
            }
            goodsEntity = goodsDao.queryObjectByStoreId(productStoreRela.getGoodsId(), productStoreRela.getStoreId());
            isStockShare = StockUtil.getIsStockShareByGoodsEntity(goodsEntity.getIsSupplierGoods(),
                    goodsEntity.getIsStockShare(), goodsEntity.getIsStockShareBySuppler());
            if(Dict.orderBizType.item_00.getItem().equalsIgnoreCase(goodsEntity.getGoodsBizType())){
                if(Dict.isStockShare.item_0.getItem().equalsIgnoreCase(isStockShare)){
                    builder.put("stockNum", "库存");
                }
            }else{
                builder.put("stockNum", "库存");
            }
            if (Dict.orderBizType.item_11.getItem().equals(goodsEntity.getGoodsBizType())) {
                // 普通商品校验商品规格
                builder.put("specification", "规格");
            }
            builder.put("retailPrice", "零售价");
//            builder.put("marketPrice", "市场价");
            r = ValidatorUtil.isEmpty(builder.build(), valideDate);
            if (Integer.valueOf(r.get("code").toString()) != 0) {
                throw new RRException(r.get("msg").toString());
            }
        }

        if(!goodsEntity.getMerchSn().equalsIgnoreCase(productStoreRela.getMerchSn())) {
            throw new RRException("该商品所属商户不属于该门店所属商户！");
        }
        //校验总库存
        checkStockNum(productStoreRela, goodsEntity, isStockShare);

        String storeId = String.valueOf(productStoreRela.getStoreId());
        String goodsId = String.valueOf(goodsEntity.getId());
        Map<String, Object> map = Maps.newHashMap();
        map.put("goodsId", goodsId);
        map.put("storeId", storeId);
        map.put("id", productStoreRela.getId());
        List<ProductStoreRelaEntity> storeRelaList = querySameList(map);
        if (storeRelaList != null && storeRelaList.size() > 0) {
            throw new RRException("该门店已存在此商品！");
        }
        ProductStoreRelaEntity productStoreRelaEntity = productStoreRelaDao.queryObject(productStoreRela.getId());
        if(productStoreRelaEntity == null){
            throw new RRException("该门店商品信息不存在！");
        }
        BigDecimal retailPrice = productStoreRelaEntity.getRetailPrice();//修改前销售价
        BigDecimal nowRetailPrice = productStoreRela.getRetailPrice();//用户当前修改销售价
        if(nowRetailPrice.doubleValue() < retailPrice.doubleValue()){//当前修改销售价格低于修改前价格，则判断查询分销分配金额总数是否低于销售价
            Map<String, Object> queryDistMap = new HashMap();
            queryDistMap.put("storeId", productStoreRela.getStoreId());
            queryDistMap.put("goodsId", productStoreRela.getGoodsId());
            List<MkDistSellAllocationEntity> allocationEntities = mkDistSellAllocationDao.queryAllocationByMap(queryDistMap);
            for (MkDistSellAllocationEntity allocationEntity: allocationEntities) {
                String expendDistLines = allocationEntity.getExpendDistLines();
                String[] distLiness = expendDistLines.split(",");
                BigDecimal totalPrice = new BigDecimal(0); //支出分销商额度相加总额
                for(int i = 0 ; i < distLiness.length; i++){
                    totalPrice = totalPrice.add(BigDecimal.valueOf(Double.parseDouble(distLiness[i])));
                }
                if(allocationEntity.getAllocType().equalsIgnoreCase(Dict.allocType.item_10.getItem())){
                    if(nowRetailPrice.doubleValue() < totalPrice.doubleValue()){
                        throw new RRException("修改商品价格失败，当前修改销售价不能低于渠道销售分配规则中子级分销商分配额度总额，" +
                                "子级分销商分配额度规则为【"+ allocationEntity.getExpendDistLines() +
                                "】，需重新修改渠道销售分配功能的子级分销商分配额度规则信息，详情请看营销平台--》渠道销售分配功能");
                    }
                }
            }
        }

        SysUserEntity user = ShiroUtils.getUserEntity();
//        GoodsEntity goods = new GoodsEntity();
//        goods.setRetailPrice(productStoreRela.getRetailPrice());
//        goods.setMarketPrice(productStoreRela.getMarketPrice());
//        goods.setId(goodsEntity.getId());
//        goodsDao.update(goods);
        ProductEntity product = productDao.queryObjectByGoodsIdAndStoreId(goodsId, storeId);
        if(product == null){
            throw new RRException("该商品规格信息为空！请完善商品数据");
        }
        productStoreRela.setProductId(product.getId());
        if (Dict.orderBizType.item_11.getItem().equals(goodsEntity.getGoodsBizType())) {
            // 添加商品规格
            GoodsSpecificationEntity goodsSpecification = goodsSpecificationDao.queryByGoodsId(goodsEntity.getId());
            goodsSpecification.setValue(productStoreRela.getSpecification());
            goodsSpecificationDao.update(goodsSpecification);

            // 修改产品
            product.setGoodsSpecificationIds(goodsSpecification.getId().toString());
            product.setGoodsSpecificationNameValue(goodsSpecification.getValue());
            productDao.update(product);
        }

        // 修改商品参数
        List<GoodsAttributeEntity> attributeEntityList = productStoreRela.getAttributeEntityList();
        if (attributeEntityList != null && attributeEntityList.size() > 0) {
            for (GoodsAttributeEntity item : attributeEntityList) {
                if (item.getIsDelete() == 0) {
                    if (item.getId() != null) {
                        item.setMerchSn(goodsEntity.getMerchSn());
                        item.setStoreId(Integer.parseInt(String.valueOf(productStoreRela.getStoreId())));
                        goodsAttributeDao.update(item);
                    } else if (item.getId() == null && item.getAttributeId() != null && com.kmall.common.utils.StringUtils.isNotEmpty(item.getValue())) {
                        item.setMerchSn(goodsEntity.getMerchSn());
                        item.setGoodsId(goodsEntity.getId());
                        item.setStoreId(Integer.parseInt(String.valueOf(productStoreRela.getStoreId())));
                        goodsAttributeDao.save(item);
                    } else if (item.getId() == null && item.getAttributeId() != null && com.kmall.common.utils.StringUtils.isNullOrEmpty(item.getValue())) {
                        throw new RRException("商品属性【" + attributeDao.queryObject(item.getAttributeId()).getName() + "】值不能为空！");
                    } else if (item.getId() == null && item.getAttributeId() == null) {
                        continue;
                    }
                } else if (item.getIsDelete() == 1) {
                    goodsAttributeDao.delete(item.getId());
                }
            }
        }
        if(productStoreRela.getMarketPrice()==null){
            productStoreRela.setMarketPrice(Constant.ZERO);
        }
        Map cartMap = Maps.newHashMap();
        cartMap.put("goodsId",goodsEntity.getId());
        List<CartEntity> cartList = cartDao.queryList(cartMap);
        if (cartList != null && cartList.size() > 0) {
            for (CartEntity cartEntity : cartList) {
                cartEntity.setMarketPrice(productStoreRela.getMarketPrice());
                cartEntity.setRetailPrice(productStoreRela.getRetailPrice());
                cartEntity.setStockNum(productStoreRela.getStockNum());
                cartEntity.setSku(goodsEntity.getSku());
                cartEntity.setGoodsName(goodsEntity.getName());
                cartEntity.setGoodsSn(goodsEntity.getGoodsSn());
                cartDao.update(cartEntity);
            }
        }
        StoreMngChangeEntity storeMngChangeEntity = new StoreMngChangeEntity();
        storeMngChangeEntity.setChangeType(Dict.changeType.item_3.getItem());
        storeMngChangeEntity.setChangeReason("更新门店商品库存");
        storeMngChangeEntity.setGoodsId(Integer.parseInt(String.valueOf(productStoreRela.getGoodsId())));
        storeMngChangeEntity.setStoreId(Integer.parseInt(String.valueOf(productStoreRela.getStoreId())));
        storeMngChangeEntity.setMerchSn(productStoreRela.getMerchSn());
        storeMngChangeEntity.setCreateTime(new Date());
        storeMngChangeEntity.setModTime(new Date());
        storeMngChangeEntity.setCreaterSn(user.getUsername());
        storeMngChangeEntity.setModerSn(user.getUsername());

        Integer orginalNum = productStoreRelaEntity.getStockNum()==null?0:productStoreRelaEntity.getStockNum();//原有库存
        Integer changeNum = productStoreRela.getStockNum()==null ? 0 : productStoreRela.getStockNum();//前端变化库存
        if(changeNum != orginalNum) {
            if (orginalNum > changeNum) {
                storeMngChangeEntity.setStoreChangeNum(orginalNum - changeNum);//变化数
                storeMngChangeEntity.setChangeType(Dict.changeType.item_4.getItem());
            } else {
                storeMngChangeEntity.setStoreChangeNum(changeNum - orginalNum);//变化数
                storeMngChangeEntity.setChangeType(Dict.changeType.item_3.getItem());
            }
            storeMngChangeEntity.setStoreOriginalNum(orginalNum);//原库存数
            storeMngChangeEntity.setStoreValidNum(changeNum);//可用数
            storeMngChangeDao.save(storeMngChangeEntity);
        }
        //更新门店商品是否有修改字段
        updateLoadGoodsByStoreId(storeId, user);

        productStoreRela.setAttributeCategory(categoryDao.queryObject(productStoreRela.getCategoryId()).getParentId());
        productStoreRela.setModerSn(user.getUserId().toString());
        productStoreRela.setModTime(new Date());
        productStoreRela.setGoodsBizType(goodsEntity.getGoodsBizType());
        return productStoreRelaDao.update(productStoreRela);
    }

    /**
     * 更新门店商品是否有修改字段
     * @param storeId
     * @param user
     */
    private void updateLoadGoodsByStoreId(String storeId, SysUserEntity user){
        List<MerchUserEntity> list = merchUserDao.queryMerchUserByLoadGoods(Long.valueOf(storeId));
        for(MerchUserEntity entity : list) {
            entity.setIsLoadGoods("1");
            entity.setStoreId(Integer.valueOf(String.valueOf(storeId)));
            entity.setModerSn(user.getUsername());
            merchUserDao.updateStoreLoadGoodsById(entity);
        }
    }

    /**
     * 校验总库存
     * @param productStoreRela
     * @param goodsEntity
     * @param isStockShare
     */
    private void checkStockNum(ProductStoreRelaEntity productStoreRela, GoodsEntity goodsEntity, String isStockShare){
        if(goodsEntity.getGoodsBizType().equalsIgnoreCase(Dict.orderBizType.item_00.getItem()) && isStockShare.equalsIgnoreCase(Dict.isStockShare.item_1.getItem())){
            Integer stockNum = productStoreRela.getStockNum();
            Integer goodsNumber = goodsEntity.getGoodsNumber();//商品总库存
            if (stockNum.intValue() != goodsNumber.intValue()) {
                throw new RRException("当前门店商品分配库存不等于商品总库存！当前门店属于共享库存，需与总库存一致，该商品总库存【" + goodsNumber + "】");
            } else {
                productStoreRela.setStockNum(goodsEntity.getGoodsNumber());
            }
        }
        if((!goodsEntity.getGoodsBizType().equalsIgnoreCase(Dict.orderBizType.item_00.getItem()) && isStockShare.equalsIgnoreCase(Dict.isStockShare.item_1.getItem())) ||
                isStockShare.equalsIgnoreCase(Dict.isStockShare.item_0.getItem())){
            Integer stockNum = productStoreRela.getStockNum();
            Integer goodsNumber = goodsEntity.getGoodsNumber();//商品总库存
            Integer storeTotalStockNum = 0;//商品分配库存
            List<ProductStoreRelaEntity> proStoreList = productStoreRelaDao.queryByGoodsId(goodsEntity.getId());
            for(ProductStoreRelaEntity relaEntity: proStoreList){
                if(relaEntity.getStoreId().intValue() != productStoreRela.getStoreId().intValue()) {
                    storeTotalStockNum = storeTotalStockNum + relaEntity.getStockNum();
                }
            }
            Integer totalStockNum = storeTotalStockNum + stockNum;
            if(goodsNumber < totalStockNum){
                throw new RRException("当前门店商品分配库存已超过商品总库存！当前门店商品分配库存【" + stockNum + "】，已在各门店分配库存总额【"+
                        storeTotalStockNum + "】，该商品总库存【" + goodsNumber + "】");
            }
        }
    }

    @Override
    public int delete(Integer id) {
        return productStoreRelaDao.delete(id);
    }

    @Override
    public int deleteBatch(Integer[] ids) {
        return productStoreRelaDao.deleteBatch(ids);
    }


    @Override
    public List<ProductStoreRelaEntity> queryGoodsRealListByDiscountTid(Map<String, Object> map) {
        return productStoreRelaDao.queryGoodsRealListByDiscountTid(map);
    }

    @Override
    public int queryGoodsRealListByDiscountTidTotal(Map<String, Object> map) {
        return productStoreRelaDao.queryGoodsRealListByDiscountTidTotal(map);
    }

    @Override
    public List<ProductStoreRelaEntity> queryGoodsRealListByTopicId(Map<String, Object> map) {
        return productStoreRelaDao.queryGoodsRealListByTopicId(map);
    }

    @Override
    public int queryGoodsRealListByTopicIdTotal(Map<String, Object> map) {
        return productStoreRelaDao.queryGoodsRealListByTopicIdTotal(map);
    }

    @Override
    public int uploadExcel(List<StoreGoodsDto> storeGoodsDtoList){
        GoodsEntity goodsEntity = null;
        String isStockShare = "";
        SysUserEntity user = ShiroUtils.getUserEntity();
        String merchSn = user.getMerchSn();
        boolean isFail = false;
        List<String> failThirdMerchSnList = new ArrayList<>(),
                failGoodsSnList = new ArrayList<>(), failHaveNameList = new ArrayList<>(), failHaveGoodsSnList = new ArrayList<>()
                , failParentCateList = new ArrayList<>(), failCateList = new ArrayList<>(), failHaveStoreNameList = new ArrayList<>()
                , failBrandList = new ArrayList<>(), failFreightList = new ArrayList<>();
        if (storeGoodsDtoList != null && storeGoodsDtoList.size() > 0) {
            for (int i = 0; i < storeGoodsDtoList.size(); i++) {
                StoreGoodsDto storeGoodsDto = storeGoodsDtoList.get(i);
                ProductStoreRelaEntity storeRelaEntity = new ProductStoreRelaEntity();
                Map<String, Object> valideDate = MapBeanUtil.fromObject(storeGoodsDto);
                ImmutableBiMap.Builder builder = new ImmutableBiMap.Builder();
                builder.put("storeName", "门店名称");
                builder.put("goodsSn", "商品编码");
                builder.put("categoryName", "一级分类");
                builder.put("attributeCategory", "二级分类");
                builder.put("brandName", "品牌");
                builder.put("freightName", "运费");

                R r = ValidatorUtil.isEmpty(builder.build(), valideDate);
                if (Integer.valueOf(r.get("code").toString()) != 0) {
                    throw new RRException(r.get("msg").toString());
                }
                StoreEntity store = storeDao.queryObjectByName(storeGoodsDto.getStoreName().trim());
                if (store != null) {
                    storeRelaEntity.setStoreId(store.getId());
                    storeRelaEntity.setMerchSn(store.getMerchSn());
                    MerchEntity merchEntity = merchDao.findByMerchSn(store.getMerchSn());
                    if(merchEntity != null){
                        storeRelaEntity.setMerchName(merchEntity.getMerchName());
                    }
                    goodsEntity = goodsDao.queryGoodsByGoodsSnAndStoreId(storeGoodsDto.getGoodsSn(), store.getId());
                    if(goodsEntity == null){//商品不存在
                        isFail = true;
                        failGoodsSnList.add(storeGoodsDto.getStoreName());
                    }else {
                        storeRelaEntity.setSku(goodsEntity.getSku());
                        storeRelaEntity.setGoodsId(goodsEntity.getId());
                        storeRelaEntity.setGoodsBizType(goodsEntity.getGoodsBizType());
                        isStockShare = StockUtil.getIsStockShareByGoodsEntity(goodsEntity.getIsSupplierGoods(),
                                goodsEntity.getIsStockShare(), goodsEntity.getIsStockShareBySuppler());

                        if(goodsEntity.getIsSupplierGoods().equalsIgnoreCase(Dict.isSupplierGoods.item_1.getItem())) {
                            builder.put("supplierThirdName", "商品供货商所属第三方商户");
                        }
                        if(Dict.orderBizType.item_00.getItem().equalsIgnoreCase(goodsEntity.getGoodsBizType())){
                            if(Dict.isStockShare.item_0.getItem().equalsIgnoreCase(isStockShare)){
                                builder.put("stockNum", "库存");
                            }
                        }else{
                            builder.put("stockNum", "库存");
                        }
                        if (Dict.orderBizType.item_11.getItem().equals(goodsEntity.getGoodsBizType())) {
                            // 普通商品校验商品规格
                            builder.put("specification", "产品规格");
                        }
                        builder.put("retailPrice", "零售价");
                        builder.put("marketPrice", "市场价");
                        r = ValidatorUtil.isEmpty(builder.build(), valideDate);
                        if (Integer.valueOf(r.get("code").toString()) != 0) {
                            throw new RRException(r.get("msg").toString());
                        }
                        //商品配置校验
                        if(!StringUtils.isNotEmpty(goodsEntity.getListPicUrl())){
                            throw new RRException("该商品列表图不能为空！请先在商品管理》所有商品中维护商品编号为【"+goodsEntity.getGoodsSn()+"】的商品列表图信息，再来操作门店商品数据");
                        }
                        if(!StringUtils.isNotEmpty(goodsEntity.getPrimaryPicUrl())){
                            throw new RRException("该商品主图不能为空！请先在商品管理》所有商品中维护商品编号为【"+goodsEntity.getGoodsSn()+"】的商品主图信息，再来操作门店商品数据");
                        }
                        List<GoodsGalleryEntity> galleryEntityList = goodsGalleryDao.queryObjectByGoodId(goodsEntity.getId());
                        if (galleryEntityList == null || galleryEntityList.size() <= 0) {
                            throw new RRException("该商品轮播图不能为空！请先在商品管理》所有商品中维护商品编号为【"+goodsEntity.getGoodsSn()+"】的商品详情轮播图信息，再来操作门店商品数据");
                        }

                        if(goodsEntity.getIsSupplierGoods().equalsIgnoreCase(Dict.isSupplierGoods.item_1.getItem())) {
                            builder.put("supplierThirdCode", "商品供货商所属第三方商户");
                            ThirdMerchantBizEntity thirdMerchantBizEntity = thirdMerchantBizDao.getThirdMerchangByCode(storeGoodsDto.getSupplierThirdCode());
                            if(thirdMerchantBizEntity != null){
                                storeRelaEntity.setThirdPartyMerchCode(thirdMerchantBizEntity.getThirdPartyMerchCode());
                                storeRelaEntity.setSupplierThirdId(thirdMerchantBizEntity.getThirdMerchSn());
                            }else{//第三方商户不存在
                                isFail = true;
                                failThirdMerchSnList.add(storeGoodsDto.getStoreName());
                            }
                        }
                        CategoryEntity parentCategoryEntity = categoryDao.queryObjectByName(storeGoodsDto.getAttributeCategory(), store.getMerchSn());
                        if(parentCategoryEntity == null){
                            isFail = true;
                            failParentCateList.add(storeGoodsDto.getStoreName());
                        }else {
                            storeRelaEntity.setAttributeCategory(parentCategoryEntity.getParentId());
                        }
                        CategoryEntity categoryEntity = categoryDao.queryObjectByName(storeGoodsDto.getCategoryName(), store.getMerchSn());
                        if(categoryEntity == null){
                            isFail = true;
                            failCateList.add(storeGoodsDto.getStoreName());
                        }else {
                            storeRelaEntity.setCategoryId(categoryEntity.getId());
                        }
                        BrandEntity brandEntity = brandDao.queryBrandByBrandNameAndStoreId(storeGoodsDto.getBrandName(), store.getId());
                        if(brandEntity == null){
                            isFail = true;
                            failBrandList.add(storeGoodsDto.getStoreName());
                        }else {
                            storeRelaEntity.setBrandId(brandEntity.getId());
                        }
                        FreightEntity freightEntity = freightDao.queryFreightByDefaultFreightAndStoreId(storeGoodsDto.getBrandName(), store.getId());
                        if(freightEntity == null){
                            isFail = true;
                            failFreightList.add(storeGoodsDto.getStoreName());
                        }else {
                            storeRelaEntity.setFreightId(freightEntity.getId());
                        }

                        //校验总库存
                        if(goodsEntity.getGoodsBizType().equalsIgnoreCase(Dict.orderBizType.item_00.getItem()) && isStockShare.equalsIgnoreCase(Dict.isStockShare.item_1.getItem())){
                            Integer stockNum = Integer.parseInt(storeGoodsDto.getStockNum());
                            Integer goodsNumber = goodsEntity.getGoodsNumber();//商品总库存
                            if (stockNum.intValue() != goodsNumber.intValue()) {
                                throw new RRException("门店【" + store.getStoreName() + "】商品编码【" + storeGoodsDto.getGoodsSn()
                                        + "】的门店商品分配库存不等于商品总库存！当前门店属于共享库存，需与总库存一致，该商品总库存【" + goodsNumber + "】");
                            } else {
                                storeRelaEntity.setStockNum(goodsEntity.getGoodsNumber());
                            }
                        }
                        if((!goodsEntity.getGoodsBizType().equalsIgnoreCase(Dict.orderBizType.item_00.getItem()) && isStockShare.equalsIgnoreCase(Dict.isStockShare.item_1.getItem())) ||
                                isStockShare.equalsIgnoreCase(Dict.isStockShare.item_0.getItem())){
                            Integer stockNum = Integer.parseInt(storeGoodsDto.getStockNum());
                            Integer goodsNumber = goodsEntity.getGoodsNumber();//商品总库存
                            Integer storeTotalStockNum = 0;//商品分配库存
                            List<ProductStoreRelaEntity> proStoreList = productStoreRelaDao.queryByGoodsId(goodsEntity.getId());
                            for(ProductStoreRelaEntity relaEntity: proStoreList){
                                if(relaEntity.getStoreId().intValue() != store.getId().intValue()) {
                                    storeTotalStockNum = storeTotalStockNum + relaEntity.getStockNum();
                                }
                            }
                            Integer totalStockNum = storeTotalStockNum + stockNum;
                            if(goodsNumber < totalStockNum){
                                throw new RRException("门店【" + store.getStoreName() + "】商品编码【" + storeGoodsDto.getGoodsSn()
                                        + "】的门店商品分配库存已超过商品总库存！当前门店商品分配库存【" + stockNum + "】，已在各门店分配库存总额【"+
                                        storeTotalStockNum + "】，该商品总库存【" + goodsNumber + "】");
                            }
                        }

                        String storeId = String.valueOf(store.getId());
                        String goodsId = String.valueOf(goodsEntity.getId());
                        Map<String, Object> map = Maps.newHashMap();
                        map.put("goodsId", goodsId);
                        map.put("storeId", storeId);
                        List<ProductStoreRelaEntity> storeRelaList = querySameList(map);
                        if (storeRelaList != null && storeRelaList.size() > 0) {
//                        throw new RRException("该门店已存在此商品！");
                            isFail = true;
                            failHaveNameList.add(storeGoodsDto.getStoreName());
                            failHaveGoodsSnList.add(storeGoodsDto.getGoodsSn());
                        }

                        ProductEntity product = productDao.queryObjectByGoodsIdAndStoreId(goodsId, "");
                        if (Dict.orderBizType.item_11.getItem().equals(goodsEntity.getGoodsBizType())) {
                            GoodsSpecificationEntity goodsSpecificationEntity = goodsSpecificationDao.queryByGoodsId(goodsEntity.getId());
                            if(goodsSpecificationEntity != null){
                                goodsSpecificationDao.delete(goodsSpecificationEntity.getId());
                            }
                            // 添加商品规格
                            GoodsSpecificationEntity goodsSpecification = new GoodsSpecificationEntity();
                            goodsSpecification.setGoodsId(goodsEntity.getId());
                            goodsSpecification.setValue(storeGoodsDto.getSpecification());
                            goodsSpecification.setSpecificationId(1);
                            goodsSpecificationDao.save(goodsSpecification);

                            // 修改产品
                            if(product == null){
                                product = new ProductEntity();
                                product.setGoodsSn(goodsEntity.getGoodsSn());
                                product.setGoodsSpecificationNameValue(goodsSpecification.getValue());
                                product.setGoodsSpecificationIds(goodsSpecification.getId().toString());
                                product.setGoodsId(goodsEntity.getId());
                                product.setGoodsNumber(goodsEntity.getGoodsNumber());
                                product.setGoodsDefault(0);
                                productDao.save(product);
                            }else{
                                product.setGoodsSpecificationIds(goodsSpecification.getId().toString());
                                product.setGoodsSpecificationNameValue(goodsSpecification.getValue());
                                productDao.update(product);
                            }
                        }

                        // 批量导入不添加商品参数
                        //新增库存操作记录
                        StoreMngChangeEntity storeMngChangeEntity = new StoreMngChangeEntity();
                        storeMngChangeEntity.setChangeType(Dict.changeType.item_2.getItem());
                        storeMngChangeEntity.setChangeReason("新增门店商品");
                        storeMngChangeEntity.setGoodsId(Integer.parseInt(String.valueOf(goodsEntity.getId())));
                        storeMngChangeEntity.setStoreId(Integer.parseInt(String.valueOf(store.getId())));
                        storeMngChangeEntity.setMerchSn(store.getMerchSn());
                        storeMngChangeEntity.setCreateTime(new Date());
                        storeMngChangeEntity.setModTime(new Date());
                        storeMngChangeEntity.setStoreChangeNum(Integer.parseInt(storeGoodsDto.getStockNum()));
                        storeMngChangeEntity.setStoreOriginalNum(0);
                        storeMngChangeEntity.setStoreValidNum(Integer.parseInt(storeGoodsDto.getStockNum()));
                        storeMngChangeEntity.setCreaterSn(user.getUsername());
                        storeMngChangeEntity.setModerSn(user.getUsername());
                        storeMngChangeEntity.setIsValid(0);
                        storeMngChangeDao.save(storeMngChangeEntity);

                        //更新门店商品是否有修改字段
                        updateLoadGoodsByStoreId(storeId, user);

                        storeRelaEntity.setProductId(product.getId());
//                    storeRelaEntity.setGoodsBizType(goodsEntity.getGoodsBizType());
//                    storeRelaEntity.setSku(goodsEntity.getSku());
                        storeRelaEntity.setRetailPrice(BigDecimal.valueOf(Long.valueOf(storeGoodsDto.getRetailPrice())));
                        storeRelaEntity.setMarketPrice(BigDecimal.valueOf(Long.valueOf(storeGoodsDto.getMarketPrice())));
                        storeRelaEntity.setCreaterSn(user.getUserId().toString());
                        storeRelaEntity.setCreateTime(new Date());
                        storeRelaEntity.setModerSn(user.getUserId().toString());
                        storeRelaEntity.setModTime(new Date());
                    }
                }else{
                    isFail = true;
                    failHaveStoreNameList.add(storeGoodsDto.getStoreName());
                }

                if(!isFail){
                    productStoreRelaDao.save(storeRelaEntity);
                }

                ExportExceptionDataEntity exportExceptionDataEntity = new ExportExceptionDataEntity();
                exportExceptionDataEntity.setCreaterSn(user.getUserId().toString());
                exportExceptionDataEntity.setUserId(user.getUserId().intValue());
                exportExceptionDataEntity.setCreateTime(new Date());
                exportExceptionDataEntity.setModTime(new Date());
                exportExceptionDataEntity.setMerchSn(merchSn);
                exportExceptionDataEntity.setStoreId(user.getStoreId());
                exportExceptionDataEntity.setExportDataType(Dict.exportDataType.item_3.getItem());

                if(failHaveStoreNameList != null && failHaveStoreNameList.size() > 0){
                    exportExceptionDataEntity.setExportExceptionData("门店名称不存在，请检查门店名称【"+failHaveStoreNameList+"】的门店名称信息！");
                    exportExceptionDataDao.save(exportExceptionDataEntity);
                    throw new RRException("导入数据异常，异常信息请在商品管理》》导入异常数据中查看检查");
                }
                if(failThirdMerchSnList != null && failThirdMerchSnList.size() > 0){
                    exportExceptionDataEntity.setExportExceptionData("第三方商户代码不存在，请在商城配置》第三方商户管理中维护，请检查门店名称【"+failThirdMerchSnList+"】的第三方商户代码信息，请先维护再继续操作！");
                    exportExceptionDataDao.save(exportExceptionDataEntity);
                    throw new RRException("导入数据异常，异常信息请在商品管理》》导入异常数据中查看检查");
                }
                if(failHaveNameList != null && failHaveNameList.size() > 0){
                    exportExceptionDataEntity.setExportExceptionData("门店商品已存在！请检查门店名称【" + failHaveNameList + "】商品编码【" + failHaveGoodsSnList + "】的门店商品信息");
                    exportExceptionDataDao.save(exportExceptionDataEntity);
                    throw new RRException("导入数据异常，异常信息请在商品管理》》导入异常数据中查看检查");
                }
                if(failGoodsSnList != null && failGoodsSnList.size() > 0){
                    exportExceptionDataEntity.setExportExceptionData("商户编码不存在，请检查门店名称【"+failGoodsSnList+"】的商户编码信息，请先维护再继续操作！");
                    exportExceptionDataDao.save(exportExceptionDataEntity);
                    throw new RRException("导入数据异常，异常信息请在商品管理》》导入异常数据中查看检查");
                }
                if(failParentCateList != null && failParentCateList.size() > 0){
                    exportExceptionDataEntity.setExportExceptionData("一级分类不存在，请检查门店名称【"+failParentCateList+"】的一级分类信息，请先维护再继续操作！");
                    exportExceptionDataDao.save(exportExceptionDataEntity);
                    throw new RRException("导入数据异常，异常信息请在商品管理》》导入异常数据中查看检查");
                }
                if(failCateList != null && failCateList.size() > 0){
                    exportExceptionDataEntity.setExportExceptionData("二级分类不存在，请检查门店名称【"+failCateList+"】的二级分类信息，请先维护再继续操作！");
                    exportExceptionDataDao.save(exportExceptionDataEntity);
                    throw new RRException("导入数据异常，异常信息请在商品管理》》导入异常数据中查看检查");
                }
                if(failBrandList != null && failBrandList.size() > 0){
                    exportExceptionDataEntity.setExportExceptionData("品牌不存在，请检查门店名称【"+failBrandList+"】的品牌信息，请先维护再继续操作！");
                    exportExceptionDataDao.save(exportExceptionDataEntity);
                    throw new RRException("导入数据异常，异常信息请在商品管理》》导入异常数据中查看检查");
                }
                if(failFreightList != null && failFreightList.size() > 0){
                    exportExceptionDataEntity.setExportExceptionData("运费模板不存在，请检查门店名称【"+failFreightList+"】的运费模板信息，请先维护再继续操作！");
                    exportExceptionDataDao.save(exportExceptionDataEntity);
                    throw new RRException("导入数据异常，异常信息请在商品管理》》导入异常数据中查看检查");
                }
            }
        }else{
            throw new RRException("导入数据为空，或者检查数据是否为空");
        }
        throw new RRException("导入成功！");
//        return 1;
    }
}
