package org.stm.base.classify.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.common.system.vo.SelectTreeModel;
import org.stm.base.classify.entity.StClassify;
import org.stm.base.classify.mapper.StClassifyMapper;
import org.stm.base.classify.service.IStClassifyService;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.stm.base.classify.vo.ClassifyVo;
import org.stm.base.domain.entity.StDomain;
import org.stm.utils.StmConstans;
import org.stm.utils.UserUtil;

/**
 * @Description: st_classify
 * @Author: yzh
 * @Date:   2023-04-02
 * @Version: V1.0
 */
@Service
public class StClassifyServiceImpl extends ServiceImpl<StClassifyMapper, StClassify> implements IStClassifyService {

    public String getCode(StClassify entity){
        // 上级编码为空
        if(StringUtils.isEmpty(entity.getUpperClassifyCode())){
            QueryWrapper<StClassify> wapper = new QueryWrapper();
            wapper.eq("UPPER_CLASSIFY_CODE",ROOT_PID_VALUE);
            wapper.orderByDesc("CLASSIFY_CODE");
            wapper.last("limit 1");
            StClassify noUpperDomain = super.baseMapper.selectOne(wapper);
            // 如果为空，从001开始编码
            if(noUpperDomain == null) {
                return StringUtils.leftPad("1",2,"0");
            }else{
                // 如果不为空+1
                int no  = Integer.valueOf(noUpperDomain.getClassifyCode())+1;
                if(no>99){
                    throw new JeecgBootException("一级领域编号已经超过100,无法在创建");
                }
                String str = ""+no;
                return StringUtils.leftPad(str,2,"0");
            }
        }else{
            // 上级编码不为空
            QueryWrapper<StClassify> wapper = new QueryWrapper();
            String upperCode = entity.getUpperClassifyCode();
            wapper.eq("UPPER_CLASSIFY_CODE",upperCode);
            wapper.orderByDesc("CLASSIFY_CODE");
            wapper.last("limit 1");
            StClassify upperDomain = super.baseMapper.selectOne(wapper);
            // 如果为空，从1开始编码
            if(upperDomain == null) {
                return upperCode+StringUtils.leftPad("1",2,"0");
            }else{
                // 如果不为空+1
                int no  = Integer.valueOf(upperDomain.getClassifyCode())+1;
                if(no%100==0){
                    throw new JeecgBootException("二级领域编号已经超过100,无法在创建");
                }
                String str = ""+no;
                return StringUtils.leftPad(str,4,"0");
            }
        }
    }
    private void checkName(StClassify entity, boolean isSave){
        if(entity==null){
            return;
        }
        QueryWrapper<StClassify> wapper = new QueryWrapper<>();
        wapper.eq("CLASSIFY_NAME",entity.getClassifyName());
        if(!isSave){
            wapper.ne("CLASSIFY_CODE",entity.getClassifyCode());
        }
        long count = super.count(wapper);
        if(count>0){
            throw new JeecgBootException("标签分类管理名称已存在");
        }
    }
	@Override
	public void addStClassify(StClassify stClassify) {
        checkName(stClassify,true);
        String stClassifyCode = getCode(stClassify);
        stClassify.setClassifyCode(stClassifyCode);
        stClassify.setCreatedUser(UserUtil.getUserCode());
        stClassify.setValid(StmConstans.DEFAULT_VALID);
        stClassify.setApproveFlag(StmConstans.DEFAULT_APPROVE_Flag);
	   //新增时设置hasChild为0
	    stClassify.setHasChild(IStClassifyService.NOCHILD);
		if(oConvertUtils.isEmpty(stClassify.getUpperClassifyCode())){
			stClassify.setUpperClassifyCode(IStClassifyService.ROOT_PID_VALUE);
		}else{
            //如果当前节点父ID不为空 则设置父节点的hasChildren 为1
            QueryWrapper<StClassify> wapper = new QueryWrapper();
            wapper.eq("CLASSIFY_CODE", stClassify.getUpperClassifyCode());
            wapper.last("limit 1");
            StClassify parent = baseMapper.selectOne(wapper);
			if(parent!=null && !"1".equals(parent.getHasChild())){
				parent.setHasChild("1");
				baseMapper.updateById(parent);
			}
		}
		baseMapper.insert(stClassify);
	}
	
	@Override
	public void updateStClassify(StClassify stClassify) {
        checkName(stClassify,false);
		StClassify entity = this.getById(stClassify.getId());
		if(entity==null) {
			throw new JeecgBootException("未找到对应实体");
		}
		String old_pid = entity.getUpperClassifyCode();
		String new_pid = stClassify.getUpperClassifyCode();
		if(!old_pid.equals(new_pid)) {
			updateOldParentNode(old_pid);
			if(oConvertUtils.isEmpty(new_pid)){
				stClassify.setUpperClassifyCode(IStClassifyService.ROOT_PID_VALUE);
			}
			if(!IStClassifyService.ROOT_PID_VALUE.equals(stClassify.getUpperClassifyCode())) {
				baseMapper.updateTreeNodeStatus(stClassify.getUpperClassifyCode(), IStClassifyService.HASCHILD);
			}
		}
        // 设置更新人员
        stClassify.setUpdatedUser(UserUtil.getUserCode());
		baseMapper.updateById(stClassify);
	}
	
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void deleteStClassify(String id) throws JeecgBootException {
		//查询选中节点下所有子节点一并删除
        id = this.queryTreeChildIds(id);
        if(id.indexOf(",")>0) {
            StringBuffer sb = new StringBuffer();
            String[] idArr = id.split(",");
            for (String idVal : idArr) {
                if(idVal != null){
                    StClassify stClassify = this.getById(idVal);
                    String pidVal = stClassify.getUpperClassifyCode();
                    //查询此节点上一级是否还有其他子节点
                    List<StClassify> dataList = baseMapper.selectList(new QueryWrapper<StClassify>().eq("upper_classify_code", pidVal).notIn("id",Arrays.asList(idArr)));
                    boolean flag = (dataList == null || dataList.size() == 0) && !Arrays.asList(idArr).contains(pidVal) && !sb.toString().contains(pidVal);
                    if(flag){
                        //如果当前节点原本有子节点 现在木有了，更新状态
                        sb.append(pidVal).append(",");
                    }
                }
            }
            //批量删除节点
            baseMapper.deleteBatchIds(Arrays.asList(idArr));
            //修改已无子节点的标识
            String[] pidArr = sb.toString().split(",");
            for(String pid : pidArr){
                this.updateOldParentNode(pid);
            }
        }else{
            StClassify stClassify = this.getById(id);
            if(stClassify==null) {
                throw new JeecgBootException("未找到对应实体");
            }
            updateOldParentNode(stClassify.getUpperClassifyCode());
            baseMapper.deleteById(id);
        }
	}
	
	@Override
    public List<StClassify> queryTreeListNoPage(QueryWrapper<StClassify> queryWrapper) {
        List<StClassify> dataList = baseMapper.selectList(queryWrapper);
        List<StClassify> mapList = new ArrayList<>();
        for(StClassify data : dataList){
            String pidVal = data.getUpperClassifyCode();
            //递归查询子节点的根节点
            if(pidVal != null && !IStClassifyService.NOCHILD.equals(pidVal)){
                StClassify rootVal = this.getTreeRoot(pidVal);
                if(rootVal != null && !mapList.contains(rootVal)){
                    mapList.add(rootVal);
                }
            }else{
                if(!mapList.contains(data)){
                    mapList.add(data);
                }
            }
        }
        return mapList;
    }

    @Override
    public List<SelectTreeModel> queryListByCode(String parentCode) {
        String pid = ROOT_PID_VALUE;
        if (oConvertUtils.isNotEmpty(parentCode)) {
            LambdaQueryWrapper<StClassify> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(StClassify::getUpperClassifyCode, parentCode);
            List<StClassify> list = baseMapper.selectList(queryWrapper);
            if (list == null || list.size() == 0) {
                throw new JeecgBootException("该编码【" + parentCode + "】不存在，请核实!");
            }
            if (list.size() > 1) {
                throw new JeecgBootException("该编码【" + parentCode + "】存在多个，请核实!");
            }
            pid = list.get(0).getClassifyCode();
        }
        return baseMapper.queryListByPid(pid, null);
    }

    @Override
    public List<SelectTreeModel> queryListByPid(String pid) {
        if (oConvertUtils.isEmpty(pid)) {
            pid = ROOT_PID_VALUE;
        }
        return baseMapper.queryListByPid(pid, null);
    }

    @Override
    public List<ClassifyVo> listClassify() {
        QueryWrapper<StClassify> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("LEVEL","1");
        queryWrapper.eq("HAS_CHILD","1");
        queryWrapper.orderByDesc("SORT_NO");
        List<StClassify> stClassifies = baseMapper.selectList(queryWrapper);
        List<ClassifyVo> classifyVos = new ArrayList<>();
        for(StClassify stClassify:stClassifies){
            ClassifyVo classifyVo = ClassifyVo.bulidByStClassify(stClassify);
            QueryWrapper<StClassify> queryChildWrapper = new QueryWrapper<>();
            queryChildWrapper.eq("LEVEL","2");
            queryChildWrapper.eq("UPPER_CLASSIFY_CODE",stClassify.getClassifyCode());
            queryChildWrapper.orderByDesc("SORT_NO");
            List<StClassify> childClassifys = baseMapper.selectList(queryChildWrapper);
            classifyVo.buildOptions(childClassifys);
            classifyVos.add(classifyVo);
        }
        return classifyVos;
    }

    @Override
    public String getNameByCode(String code) {
        // 确保字段名正确（区分大小写）
        QueryWrapper<StClassify> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("classify_name")  // 只查询需要的字段
                .eq("classify_code", code);  // 使用小写字段名

        Map<String, Object> map = getMap(queryWrapper);
        return map != null ? (String) map.get("classify_name") : null;
    }


    public Map<String, String> getAllDataMap() {
        QueryWrapper<StClassify> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("classify_code", "classify_name");

        // selectMaps() 返回 List<Map<String, Object>>
        List<Map<String, Object>> list = this.baseMapper.selectMaps(queryWrapper);

        // 转换为单个Map：code -> name
        Map<String, String> resultMap = new HashMap<>();
        for (Map<String, Object> map : list) {
            String code = (String) map.get("classify_code");
            String name = (String) map.get("classify_name");
            if (code != null) {
                resultMap.put(code, name);
            }
        }
        return resultMap;
    }

    /**
	 * 根据所传pid查询旧的父级节点的子节点并修改相应状态值
	 * @param pid
	 */
	private void updateOldParentNode(String pid) {
		if(!IStClassifyService.ROOT_PID_VALUE.equals(pid)) {
			Long count = baseMapper.selectCount(new QueryWrapper<StClassify>().eq("upper_classify_code", pid));
			if(count==null || count<=1) {

				baseMapper.updateTreeNodeStatus(pid, IStClassifyService.NOCHILD);
			}
		}
	}

	/**
     * 递归查询节点的根节点
     * @param pidVal
     * @return
     */
    private StClassify getTreeRoot(String pidVal){
        StClassify data =  baseMapper.selectById(pidVal);
        if(data != null && !IStClassifyService.ROOT_PID_VALUE.equals(data.getUpperClassifyCode())){
            return this.getTreeRoot(data.getUpperClassifyCode());
        }else{
            return data;
        }
    }

    /**
     * 根据id查询所有子节点id
     * @param ids
     * @return
     */
    private String queryTreeChildIds(String ids) {
        //获取id数组
        String[] idArr = ids.split(",");
        StringBuffer sb = new StringBuffer();
        for (String pidVal : idArr) {
            if(pidVal != null){
                if(!sb.toString().contains(pidVal)){
                    if(sb.toString().length() > 0){
                        sb.append(",");
                    }
                    sb.append(pidVal);
                    this.getTreeChildIds(Integer.valueOf(pidVal),sb);
                }
            }
        }
        return sb.toString();
    }
    private String id2Code(Integer id){
        if(id == null){
            return null;
        }
        StClassify stClassify= baseMapper.selectById(id);
        if(stClassify == null){
            return null;
        }
        return stClassify.getClassifyCode();
    }
    /**
     * 递归查询所有子节点
     * @param pidVal
     * @param sb
     * @return
     */
    private StringBuffer getTreeChildIds(Integer pidVal,StringBuffer sb){
        String upCode = id2Code(pidVal);
        if(StringUtils.isEmpty(upCode)){
            return sb;
        }
        List<StClassify> dataList = baseMapper.selectList(new QueryWrapper<StClassify>().eq("upper_classify_code", upCode));
        if(dataList != null && dataList.size()>0){
            for(StClassify tree : dataList) {
                if(!sb.toString().contains(tree.getClassifyCode())){
                    sb.append(",").append(tree.getId());
                }
                this.getTreeChildIds(tree.getId(),sb);
            }
        }
        return sb;
    }

}
