package com.jeeplus.psimanage.materialType.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jeeplus.common.TokenProvider;
import com.jeeplus.core.domain.BaseEntity;
import com.jeeplus.psimanage.materialType.domain.PsiMaterialTypeInfo;
import com.jeeplus.psimanage.materialType.mapper.PsiMaterialTypeMapper;
import com.jeeplus.sys.feign.IUserApi;
import com.jeeplus.sys.service.dto.UserDTO;
import com.jeeplus.utils.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * @author: 王强
 * @create: 2022-11-25 09:13
 **/
@Service
public class PsiMaterialTypeService extends ServiceImpl<PsiMaterialTypeMapper, PsiMaterialTypeInfo> {

    @Resource
    private PsiMaterialTypeMapper mapper;

    public List<PsiMaterialTypeInfo> list(PsiMaterialTypeInfo info) {
        LambdaQueryWrapper<PsiMaterialTypeInfo> wrapper = new LambdaQueryWrapper<>();
        if(StringUtils.isNotBlank(info.getName())){
            //根据type模糊查询
            List<PsiMaterialTypeInfo> materialTypeInfoList = this.list(new QueryWrapper<PsiMaterialTypeInfo>().lambda()
                    .like(StringUtils.isNotBlank(info.getName()), PsiMaterialTypeInfo::getName, info.getName())
            );
            List<String> collect = materialTypeInfoList.stream().map(PsiMaterialTypeInfo::getId).collect(Collectors.toList());
            //materialTypeInfoList的父级id全部获取
            List<String> cupIdList = materialTypeInfoList.stream().map(PsiMaterialTypeInfo::getParentId).collect(Collectors.toList()).stream().distinct().collect(Collectors.toList());
            //获取materialTypeInfoList的父级id的父级id
            List<String> cupIdPList = new ArrayList<>();
            if (CollectionUtil.isNotEmpty(cupIdList)) {
                cupIdList.stream().forEach(item -> {
                    PsiMaterialTypeInfo byId = this.getById(item);
                    if (ObjectUtil.isNotEmpty(byId)) {
                        if (StringUtils.isNotBlank(byId.getParentId())) {
                            cupIdPList.add(byId.getParentId());
                        }
                    }
                });
            }
            //获取collect的下级id
            List<String> childIdList = new ArrayList<>();
            collect.stream().forEach(item -> {
                List<PsiMaterialTypeInfo> list = this.list(new LambdaQueryWrapper<PsiMaterialTypeInfo>().eq(PsiMaterialTypeInfo::getParentId, item));
                if (CollectionUtil.isNotEmpty(list)) {
                    List<String> collect1 = list.stream().map(PsiMaterialTypeInfo::getId).collect(Collectors.toList()).stream().distinct().collect(Collectors.toList());
                    if (CollectionUtil.isNotEmpty(collect1)) {
                        childIdList.addAll(collect1);
                        //获取collect的下级的下级的id
                        collect1.stream().forEach(i -> {
                            List<PsiMaterialTypeInfo> l = this.list(new LambdaQueryWrapper<PsiMaterialTypeInfo>().eq(PsiMaterialTypeInfo::getParentId, i));
                            if (CollectionUtil.isNotEmpty(l)) {
                                List<String> collect2 = l.stream().map(PsiMaterialTypeInfo::getId).collect(Collectors.toList()).stream().distinct().collect(Collectors.toList());
                                if (CollectionUtil.isNotEmpty(collect2)) {
                                    childIdList.addAll(collect2);
                                }
                            }
                        });
                    }
                }
            });
            //将获取到的这几个id集合融合到一起并去重，然后根据id查询，即可得到结果
            collect.addAll(cupIdList);
            collect.addAll(cupIdPList);
            collect.addAll(childIdList);

            List<String> idList = collect.stream().distinct().collect(Collectors.toList());
            if(CollectionUtil.isNotEmpty(idList)){
                wrapper.in(PsiMaterialTypeInfo::getId,idList);
            }
        }
//        if (info.getSort() != null) {
//            wrapper.like(MaterialTypeInfo::getSort, info.getSort());
//        }
//        wrapper.eq(CwReimbursementTypeInfo::getBusinessType, "1");

        wrapper.eq(BaseEntity::getDelFlag, 0);
        wrapper.orderByAsc(PsiMaterialTypeInfo::getSort);
        return mapper.findList(wrapper);
    }


    /**
     * 根据id查询项目详情
     * @param id
     * @return
     */
    public PsiMaterialTypeInfo getById(String id) {
        PsiMaterialTypeInfo info = mapper.getById(id);
        return info;
    }

    public List<PsiMaterialTypeInfo> bxList(PsiMaterialTypeInfo info) {
        LambdaQueryWrapper<PsiMaterialTypeInfo> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotEmpty(info.getName())) {
            wrapper.like(PsiMaterialTypeInfo::getName, info.getName());
        }
        if (info.getSort() != null) {
            wrapper.like(PsiMaterialTypeInfo::getSort, info.getSort());
        }

        wrapper.eq(BaseEntity::getDelFlag, 0);
        wrapper.orderByAsc(PsiMaterialTypeInfo::getSort);
        return mapper.selectList(wrapper);
    }

    public List<PsiMaterialTypeInfo> cgList(PsiMaterialTypeInfo info) {
        LambdaQueryWrapper<PsiMaterialTypeInfo> wrapper = new LambdaQueryWrapper<>();
        if(StringUtils.isNotBlank(info.getName())){
            //根据type模糊查询
            List<PsiMaterialTypeInfo> materialTypeInfoList = this.list(new QueryWrapper<PsiMaterialTypeInfo>().lambda()
                    .like(StringUtils.isNotBlank(info.getName()), PsiMaterialTypeInfo::getName, info.getName())
            );
            List<String> collect = materialTypeInfoList.stream().map(PsiMaterialTypeInfo::getId).collect(Collectors.toList());
            //materialTypeInfoList的父级id全部获取
            List<String> cupIdList = materialTypeInfoList.stream().map(PsiMaterialTypeInfo::getParentId).collect(Collectors.toList()).stream().distinct().collect(Collectors.toList());
            //获取materialTypeInfoList的父级id的父级id
            List<String> cupIdPList = new ArrayList<>();
            if (CollectionUtil.isNotEmpty(cupIdList)) {
                cupIdList.stream().forEach(item -> {
                    PsiMaterialTypeInfo byId = this.getById(item);
                    if (ObjectUtil.isNotEmpty(byId)) {
                        if (StringUtils.isNotBlank(byId.getParentId())) {
                            cupIdPList.add(byId.getParentId());
                        }
                    }
                });
            }
            //获取collect的下级id
            List<String> childIdList = new ArrayList<>();
            collect.stream().forEach(item -> {
                List<PsiMaterialTypeInfo> list = this.list(new LambdaQueryWrapper<PsiMaterialTypeInfo>().eq(PsiMaterialTypeInfo::getParentId, item));
                if (CollectionUtil.isNotEmpty(list)) {
                    List<String> collect1 = list.stream().map(PsiMaterialTypeInfo::getId).collect(Collectors.toList()).stream().distinct().collect(Collectors.toList());
                    if (CollectionUtil.isNotEmpty(collect1)) {
                        childIdList.addAll(collect1);
                        //获取collect的下级的下级的id
                        collect1.stream().forEach(i -> {
                            List<PsiMaterialTypeInfo> l = this.list(new LambdaQueryWrapper<PsiMaterialTypeInfo>().eq(PsiMaterialTypeInfo::getParentId, i));
                            if (CollectionUtil.isNotEmpty(l)) {
                                List<String> collect2 = l.stream().map(PsiMaterialTypeInfo::getId).collect(Collectors.toList()).stream().distinct().collect(Collectors.toList());
                                if (CollectionUtil.isNotEmpty(collect2)) {
                                    childIdList.addAll(collect2);
                                }
                            }
                        });
                    }
                }
            });
            //将获取到的这几个id集合融合到一起并去重，然后根据id查询，即可得到结果
            collect.addAll(cupIdList);
            collect.addAll(cupIdPList);
            collect.addAll(childIdList);

            List<String> idList = collect.stream().distinct().collect(Collectors.toList());
            if(CollectionUtil.isNotEmpty(idList)){
                wrapper.in(PsiMaterialTypeInfo::getId,idList);
            }
        }

        wrapper.eq(BaseEntity::getDelFlag, 0);
        wrapper.orderByAsc(PsiMaterialTypeInfo::getSort);
        return mapper.selectList(wrapper);
    }

    public String saveM(PsiMaterialTypeInfo info) {
        // parentId未传值，则表示一级菜单
        if(StringUtils.isEmpty(info.getParentId())) {
            info.setParentId("0");
        }
        // 保存数据
        if (StringUtils.isNotEmpty(info.getId())) {
            return update(info);
        }
        return add(info);
    }

    /**
     * 新增
     * @param info
     * @return
     */
    public String add(PsiMaterialTypeInfo info) {

        // 判断名称是否已存在
        Integer isExist = mapper.checkNameIsExist(info.getName(), info.getParentId());
        if (isExist > 0) {
            return "false";
        }
        // 获取当前登录人信息
        UserDTO userDto = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken ( ));
//        UserDTO userDto = UserUtils.getCurrentUserDTO();
        // 生成id值
        String id = UUID.randomUUID().toString().replace("-", "");
        info.setId(id);
        info.setCreateBy(userDto.getId());
        info.setCreateDate(new Date());
        info.setUpdateBy(userDto.getId());
        info.setUpdateDate(new Date());
        info.setDelFlag(0);
        // 生成序号/层级
        getNo(info);
        mapper.insert(info);
        return "操作完成";
    }

    /**
     * 修改
     * @param info
     * @return
     */
    public String update(PsiMaterialTypeInfo info) {
        UserDTO userDto = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken ( ));
        // 获取当前登录人信息
//        UserDTO userDto = UserUtils.getCurrentUserDTO();
        info.setUpdateBy(userDto.getId());
        info.setUpdateDate(new Date());
        mapper.updateById(info);
        return "操作完成";
    }

    /**
     * 生成序号/层级
     * @param info
     * @return
     */
    public PsiMaterialTypeInfo getNo(PsiMaterialTypeInfo info) {
        PsiMaterialTypeInfo parentInfo = null;
        if (!"0".equals(info.getParentId())) {
            //根据parentId查询父节点信息
            LambdaQueryWrapper<PsiMaterialTypeInfo> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(BaseEntity::getDelFlag, 0);
            wrapper.eq(BaseEntity::getId, info.getParentId());
            parentInfo = mapper.selectOne(wrapper);
        }
        //查询序号
        Integer no = mapper.getNo(info.getParentId());
        // 该层级下有数据，正常返回序号值
        if (no != null) {
            info.setSort(no);
        } else {
            // 父节点存在，根据父节点序号生成；不存在，则表示无上级层级，从1开始
            if (parentInfo != null) {
                String s = parentInfo.getSort() + "01";
                info.setSort(Integer.parseInt(s));
            } else {
                info.setSort(1);
            }
        }
        // 生成层级
        //查询层级
        Integer level = mapper.getLevel(info.getParentId());
        if (level != null) {
            info.setLevel(level.toString());
        } else {
            // 父节点存在，根据父节点level生成，不存在，则表示无上级层级，从1开始
            if (parentInfo != null) {
                Integer i = Integer.parseInt(parentInfo.getLevel())+1;
                info.setLevel(i.toString());
            } else {
                info.setLevel("1");
            }
        }
        return info;
    }

    public String remove(String id) {
        //如果层级是一级或者是二级，则应该将一级下的所有信息删除或二级下的所有信息删除，反之为三级则直接删除
        PsiMaterialTypeInfo typeInfo = mapper.getById(id);
        if (typeInfo.getLevel().equals("1")){
            //三个层级的情况
            mapper.deleteLevel3(id);
            //删除二级的信息
            mapper.deleteLevel2(id);
            //删除一级的信息
            mapper.deleteById(id);
        } else if (typeInfo.getLevel().equals("2")) {
            //两个层级的情况
            mapper.deleteLevel2(id);
            //删除二级的信息
            mapper.deleteById(id);
        } else if (typeInfo.getLevel().equals("3")) {
            mapper.deleteById(id);
        }
        return "操作成功";
    }
}
