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

import com.kmall.admin.dao.mk.MkDistChnlDao;
import com.kmall.admin.dao.mk.MkDistDao;
import com.kmall.admin.dao.mk.MkDistHierDao;
import com.kmall.admin.dao.mk.MkDistSellAllocationDao;
import com.kmall.admin.entity.mk.*;
import com.kmall.admin.service.mk.MkDistHierService;
import com.kmall.admin.utils.ShiroUtils;
import com.kmall.common.constant.Dict;
import com.kmall.common.utils.MapUtils;
import com.kmall.common.utils.RRException;
import com.kmall.common.utils.StringUtils;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 分销层级，树状层级，每个子级只有唯一一个父级，一个父级可以多个子级Service实现类
 *
 * @author emato
 * @email admin@qhdswl.com
 * @date 2019-04-09 18:04:46
 */
@Service("mkDistHierService")
public class MkDistHierServiceImpl implements MkDistHierService {
    @Autowired
    private MkDistHierDao mkDistHierDao;
    @Autowired
    private MkDistDao mkDistDao;
    @Autowired
    private MkDistChnlDao mkDistChnlDao;
    @Autowired
    private MkDistSellAllocationDao mkDistSellAllocationDao;

    @Override
    public MkDistHierEntity queryObject(Integer distHierId) {
        MkDistHierEntity entity = mkDistHierDao.queryObject(distHierId);
        if(entity != null){
            return entity;
        }
        return null;
    }
    @Override
    public Map querySysConfigByKey() {
        Map configMap = mkDistHierDao.querySysConfigByKey("DIST_HIER_LVL");
        return configMap;
    }

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

    @Override
    public List<MkDistHierEntity> queryListByTree(Map<String, Object> map) {
        return mkDistHierDao.queryListByTree(map);
    }
    @Override
    public int queryTotal(Map<String, Object> map) {
        return mkDistHierDao.queryTotal(map);
    }

    @Override
    public MkDistHierEntity queryObjectByDistMap(Map<String, Object> map) {
        List<MkDistHierEntity> mkDistHierEntities = mkDistHierDao.queryObjectByDistIdAndPdistId(map);
        if(mkDistHierEntities.size() == 0){
            return null;
        }else {
            return mkDistHierEntities.get(0);
        }
    }
    private MkDistHierEntity getOneLvlDistByCurrentDistId(Integer distIdParam, Integer pdistIdParam){
        MkDistHierEntity oneLvlDistEntity = new MkDistHierEntity();
        //获取子级层级信息
        MkDistHierEntity mkDistHierEntity = mkDistHierDao.selectDistHierByDistId(pdistIdParam);
        if(mkDistHierEntity == null){
            mkDistHierEntity = mkDistHierDao.selectDistHierByDistId(distIdParam);
        }
        if(mkDistHierEntity != null){
            //子级层级级别
            Integer hierLvl = Integer.parseInt(mkDistHierEntity.getHierLvl());
            Integer pdistId = 0;
            if(mkDistHierEntity != null ){
                pdistId = mkDistHierEntity.getPdistId();
            }
            if(hierLvl == 1){
                Map<String, Object> lvlMap = new HashMap<>();
                lvlMap.put("hierLvl", hierLvl);
                lvlMap.put("pdistId", pdistId);
                List<MkDistHierEntity> lvlList = mkDistHierDao.queryListByTree(lvlMap);
                if(lvlList.size() > 0) {
                    oneLvlDistEntity = lvlList.get(0);
                }
            }else{
                for (int i = 0; i< hierLvl-1; i++){
                    Map<String, Object> lvlMap = new HashMap<>();
                    Integer lvl = hierLvl-1-i;
                    lvlMap.put("hierLvl", lvl);
                    lvlMap.put("pdistId", pdistId);
                    List<MkDistHierEntity> lvlList = mkDistHierDao.queryListByTree(lvlMap);
                    pdistId = lvlList.get(0).getPdistId();
                    if(lvl == 1){
                        oneLvlDistEntity = lvlList.get(0);
                    }
                }
            }
        }
        return oneLvlDistEntity;
    }
    @Override
    public int save(MkDistHierEntity mkDistHier) {
        MkDistEntity pdistEntity = mkDistDao.queryObject(mkDistHier.getPdistId());//父级分销商
        MkDistEntity distEntity = mkDistDao.queryObject(mkDistHier.getDistId());//子级分销商

        MkDistChnlEntity distChnlEntity = mkDistChnlDao.queryObject(mkDistHier.getDistChnlId());
        if (distChnlEntity == null) {
            throw new RRException("分销渠道信息不存在");
        }
        String pdistName = pdistEntity.getDistName();
        String distName = distEntity.getDistName();
        String chnlName = distChnlEntity.getDistFlag();

        //查询当前上下级分销商是否已已存在层级关系
        Map<String, Object> pdistMap = new HashMap<>();
        pdistMap.put("pdistId", mkDistHier.getPdistId());
        pdistMap.put("distId", mkDistHier.getDistId());
        MkDistHierEntity mkDistHierEntity = queryObjectByDistMap(pdistMap);
        if (mkDistHierEntity != null) {
            throw new RRException("上级分销商【"+ pdistName +"】,下级分销商【"+ distName +"】层级关系已存在");
        }
        //交叉查询当前上下级分销商，判断是否已已存在上下层级关系
        Map<String, Object> isChildMap = new HashMap<>();
        isChildMap.put("pdistId", mkDistHier.getDistId());
        isChildMap.put("distId", mkDistHier.getPdistId());
        MkDistHierEntity distHierEntity = queryObjectByDistMap(isChildMap);
        if (distHierEntity != null) {
            throw new RRException("上级分销商【"+ pdistName +"】,下级分销商【"+ distName +"】已存在上下层级关系，不能再次交叉添加");
        }
        MkDistHierEntity hierByChnlIdAndOneLvl = mkDistHierDao.selectDistHierByChnlIdAndOneLvl(mkDistHier.getDistChnlId(),null);
        if(mkDistHier.getHierLvl().equalsIgnoreCase("1")){
            if(hierByChnlIdAndOneLvl != null){
                throw new RRException("分销渠道【"+ chnlName +"】的一级分销商已存在，请修改层级级别");
            }
        }else{
            if(hierByChnlIdAndOneLvl == null){
                throw new RRException("分销渠道【"+ chnlName +"】的一级分销商不存在，不能跨一级以上创建，请先创建该分销渠道的一级分销商，层级级别选择1");
            }
            if(mkDistHier.getPdistId().equals(mkDistHier.getDistId())){
                throw new RRException(mkDistHier.getHierLvl() + "级层级级别的上级分销商【"+ pdistName +"】与子级分销商【"+ distName +"】不能选一致的");
            }
        }
        //判断分销渠道与上级分销商的创建关系
        MkDistHierEntity oneLvlEntity = getOneLvlDistByCurrentDistId(mkDistHier.getDistId(), mkDistHier.getPdistId());
        if(oneLvlEntity != null){
            Integer distChnlId = oneLvlEntity.getDistChnlId();
            if(distChnlId != null && !mkDistHier.getDistChnlId().equals(distChnlId)){
                MkDistChnlEntity chnlByOneLvlEntity = mkDistChnlDao.queryObject(distChnlId);
                throw new RRException("当前所选的分销渠道与上级分销商【" + pdistName + "】不存在层级关系，请选择该上级分销商的分销渠道【" +
                        chnlByOneLvlEntity.getDistFlag() + "】");
            }
        }
        //查询当前子级分销商是否已创建层级关系
        MkDistHierEntity checkChildDistEntity = mkDistHierDao.selectDistHierByDistId(mkDistHier.getDistId());
        if (checkChildDistEntity != null){
            throw new RRException("当前选择的子级分销商【"+ distName +"】已与其他分销商创建层级关系，请重新选择子级分销商");
        }
        //判断分销商的层级是否已存在
        Map hierMap = new HashMap();
        hierMap.put("pdistId" , mkDistHier.getPdistId());
        hierMap.put("distChnlId" , mkDistHier.getDistChnlId());
        hierMap.put("hierLvl" , mkDistHier.getHierLvl());
        MkDistHierEntity hierEntity = mkDistHierDao.queryObjectByHierMap(hierMap);
        if(hierEntity != null){
            throw new RRException("当前选择的子级分销商【" + distName + "】的层级级别【"+ mkDistHier.getHierLvl() +"】已存在");
        }

        /*//判断分销渠道与上级分销商的创建关系
        List<MkDistHierEntity> queryByPdistAndChnlList = mkDistHierDao.queryObjectByPdistIdAndChnlId(mkDistHier.getPdistId(), mkDistHier.getDistChnlId());
        if(queryByPdistAndChnlList.size() == 0) {
            List<MkDistHierEntity> hierByChnlList = mkDistHierDao.queryObjectByPdistIdAndChnlId(null, mkDistHier.getDistChnlId());
            if (hierByChnlList != null && hierByChnlList.size() > 0) {
                throw new RRException("分销渠道【" + chnlName + "】已与上级分销商【" + hierByChnlList.get(0).getDistName() + "】创建关系，不能再与其他分销商存在关系");
            }
            List<MkDistHierEntity> hierByPdistList = mkDistHierDao.queryObjectByPdistIdAndChnlId(mkDistHier.getPdistId(), null);
            if (hierByPdistList.size() > 0 && hierByPdistList != null) {
                throw new RRException("分销渠道【" + hierByPdistList.get(0).getDistFlag() + "】已与上级分销商【" + pdistName + "】创建关系，不能再与其他分销渠道存在关系");
            }
        }*/

        //判断分销层级名称是否存在
        MkDistHierEntity mkDistHierEntityByName = mkDistHierDao.queryObjectByName(mkDistHier.getDistHierName());
        if (mkDistHierEntityByName != null) {
            throw new RRException("分销层级名称已存在");
        }
        //判断层级不能超过最高限度
        Map configMap = mkDistHierDao.querySysConfigByKey("DIST_HIER_LVL");
        String value = MapUtils.getString("value", configMap);
        if(StringUtils.isNotEmpty(value)) {
            //查询上级分销商已存在的层级信息
            MkDistHierEntity distByPdistIdEntity = mkDistHierDao.selectDistHierByDistId(mkDistHier.getPdistId());
            if(distByPdistIdEntity != null){
                Integer distHierLvl = Integer.parseInt(distByPdistIdEntity.getHierLvl());
                if(distHierLvl == Integer.parseInt(value)){
                    throw new RRException("该上级分销商【"+ pdistName +"】的层级级别为【"+ distHierLvl +"】级，不能再创建层级为【"+ mkDistHier.getHierLvl() +"】的信息");
                }
                if(Integer.parseInt(mkDistHier.getHierLvl()) != distHierLvl+1){
                    throw new RRException("该上级分销商【"+ pdistName +"】的层级级别为【"+ distHierLvl +"】级，请选择层级级别为【"+ (distHierLvl+1) +"】，不能跨一级以上创建");
                }
            }
        }
//        mkDistHier.setHierLvl(String.valueOf(distHierLvl));
        mkDistHier.setCreaterSn(ShiroUtils.getUserEntity().getUsername());
        mkDistHier.setCreateTime(new Date());
        mkDistHier.setModerSn(ShiroUtils.getUserEntity().getUsername());
        mkDistHier.setModTime(new Date());
        return mkDistHierDao.save(mkDistHier);
    }

    @Override
    public int update(MkDistHierEntity mkDistHier) {
        MkDistEntity pdistEntity = mkDistDao.queryObject(mkDistHier.getPdistId());//父级分销商
        MkDistEntity distEntity = mkDistDao.queryObject(mkDistHier.getDistId());//子级分销商
        MkDistChnlEntity distChnlEntity = mkDistChnlDao.queryObject(mkDistHier.getDistChnlId());
        if (distChnlEntity == null) {
            throw new RRException("分销渠道信息不存在");
        }
        String pdistName = pdistEntity.getDistName();
        String distName = distEntity.getDistName();
        String chnlName = distChnlEntity.getDistFlag();

        //查询当前上下级分销商是否已存在层级关系
        Map<String, Object> pdistMap = new HashMap<>();
        pdistMap.put("pdistId", mkDistHier.getPdistId());
        pdistMap.put("distId", mkDistHier.getDistId());
        MkDistHierEntity mkDistHierEntity = queryObjectByDistMap(pdistMap);
        if (mkDistHierEntity != null && !mkDistHierEntity.getDistHierId().equals(mkDistHier.getDistHierId())) {
            throw new RRException("上级分销商【"+ pdistName +"】,下级分销商【"+ distName +"】层级关系已存在");
        }
        //交叉查询当前上下级分销商，判断是否已已存在上下层级关系
        Map<String, Object> isChildMap = new HashMap<>();
        isChildMap.put("pdistId", mkDistHier.getDistId());
        isChildMap.put("distId", mkDistHier.getPdistId());
        MkDistHierEntity distHierEntity = queryObjectByDistMap(isChildMap);
        if (distHierEntity != null && !distHierEntity.getDistHierId().equals(mkDistHier.getDistHierId())) {
            throw new RRException("上级分销商【"+ pdistName +"】,下级分销商【"+ distName +"】已存在上下层级关系，不能再次交叉添加");
        }

        MkDistHierEntity hierByChnlIdAndOneLvl = mkDistHierDao.selectDistHierByChnlIdAndOneLvl(mkDistHier.getDistChnlId(), mkDistHier.getDistHierId());
        if(!mkDistHier.getHierLvl().equalsIgnoreCase("1")){
            if(hierByChnlIdAndOneLvl == null){
                throw new RRException("分销渠道【"+ chnlName +"】的一级分销商不存在，不能跨一级以上创建，请先创建该分销渠道的一级分销商，层级级别选择1");
            }
            if(mkDistHier.getPdistId().equals(mkDistHier.getDistId())){
                throw new RRException(mkDistHier.getHierLvl() + "级层级级别的上级分销商【"+ pdistName +"】与子级分销商【"+ distName +"】不能选一致的");
            }
        }else{
            if(hierByChnlIdAndOneLvl != null){
                throw new RRException("分销渠道【"+ chnlName +"】的一级分销商已存在，请修改层级级别");
            }
        }
        //判断分销渠道与上级分销商的创建关系
        MkDistHierEntity oneLvlEntity = getOneLvlDistByCurrentDistId(mkDistHier.getDistId(), mkDistHier.getPdistId());
        if(oneLvlEntity != null){
            Integer distChnlId = oneLvlEntity.getDistChnlId();
            if(!mkDistHier.getDistChnlId().equals(distChnlId)){
                MkDistChnlEntity chnlByOneLvlEntity = mkDistChnlDao.queryObject(distChnlId);
                throw new RRException("当前所选的分销渠道与上级分销商【" + pdistName + "】不存在层级关系，请选择该上级分销商的分销渠道【" +
                        chnlByOneLvlEntity.getDistFlag() + "】");
            }
        }
        //查询当前子级分销商是否已创建层级关系
        MkDistHierEntity checkChildDistEntity = mkDistHierDao.selectDistHierByDistId(mkDistHier.getDistId());
        if (checkChildDistEntity != null && !checkChildDistEntity.getDistHierId().equals(mkDistHier.getDistHierId())){
            throw new RRException("当前选择的子级分销商【"+ distName +"】已与其他分销商创建层级关系，请重新选择");
        }

        //判断该上级分销商的层级是否已存在
        Map hierMap = new HashMap();
        hierMap.put("pdistId",mkDistHier.getPdistId());
        hierMap.put("distId",mkDistHier.getDistId());
        hierMap.put("distChnlId",mkDistHier.getDistChnlId());
        hierMap.put("hierLvl", mkDistHier.getHierLvl());
        MkDistHierEntity hierEntity = mkDistHierDao.queryObjectByHierMap(hierMap);
        if(hierEntity != null && !hierEntity.getDistHierId().equals(mkDistHier.getDistHierId())){
            throw new RRException("当前选择的子级分销商【" + distName + "】的层级级别【"+ mkDistHier.getHierLvl() +"】已存在");
        }
        /*//判断分销渠道与上级分销商的创建关系
        List<MkDistHierEntity> queryByPdistAndChnlList = mkDistHierDao.queryObjectByPdistIdAndChnlId(mkDistHier.getPdistId(), mkDistHier.getDistChnlId());
        if(queryByPdistAndChnlList.size() == 0) {
            List<MkDistHierEntity> hierByChnlList = mkDistHierDao.queryObjectByPdistIdAndChnlId(null, mkDistHier.getDistChnlId());
            if (hierByChnlList != null && hierByChnlList.size() > 0) {
                throw new RRException("分销渠道【" + chnlName + "】已与上级分销商【" + hierByChnlList.get(0).getDistName() + "】创建关系，不能再与其他分销商存在关系");
            }
            List<MkDistHierEntity> hierByPdistList = mkDistHierDao.queryObjectByPdistIdAndChnlId(mkDistHier.getPdistId(), null);
            if (hierByPdistList != null && hierByPdistList.size() > 0) {
                throw new RRException("分销渠道【" + hierByPdistList.get(0).getDistFlag() + "】已与上级分销商【" + pdistName + "】创建关系，不能再与其他分销渠道存在关系");
            }
        }*/
        //判断分销层级名称是否存在
        MkDistHierEntity mkDistHierEntityByName = mkDistHierDao.queryObjectByName(mkDistHier.getDistHierName());
        if (mkDistHierEntityByName != null && !mkDistHierEntityByName.getDistHierId().equals(mkDistHier.getDistHierId())) {
            throw new RRException("分销层级名称已存在");
        }

        //判断层级不能超过最高限度
        Map configMap = mkDistHierDao.querySysConfigByKey("DIST_HIER_LVL");
        String value = MapUtils.getString("value", configMap);
        if(StringUtils.isNotEmpty(value)) {
            //查询上级分销商已存在的层级信息
            MkDistHierEntity distByPdistIdEntity = mkDistHierDao.selectDistHierByDistId(mkDistHier.getPdistId());
            if(distByPdistIdEntity != null && !distByPdistIdEntity.getDistHierId().equals(mkDistHier.getDistHierId())){
                Integer distHierLvl = Integer.parseInt(distByPdistIdEntity.getHierLvl());
                if(distHierLvl == Integer.parseInt(value)){
                    throw new RRException("该上级分销商【"+ pdistName +"】的层级级别为【"+ distHierLvl +"】级，不能再创建层级为【"+ mkDistHier.getHierLvl() +"】的信息");
                }
                if(Integer.parseInt(mkDistHier.getHierLvl()) != distHierLvl+1){
                    throw new RRException("该上级分销商【"+ pdistName +"】的层级级别为【"+ distHierLvl +"】级，请选择层级级别为【"+ (distHierLvl+1) +"】，不能跨一级以上创建");
                }
            }
        }

        mkDistHier.setModerSn(ShiroUtils.getUserEntity().getUsername());
        mkDistHier.setModTime(new Date());
        return mkDistHierDao.update(mkDistHier);
    }

    @Override
    public int delete(Integer distHierId) {
        MkDistHierEntity hierEntity = mkDistHierDao.queryObject(distHierId);
        Map<String, Object> allocationMap = new HashMap<>();
        allocationMap.put("distChnlId", hierEntity.getDistChnlId());
        allocationMap.put("distId", hierEntity.getPdistId());
        List<MkDistSellAllocationEntity> allocationEntityList =  mkDistSellAllocationDao.queryAllocationByMap(allocationMap);
        if(allocationEntityList != null && allocationEntityList.size() > 0){
            throw new RRException("当前删除的分销层级关系已与渠道销售分配信息关联，请勿删除");
        }
        return mkDistHierDao.delete(distHierId);
    }

    @Override
    public int deleteBatch(Integer[] distHierIds) {
        List<String> hierNameList = new ArrayList<>();
        List<String> allocationSizeList = new ArrayList<>();
        for(int i=0; i<distHierIds.length; i++) {
            MkDistHierEntity hierEntity = mkDistHierDao.queryObject(distHierIds[i]);
            //查询该分销层级关系是否已与渠道销售分配信息关联
            Map<String, Object> allocationMap = new HashMap<>();
            allocationMap.put("distChnlId", hierEntity.getDistChnlId());
            allocationMap.put("distId", hierEntity.getDistId());
            List<MkDistSellAllocationEntity> allocationEntityList = mkDistSellAllocationDao.queryAllocationByMap(allocationMap);
            if(allocationEntityList != null && allocationEntityList.size() > 0){
                hierNameList.add(hierEntity.getDistHierName());
                allocationSizeList.add(allocationEntityList.size()+"条");
            }
        }
        if(hierNameList != null && hierNameList.size() > 0){
            throw new RRException("当前删除的层级名称【"+hierNameList.get(0)+"】的分销层级关系已创建【"+allocationSizeList.get(0)+"】渠道销售分配信息关联，请勿删除");
        }
        return mkDistHierDao.deleteBatch(distHierIds);
    }
}
