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.MkDistSellAllocationDao;
import com.kmall.admin.entity.*;
import com.kmall.admin.entity.mk.MkDistSellAllocationEntity;
import com.kmall.admin.service.ProductStoreRelaService;
import com.kmall.admin.service.mk.MkDistSellAllocationService;
import com.kmall.admin.utils.ShiroUtils;
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.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 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;

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

        Map<String, Object> map = new HashMap<String, Object>();
        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;
        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());
            if(Dict.orderBizType.item_00.getItem().equalsIgnoreCase(goodsEntity.getGoodsBizType())){
                if(Dict.isStockShare.item_0.getItem().equalsIgnoreCase(goodsEntity.getIsStockShare())){
                    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.getMerchSn().equalsIgnoreCase(productStoreRela.getMerchSn())) {
            throw new RRException("该商品所属商户不属于该门店所属商户！");
        }
        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, "");

//        GoodsEntity goods = new GoodsEntity();
//        goods.setRetailPrice(productStoreRela.getRetailPrice());
//        goods.setMarketPrice(productStoreRela.getMarketPrice());
//        goods.setId(goodsEntity.getId());
//        goodsDao.update(goods);

        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);
            }
        }/* else {
            productStoreRela.setRetailPrice(goodsEntity.getRetailPrice());
            productStoreRela.setMarketPrice(goodsEntity.getMarketPrice());
        }*/

        // 添加商品参数
        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.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);

        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;
        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 {
            goodsEntity = goodsDao.queryObject(productStoreRela.getGoodsId());
            if(Dict.orderBizType.item_00.getItem().equalsIgnoreCase(goodsEntity.getGoodsBizType())){
                if(Dict.isStockShare.item_0.getItem().equalsIgnoreCase(goodsEntity.getIsStockShare())){
                    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("该商品所属商户不属于该门店所属商户！");
        }

        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());
                        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());
                        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());
                }
            }
        }
        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();//原有库存
        Integer changeNum = 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);
        }

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

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

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