package com.kmall.admin.service.impl.mk.dist;

import com.kmall.admin.dao.GoodsDao;
import com.kmall.admin.dao.ProductStoreRelaDao;
import com.kmall.admin.dao.StoreDao;
import com.kmall.admin.dao.mk.dist.*;
import com.kmall.admin.dto.ExpendDistDto;
import com.kmall.admin.entity.GoodsEntity;
import com.kmall.admin.entity.ProductStoreRelaEntity;
import com.kmall.admin.entity.StoreEntity;
import com.kmall.admin.entity.mk.dist.*;
import com.kmall.admin.service.mk.dist.MkDistSellAllocationService;
import com.kmall.admin.utils.ShiroUtils;
import com.kmall.common.constant.Dict;
import com.kmall.common.utils.RRException;
import com.kmall.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * 渠道销售分配，分销商针对某个商品sku的销售分配Service实现类
 *
 * @author huangyq
 * @email admin@qhdswl.com
 * @date 2019-04-09 18:04:46
 */
@Service("mkDistSellAllocationService")
public class MkDistSellAllocationServiceImpl implements MkDistSellAllocationService {
    @Autowired
    private MkDistSellAllocationDao mkDistSellAllocationDao;
    @Autowired
    private MkDistHierDao mkDistHierDao;
    @Autowired
    private MkDistChnlDao mkDistChnlDao;
    @Autowired
    private MkDistDao mkDistDao;

    @Autowired
    private StoreDao storeDao;
    @Autowired
    private GoodsDao goodsDao;
    @Autowired
    private ProductStoreRelaDao productStoreRelaDao;
    @Autowired
    private MkDistSellAllocationHistoryDao mkDistSellAllocationHistoryDao;
    @Autowired
    private MkDistSellStatisDao mkDistSellStatisDao;

    @Override
    public MkDistSellAllocationEntity queryObject(Integer sellAllocId) {
        return mkDistSellAllocationDao.queryObject(sellAllocId);
    }
    @Override
    public List<MkDistSellAllocationEntity> queryAllocationByMap(Map<String, Object> map) {
        return mkDistSellAllocationDao.queryAllocationByMap(map);
    }

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

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

    @Override
    public int save(MkDistSellAllocationEntity mkDistSellAllocation) {
        /*List<Integer> expendDistIdList = mkDistSellAllocation.getExpendDistIdList();
        if(expendDistIdList == null || expendDistIdList.size() == 0) {
            throw new RRException("支出分销商不能为空");
        }
        String expendDistLines = mkDistSellAllocation.getExpendDistLines();
        String[] distLiness = expendDistLines.split(",");
        if(expendDistList.size() != distLiness.length){
            throw new RRException("支出分销商额度对应个数错误，个数为"+distLiness.length+"，个数需与支出分销商一致，且对应排序！示例：比例1,比例2,比例3...");
        }*/
        List<ExpendDistDto> expendDistList = mkDistSellAllocation.getExpendDistDtoList();
        if(expendDistList == null || expendDistList.size() == 0) {
            throw new RRException("分销额度分配信息不能为空");
        }
        StoreEntity storeEntity = storeDao.queryObject(mkDistSellAllocation.getStoreId());
        if(storeEntity == null){
            throw new RRException("门店id不存在");
        }
        GoodsEntity goodsEntity = goodsDao.queryObject(mkDistSellAllocation.getGoodsId());
        if(goodsEntity == null){
            throw new RRException("商品id不存在");
        }
        MkDistEntity mkDistEntity = mkDistDao.queryObject(mkDistSellAllocation.getDistId());
        if(mkDistEntity == null){
            throw new RRException("商品所属分销商id不存在");
        }
        MkDistHierEntity mkDistHierEntities =  mkDistHierDao.selectDistHierByDistId(mkDistSellAllocation.getDistId());
        if(mkDistHierEntities == null){
            throw new RRException("当前所选的商户所属分销商【"+ mkDistEntity.getDistName() +"】没有层级关系信息，请重新选择");
        }
        MkDistChnlEntity chnlEntity = mkDistChnlDao.queryObject(mkDistHierEntities.getDistChnlId());
        if(chnlEntity == null){
            throw new RRException("分销渠道id不存在");
        }
        Map<String, Object> allocationMap = new HashMap<>();
        allocationMap.put("distId", mkDistSellAllocation.getDistId());
        allocationMap.put("distChnlId", mkDistSellAllocation.getDistChnlId());
        allocationMap.put("goodsId", mkDistSellAllocation.getGoodsId());
        allocationMap.put("storeId", mkDistSellAllocation.getStoreId());
        List<MkDistSellAllocationEntity> allocationEntityList =  mkDistSellAllocationDao.queryAllocationByMap(allocationMap);
        if(allocationEntityList.size() > 0){
            throw new RRException("门店【"+storeEntity.getStoreName()+"】商品【"+ goodsEntity.getName() +
                    "】商户所属分销商【"+ mkDistEntity.getDistName() +"】，已存在渠道销售分配信息！请选择其他商品");
        }
        StringBuffer expendDistLines = new StringBuffer();
        StringBuffer expendDistIds = new StringBuffer();
        for (ExpendDistDto distDto: expendDistList) {
            expendDistLines = expendDistLines.append(distDto.getExpendDistLine() + ",");
            expendDistIds = expendDistIds.append(distDto.getExpendDistId() + ",");
        }
        if(StringUtils.isNotEmpty(expendDistLines.toString())){
            BigDecimal price = new BigDecimal(0); //支出分销商额度相加总额
            BigDecimal retailPrice = new BigDecimal(0);//商品销售价
            String expendLines = expendDistLines.substring(0,expendDistLines.length() - 1);
            if(StringUtils.isNotEmpty(expendLines)){
                String[] distLiness = expendLines.split(",");
                ProductStoreRelaEntity relaEntity = productStoreRelaDao.queryByGoodsIdAndStoreId(Long.valueOf(mkDistSellAllocation.getStoreId()),
                        Long.valueOf(mkDistSellAllocation.getGoodsId()));
                if(relaEntity != null){
                    retailPrice = relaEntity.getRetailPrice();
                }
                for(int i = 0;i < distLiness.length; i++){
                    price = price.add(BigDecimal.valueOf(Double.parseDouble(distLiness[i])));
                }
                String allocType = mkDistSellAllocation.getAllocType();
                if(allocType.equalsIgnoreCase(Dict.allocType.item_00.getItem())){
                    if(price.doubleValue() > 1){
                        throw new RRException("分配方式为【"+ Dict.allocType.item_00.getItemName() +"】的支出分销商额度相加总额【"+ price +"】不能超过1");
                    }
                }
                if(allocType.equalsIgnoreCase(Dict.allocType.item_10.getItem())){
                    if(price.doubleValue() > retailPrice.doubleValue()){
                        throw new RRException("分配方式为【"+ Dict.allocType.item_10.getItemName() +"】的支出分销商额度相加总额【"+
                                price +"】不能超过商品销售价，商品销售价为【"+ retailPrice +"】");
                    }
                }
                mkDistSellAllocation.setExpendDistLines(expendLines);
            }
        }
        if(StringUtils.isNotEmpty(expendDistIds.toString())) {
            mkDistSellAllocation.setExpendDistIds(expendDistIds.substring(0, expendDistIds.length() - 1).toString());
        }
        mkDistSellAllocation.setDistChnlId(mkDistHierEntities.getDistChnlId());
        mkDistSellAllocation.setDistFlag(chnlEntity.getDistFlag());
        mkDistSellAllocation.setCreaterSn(ShiroUtils.getUserEntity().getUsername());
        mkDistSellAllocation.setCreateTime(new Date());
        mkDistSellAllocation.setModerSn(ShiroUtils.getUserEntity().getUsername());
        mkDistSellAllocation.setModTime(new Date());

        MkDistSellAllocationHistoryEntity entity = saveDistSellAllocationHistory(mkDistSellAllocation);
        if(entity != null) {
            mkDistSellAllocation.setSellAllocHistoryId(entity.getSellAllocHistoryId());
            return mkDistSellAllocationDao.save(mkDistSellAllocation);
        }else{
            return 0;
        }
    }

    private MkDistSellAllocationHistoryEntity saveDistSellAllocationHistory(MkDistSellAllocationEntity mkDistSellAllocationEntity){
        MkDistSellAllocationHistoryEntity historyEntity = new MkDistSellAllocationHistoryEntity();
        historyEntity.setAllocType(mkDistSellAllocationEntity.getAllocType());
        historyEntity.setCreaterSn(mkDistSellAllocationEntity.getCreaterSn());
        historyEntity.setCreateTime(mkDistSellAllocationEntity.getCreateTime());
        historyEntity.setDistChnlId(mkDistSellAllocationEntity.getDistChnlId());
        historyEntity.setDistFlag(mkDistSellAllocationEntity.getDistFlag());
        historyEntity.setDistId(mkDistSellAllocationEntity.getDistId());
        historyEntity.setExpendDistIds(mkDistSellAllocationEntity.getExpendDistIds());
        historyEntity.setExpendDistLines(mkDistSellAllocationEntity.getExpendDistLines());
        historyEntity.setGoodsId(mkDistSellAllocationEntity.getGoodsId());
        historyEntity.setStoreId(mkDistSellAllocationEntity.getStoreId());
        historyEntity.setSupplierId(mkDistSellAllocationEntity.getSupplierId());
        historyEntity.setIsValid(mkDistSellAllocationEntity.getIsValid());
        historyEntity.setThirdMerchSn(mkDistSellAllocationEntity.getThirdMerchSn());
        historyEntity.setModerSn(mkDistSellAllocationEntity.getModerSn());
        historyEntity.setModTime(mkDistSellAllocationEntity.getModTime());
        historyEntity.setTstm(mkDistSellAllocationEntity.getTstm());
        if(mkDistSellAllocationHistoryDao.save(historyEntity) > 0) {
            return historyEntity;
        }else{
            return null;
        }
    }

    @Override
    public int update(MkDistSellAllocationEntity mkDistSellAllocation) {
        /*List<Integer> expendDistIdList = mkDistSellAllocation.getExpendDistIdList();
        if(expendDistIdList == null || expendDistIdList.size() == 0) {
            throw new RRException("支出分销商不能为空");
        }
        String expendDistLines = mkDistSellAllocation.getExpendDistLines();
        String[] distLiness = expendDistLines.split(",");
        if(expendDistIdList.size() != distLiness.length){
            throw new RRException("支出分销商额度对应个数错误，个数为"+distLiness.length+"，个数需与支出分销商一致，且对应排序！示例：比例1,比例2,比例3...");
        }*/

        List<ExpendDistDto> expendDistList = mkDistSellAllocation.getExpendDistDtoList();
        if(expendDistList == null || expendDistList.size() == 0) {
            throw new RRException("分销额度分配信息不能为空");
        }
        StoreEntity storeEntity = storeDao.queryObject(mkDistSellAllocation.getStoreId());
        if(storeEntity == null){
            throw new RRException("门店id不存在");
        }
        GoodsEntity goodsEntity = goodsDao.queryObject(mkDistSellAllocation.getGoodsId());
        if(goodsEntity == null){
            throw new RRException("商品id不存在");
        }
        MkDistEntity mkDistEntity = mkDistDao.queryObject(mkDistSellAllocation.getDistId());
        if(mkDistEntity == null){
            throw new RRException("商品所属分销商id不存在");
        }
        MkDistHierEntity mkDistHierEntities =  mkDistHierDao.selectDistHierByDistId(mkDistSellAllocation.getDistId());
        if(mkDistHierEntities == null){
            throw new RRException("当前所选的商户所属分销商【"+ mkDistEntity.getDistName() +"】没有层级关系信息，请重新选择");
        }
        MkDistChnlEntity chnlEntity = mkDistChnlDao.queryObject(mkDistHierEntities.getDistChnlId());
        if(chnlEntity == null){
            throw new RRException("分销渠道id不存在");
        }

        Map<String, Object> allocationMap = new HashMap<>();
        allocationMap.put("distId", mkDistSellAllocation.getDistId());
        allocationMap.put("distChnlId", mkDistSellAllocation.getDistChnlId());
        allocationMap.put("goodsId", mkDistSellAllocation.getGoodsId());
        allocationMap.put("storeId", mkDistSellAllocation.getStoreId());
        allocationMap.put("sellAllocId",mkDistSellAllocation.getSellAllocId());
        List<MkDistSellAllocationEntity> allocationEntityList =  mkDistSellAllocationDao.queryAllocationByMap(allocationMap);
        if(allocationEntityList.size() > 0){
            throw new RRException("门店【"+storeEntity.getStoreName()+"】商品【"+ goodsEntity.getName() +
                    "】商户所属分销商【"+ mkDistEntity.getDistName() +"】，已存在渠道销售分配信息！请选择其他商品");
        }
        StringBuffer expendDistLines = new StringBuffer();
        StringBuffer expendDistIds = new StringBuffer();
        for (ExpendDistDto distDto: expendDistList) {
            expendDistLines = expendDistLines.append(distDto.getExpendDistLine() + ",");
            expendDistIds = expendDistIds.append(distDto.getExpendDistId() + ",");
        }
        if(StringUtils.isNotEmpty(expendDistLines.toString())){
            BigDecimal price = new BigDecimal(0); //支出分销商额度相加总额
            BigDecimal retailPrice = new BigDecimal(0);//商品销售价
            String expendLines = expendDistLines.substring(0,expendDistLines.length() - 1);
            if(StringUtils.isNotEmpty(expendLines)){
                String[] distLiness = expendLines.split(",");
                ProductStoreRelaEntity relaEntity = productStoreRelaDao.queryByGoodsIdAndStoreId(Long.valueOf(mkDistSellAllocation.getStoreId()),
                        Long.valueOf(mkDistSellAllocation.getGoodsId()));
                if(relaEntity != null){
                    retailPrice = relaEntity.getRetailPrice();
                }
                for(int i = 0;i < distLiness.length; i++){
                    price = price.add(BigDecimal.valueOf(Double.parseDouble(distLiness[i])));
                }
                String allocType = mkDistSellAllocation.getAllocType();
                if(allocType.equalsIgnoreCase(Dict.allocType.item_10.getItem())){
                    if(price.doubleValue() > retailPrice.doubleValue()){
                        throw new RRException("分配方式为【"+ Dict.allocType.item_10.getItemName() +"】的支出分销商额度相加总额【"+
                                price +"】不能超过商品销售价，商品销售价为【"+ retailPrice +"】");
                    }
                }
                if(allocType.equalsIgnoreCase(Dict.allocType.item_00.getItem())){
                    if(price.doubleValue() > 1){
                        throw new RRException("分配方式为【"+ Dict.allocType.item_00.getItemName() +"】的支出分销商额度相加总额【"+ price +"】不能超过1");
                    }
                }
                mkDistSellAllocation.setExpendDistLines(expendLines);
            }
        }
        if(StringUtils.isNotEmpty(expendDistIds.toString())) {
            mkDistSellAllocation.setExpendDistIds(expendDistIds.substring(0, expendDistIds.length() - 1).toString());
        }
        mkDistSellAllocation.setDistChnlId(mkDistHierEntities.getDistChnlId());
        mkDistSellAllocation.setDistFlag(chnlEntity.getDistFlag());
        mkDistSellAllocation.setModerSn(ShiroUtils.getUserEntity().getUsername());
        mkDistSellAllocation.setModTime(new Date());
        MkDistSellAllocationHistoryEntity entity = saveDistSellAllocationHistory(mkDistSellAllocation);
        if(entity != null) {
            mkDistSellAllocation.setSellAllocHistoryId(entity.getSellAllocHistoryId());
            return mkDistSellAllocationDao.update(mkDistSellAllocation);
        }else{
            return 0;
        }
    }

    @Override
    public int delete(Integer sellAllocId) {
        return mkDistSellAllocationDao.delete(sellAllocId);
    }

    @Override
    public int deleteBatch(Integer[] sellAllocIds) {
        List<String> storeList = new ArrayList<>();
        List<String> goodsList = new ArrayList<>();
        List<String> statisSizeList = new ArrayList<>();
        for (int i = 0; i < sellAllocIds.length; i++){
            MkDistSellAllocationEntity allocationEntity = mkDistSellAllocationDao.queryObject(sellAllocIds[i]);
            Map map = new HashMap();
            map.put("thirdMerchSn", allocationEntity.getThirdMerchSn());
            map.put("distChnlId", allocationEntity.getDistChnlId());
            map.put("distId", allocationEntity.getDistId());
            map.put("storeId", allocationEntity.getStoreId());
            map.put("goodsId", allocationEntity.getGoodsId());
            List<MkDistSellStatisEntity> statisEntityList = mkDistSellStatisDao.queryList(map);
            if(statisEntityList != null && statisEntityList.size() > 0){
                StoreEntity storeEntity = storeDao.queryObject(allocationEntity.getStoreId());
                GoodsEntity goodsEntity = goodsDao.queryObject(allocationEntity.getGoodsId());
                storeList.add(storeEntity.getStoreName());
                goodsList.add(goodsEntity.getName());
                statisSizeList.add(statisEntityList.size()+"条");
            }
        }
        if(storeList != null && storeList.size() > 0){
            throw new RRException("当前删除的对应门店【"+storeList+"】商品【"+goodsList+"】的分配信息已生成【"+statisSizeList+"】出货订单（销售统计数据），请勿删除！");
        }
        return mkDistSellAllocationDao.deleteBatch(sellAllocIds);
    }
}
