package com.unis.crk.basic.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.unis.crk.basic.entity.BasicEnum;
import com.unis.crk.basic.mapper.BasicEnumMapper;
import com.unis.crk.basic.service.IBasicEnumService;
import com.unis.crk.basic.entity.vo.BasicEnumVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import springfox.documentation.service.ApiListing;

import java.util.*;

/**
 * <p>
 * 数据字典大类 服务实现类
 * </p>
 *
 * @author TangSong
 * @since 2021-08-04
 */
@Service
public class BasicEnumServiceImpl extends ServiceImpl<BasicEnumMapper, BasicEnum> implements IBasicEnumService {

    @Autowired
    private BasicEnumMapper basicEnumMapper;




    @Override
    public IPage<BasicEnum> findPageVo(BasicEnumVo pageQuery)
        {
        //条形查询器
        QueryWrapper<BasicEnum> queryWrapper = new QueryWrapper<>();
        if (ObjectUtil.isNotNull(pageQuery.getId())){
            queryWrapper.eq("parentId",pageQuery.getId());
        }
        if (ObjectUtil.isNotNull(pageQuery.getName())){
            queryWrapper.like("enumName",pageQuery.getName());
        }
        //分页相关
        Page<BasicEnum> p =new Page<>(pageQuery.getPage(),pageQuery.getLimit());

        IPage<BasicEnum> page = basicEnumMapper.selectPage(p,queryWrapper);
        return page;
    }

    @Override
    public Map<Object, Object> findEnumObjEnumId()  {
        Map<Object, Object> map = new HashMap<>();
        QueryWrapper<BasicEnum> basicEnumQueryWrapper = new QueryWrapper<>();
        basicEnumQueryWrapper.select().orderByAsc("enumId");
        List<BasicEnum> list = basicEnumMapper.selectList(basicEnumQueryWrapper); //查询到所有正常数据

        for (BasicEnum be : list) {
            map.put(be.getEnumId(), be.getEnumName());
        }
        return map;
    }

    @Override
    public Map<String, List<BasicEnum>> findEnumObjParentId()  {
        Map<String, List<BasicEnum>> resultMap = new HashMap<>();
        QueryWrapper<BasicEnum> basicEnumQueryWrapper = new QueryWrapper<>();
        //查询为0或者为空的数据
        basicEnumQueryWrapper.isNull("parentId").or().eq("parentId","0");
        basicEnumQueryWrapper.select().orderByAsc("enumId");
        List<BasicEnum> list = basicEnumMapper.selectList(basicEnumQueryWrapper); //查询到所有正常数据
        for (BasicEnum be : list) {
           String enumId = be.getEnumId();
            basicEnumQueryWrapper = new QueryWrapper<>();
            //查询根节点为enumid数据，排除自己
            basicEnumQueryWrapper.isNotNull("parentId").ne("parentId",enumId);
//                    .eq("ENUM_ROOT_ID",enumId);
            basicEnumQueryWrapper.select().orderByAsc("enumId");
            List<BasicEnum> list1 = basicEnumMapper.selectList(basicEnumQueryWrapper); //查询到所有正常数据
            resultMap.put(enumId,list1);
        }
        return resultMap;
    }


    private List<BasicEnum> getChildren(List<BasicEnum> list, String parentId) {
        List<BasicEnum> children = new ArrayList<BasicEnum>();
        for(BasicEnum be: list){
            //遍历出父id等于参数的id，add进子节点集合
            if (StringUtils.equals(be.getParentId(),parentId)) {
                children.add(be);
            }
        }
        return children;
    }

    public void fillTree(List<BasicEnum> allList, List<BasicEnum> childList) {
        if(childList.size()>0){
            for(BasicEnum be : childList) {
                List<BasicEnum> childList1 = this.getChildren(allList, be.getEnumId());
                fillTree(allList, childList1);
                be.setChildren(childList1);
            }
        }
    }

    @Override
    public List<BasicEnum> queryByTree() {

        List<BasicEnum> list = basicEnumMapper.selectList(new QueryWrapper<BasicEnum>().select().orderByAsc("enumId"));
        List<BasicEnum> firstlist = this.getChildren(super.list(), "0");
        this.fillTree(list, firstlist);
        return firstlist;
    }

    @Override
    public List<BasicEnum> queryAllChildren(String enumid) {
        Map<String, List<BasicEnum>> resultMap = new HashMap<>();
        QueryWrapper<BasicEnum> basicEnumQueryWrapper = new QueryWrapper<>();
        basicEnumQueryWrapper.eq("parentId",enumid);
        basicEnumQueryWrapper.eq("delFlag",1); //未删除
        basicEnumQueryWrapper.select().orderByDesc("parentId").orderByAsc("enumCode");
        List<BasicEnum> list = basicEnumMapper.selectList(basicEnumQueryWrapper); //查询到所有正常数据
        if (list != null && list.size() > 0){
            for (int i = 0; i < list.size(); i++) {
                BasicEnum firstNode = list.get(i);
                List<BasicEnum> childrenList =  this.getChildren(firstNode);
                if (childrenList != null && childrenList.size() > 0){
                    firstNode.setChildren(childrenList);
                }
            }
        }
        return list;
    }

    private List<BasicEnum> getChildren(BasicEnum node) {
        String parendId = node.getEnumId(); //做为父级id
        QueryWrapper<BasicEnum> basicEnumQueryWrapper = new QueryWrapper<>();
        basicEnumQueryWrapper.eq("parentId",parendId);
        basicEnumQueryWrapper.eq("delFlag",1); //未删除
        basicEnumQueryWrapper.select().orderByDesc("parentId").orderByAsc("enumCode");
        List<BasicEnum> list = basicEnumMapper.selectList(basicEnumQueryWrapper); //查询到所有正常数据
        if (list != null && list.size() > 0){
            for (int i = 0; i < list.size(); i++) {
                BasicEnum node_ = list.get(i);
                List<BasicEnum> childrenList =  this.getChildren(node_);
                if (childrenList == null && childrenList.size() <= 0){
                   continue; //表明没有下级了，跳出当前循环
                }
                node_.setChildren(childrenList);
            }
        }
        return list;
    }

    private List<BasicEnum> getAllChildren(List<BasicEnum> allList,
                                           List<BasicEnum> childList, List<BasicEnum> resultList) {
        resultList.addAll(childList);
        for(BasicEnum be : childList) {
            List<BasicEnum> childList1 = this.getChildren(allList, be.getEnumId());
            if(childList1.size()>0){
                this.getAllChildren(allList, childList1, resultList);
            }
        }
        return resultList;
    }

    /**
     * 枚举导入
     * @param list
     * @throws Exception
     */
    @Override
    public String importData(List<List<String>> list) {
        boolean value_flag = false;
        int len = 0;
        String msg = "";
        StringBuilder sql = new StringBuilder();
        sql.append("");
        for (int i = 0; i < list.size(); i++) {
            List<String> revList = list.get(i);
            sql.append("(NOW(), 1, ");

            for (int j = 0; j < revList.size(); j++) {

                if (j == 0) {
                    value_flag = revList.get(j).matches("[0-9]+");
                    if (!value_flag) {
                        msg = "第 "+(i+1)+" 行的第 1 列的值只能是数字！";
                        return msg;
                    }
                    len = revList.get(j).length();
                    if (len > 11) {
                        msg = "第 "+(i+1)+" 行的第 1 列的值的长度不能超过11！";
                        return msg;
                    }

                    sql.append(revList.get(j));
                } else if (j == 1) {
                    len = revList.get(j).length();
                    if (len > 50) {
                        msg = "第 "+(i+1)+" 行的第 2 列的值的长度不能超过50！";
                        return msg;
                    }
                    sql.append("\""+revList.get(j)+"\"");
                } else if (j == 2) {
                    len = revList.get(j).length();
                    if (len > 50) {
                        msg = "第 "+(i+1)+" 行的第3 列的值的长度不能超过50！";
                        return msg;
                    }
                    sql.append("\""+revList.get(j)+"\"");
                } else if (j == 3) {
                    len = revList.get(j).length();
                    if (len > 50) {
                        msg = "第 "+(i+1)+" 行的第4 列的值的长度不能超过50！";
                        return msg;
                    }
                    sql.append("\""+revList.get(j)+"\"");
                } else if (j == 4) {
                    len = revList.get(j).length();
                    if (len > 255) {
                        msg = "第 "+(i+1)+" 行的第5 列的值的长度不能超过255！";
                        return msg;
                    }
                    sql.append("\""+revList.get(j)+"\"");
                }
                //最后一个字段后不加逗号
                if (j != revList.size()-1){
                    sql.append(",");
                }
            }
            sql.append(")");
            if (i != list.size()-1){
                sql.append(",");
            }
        }

        System.out.println(sql.toString());
        Map<String,String> map = new HashMap<>();
        map.put("sql",sql.toString());
        basicEnumMapper.importData(map);

        return msg;
    }



    @Override
    public Map<String, Object> updateOrSave(String enumJson)  {
        Map<String, Object> result_map = new HashMap<>();
        // JSON字符串转对象
        ObjectMapper mapper = new ObjectMapper();
        try {
            BasicEnum basicEnum = (BasicEnum) mapper.readValue(enumJson, BasicEnum.class);
            if (basicEnum.getEnumId() == null) {
                basicEnum.setDelFlag(1);
                basicEnum.setCreateDate(new Date());  //创建时间
                this.saveOrUpdate(basicEnum);
                result_map.put("basicEnum", basicEnum);
            } else {
                this.updateById(basicEnum);
            }
        }catch (Exception e){
            result_map.put("status", "false");
        }
        result_map.put("status", "success");
        return result_map;
    }

    @Override
    public Map<String, Object> removeObj(String id) {
        Map<String, Object> modelMap = new HashMap<>();
        // 先查询到这条数据
        BasicEnum basicEnum = this.getById(id);

        // 将删除标识改为0,然后在修改一次
        basicEnum.setDelFlag(0);
        this.updateById(basicEnum);

        modelMap.put("status", "success");

        return modelMap;
    }

    @Override
    public List<BasicEnum> queryAllChildren(String enumid, Boolean isQueryFristNode) {
        QueryWrapper<BasicEnum> basicEnumQueryWrapper = new QueryWrapper<>();
        basicEnumQueryWrapper.eq("parentId",enumid);
        basicEnumQueryWrapper.eq("delFlag",1); //未删除
        basicEnumQueryWrapper.select().orderByDesc("parentId").orderByAsc("enumCode");
        List<BasicEnum> list = basicEnumMapper.selectList(basicEnumQueryWrapper); //查询到所有正常数据

        if ( isQueryFristNode == null || !isQueryFristNode) {
            if (list != null && list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    BasicEnum firstNodeEnum = list.get(i);
                    List<BasicEnum> childrenList = this.getChildren(firstNodeEnum);
                    if (childrenList == null && childrenList.size() <= 0) {
                        continue;
                    }
                    firstNodeEnum.setChildren(childrenList);
                }
            }
        }
        return list;
    }

    @Override
    public List<BasicEnum> getAllParen() {
        return basicEnumMapper.getAllParen();
    }

    @Override
    public int getCountChildren(String enumId) {
        return basicEnumMapper.getCountChildren( enumId);
    }

    @Override
    public Boolean moveDepotEnum(String parentId) {
        List<Map<String,Object>> fristLevelList = basicEnumMapper.findEnumByDepot(parentId);
        for (int i = 0; i < fristLevelList.size(); i++) {
            Map<String,Object> map = fristLevelList.get(i);
            BasicEnum basicEnum = new BasicEnum();
            basicEnum.setEnumId(map.getOrDefault("enumId","").toString());
            basicEnum.setEnumCode(map.getOrDefault("enumcode","").toString());
            basicEnum.setEnumName(map.getOrDefault("enumname","").toString());
            basicEnum.setGbCode(map.getOrDefault("gbcode","").toString());
            basicEnum.setParentId(map.getOrDefault("parentId","").toString());
            this.saveOrUpdate(basicEnum);
            //保存下级
            saveNextLevel(map.getOrDefault("enumId","").toString());
        }
        return true;
    }

    private void saveNextLevel(String enumId) {
        List<Map<String,Object>> nextLevelList = basicEnumMapper.findEnumByDepot(enumId);
        if (nextLevelList.size() <=0){
            return;
        }
        for (int i = 0; i < nextLevelList.size(); i++) {
            Map<String,Object> map = nextLevelList.get(i);
            BasicEnum basicEnum = new BasicEnum();
            basicEnum.setEnumId(map.getOrDefault("enumId","").toString());
            basicEnum.setEnumName(map.getOrDefault("enumname","").toString());
            basicEnum.setEnumCode(map.getOrDefault("enumcode","").toString());
            basicEnum.setGbCode(map.getOrDefault("gbcode","").toString());
            basicEnum.setParentId(map.getOrDefault("parentId","").toString());
            this.saveOrUpdate(basicEnum);
            //保存下级
            saveNextLevel(map.getOrDefault("enumId","").toString());
        }
    }
}

