/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package com.unis.basic.info.modular.enumInfo.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.unis.basic.info.modular.enumInfo.entity.BasicEnum;
import com.unis.basic.info.modular.enumInfo.mapper.BasicEnumMapper;
import com.unis.basic.info.modular.enumInfo.param.BasicEnumAddParam;
import com.unis.basic.info.modular.enumInfo.param.BasicEnumEditParam;
import com.unis.basic.info.modular.enumInfo.param.BasicEnumIdParam;
import com.unis.basic.info.modular.enumInfo.param.BasicEnumPageParam;
import com.unis.basic.info.modular.enumInfo.service.BasicEnumService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.unis.common.enums.CommonSortOrderEnum;
import com.unis.common.exception.CommonException;
import com.unis.common.page.CommonPageRequest;


import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 数据字典大类Service接口实现类
 *
 * @author shine
 * @date  2024/05/10 14:06
 **/
@Service
public class BasicEnumServiceImpl extends ServiceImpl<BasicEnumMapper, BasicEnum> implements BasicEnumService {

    @Resource
    private BasicEnumMapper basicEnumMapper;

    @Override
    public Page<BasicEnum> page(BasicEnumPageParam basicEnumPageParam) {
        QueryWrapper<BasicEnum> queryWrapper = new QueryWrapper<>();
        if(ObjectUtil.isNotEmpty(basicEnumPageParam.getEnumname())) {
            queryWrapper.lambda().like(BasicEnum::getEnumname, basicEnumPageParam.getEnumname());
        }
        if(ObjectUtil.isNotEmpty(basicEnumPageParam.getParentid())) {
            queryWrapper.lambda().eq(BasicEnum::getParentid, basicEnumPageParam.getParentid());
        }
        if(ObjectUtil.isNotEmpty(basicEnumPageParam.getDelflag())) {
            queryWrapper.lambda().eq(BasicEnum::getDelflag, basicEnumPageParam.getDelflag());
        }
        if(ObjectUtil.isAllNotEmpty(basicEnumPageParam.getSortField(), basicEnumPageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(basicEnumPageParam.getSortOrder());
            queryWrapper.orderBy(true, basicEnumPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(basicEnumPageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByAsc(BasicEnum::getEnumid);
        }
        return this.page(CommonPageRequest.defaultPage(), queryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(BasicEnumAddParam basicEnumAddParam) {
        BasicEnum basicEnum = BeanUtil.toBean(basicEnumAddParam, BasicEnum.class);
        this.save(basicEnum);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(BasicEnumEditParam basicEnumEditParam) {
        BasicEnum basicEnum = this.queryEntity(basicEnumEditParam.getEnumid().toString());
        BeanUtil.copyProperties(basicEnumEditParam, basicEnum);
        this.updateById(basicEnum);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<BasicEnumIdParam> basicEnumIdParamList) {
        // 执行删除
        this.removeByIds(CollStreamUtil.toList(basicEnumIdParamList, BasicEnumIdParam::getEnumid));
    }

    @Override
    public BasicEnum detail(BasicEnumIdParam basicEnumIdParam) {
        return this.queryEntity(basicEnumIdParam.getEnumid().toString());
    }

    @Override
    public BasicEnum queryEntity(String id) {
        BasicEnum basicEnum = this.getById(id);
        if(ObjectUtil.isEmpty(basicEnum)) {
            throw new CommonException("数据字典大类不存在，id值为：{}", id);
        }
        return basicEnum;
    }

    @Override
    public Map<Integer, List<BasicEnum>> findEnumObjParentId() {

        QueryWrapper<BasicEnum> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(BasicEnum::getDelflag, 1);
        queryWrapper.lambda().orderByAsc(BasicEnum::getEnumid);

        List<BasicEnum> list = basicEnumMapper.selectList(queryWrapper);

        Map<Integer, List<BasicEnum>> resultMap = new HashMap<>();

        List<Integer> parentIds = new ArrayList<Integer>();
        for (BasicEnum be : list) {
            if (!parentIds.contains(be.getParentid())) {
                parentIds.add(be.getParentid());
            }
        }

        for (Integer parentId : parentIds) {
            List<BasicEnum> children = this.getChildren(list, parentId,null);
            resultMap.put(parentId, children);
        }
        return resultMap;
    }

    private List<BasicEnum> getChildren(List<BasicEnum> list, Integer parentId,String planManage) {
        List<BasicEnum> children = new ArrayList<BasicEnum>();
        //计划管理下面的计划 粮食性质去掉储备粮的
        if(planManage!=null && planManage.equals("0")){
            for(BasicEnum be: list){
                //遍历出父id等于参数的id，add进子节点集合  除去储备粮=3045的和父节点是储备粮的
                if (be.getParentid().equals(parentId) && !be.getParentid().equals(3045) && !be.getEnumid().equals(3045)) {
                    children.add(be);
                }
            }
        } else {
            for(BasicEnum be: list){
                //遍历出父id等于参数的id，add进子节点集合
                if (be.getParentid().equals(parentId)) {
                    children.add(be);
                }
            }
        }
        return children;
    }

    @Override
    public Map<Object, Object> findEnumObjEnumId() {

        QueryWrapper<BasicEnum> queryWrapper = new QueryWrapper<>();
        //queryWrapper.lambda().eq(BasicEnum::getDelflag, 1);
        queryWrapper.lambda().orderByAsc(BasicEnum::getEnumid);

        List<BasicEnum> list = basicEnumMapper.selectList(queryWrapper);

        Map<Object, Object> map = new HashMap<Object, Object>();
        Integer enumId = null;
        for (BasicEnum be : list) {
            enumId = be.getEnumid();
            map.put(enumId, be.getEnumname());
        }

        return map;
    }

    @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;
    }

    private List<BasicEnum> getChildren(BasicEnum node) {
        Integer 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;
    }

}
