package com.jeeplus.pubmodules.reimApprovalType.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.jeeplus.common.TokenProvider;
import com.jeeplus.core.domain.BaseEntity;
import com.jeeplus.pubmodules.reimApprovalType.domain.CwReimbursementTypeInfo;
import com.jeeplus.pubmodules.reimApprovalType.domain.OfficeDomain;
import com.jeeplus.pubmodules.reimApprovalType.mapper.CwReimbursementTypeMapper;
import com.jeeplus.sys.feign.IUserApi;
import com.jeeplus.sys.service.dto.OfficeDTO;
import com.jeeplus.sys.service.dto.UserDTO;
//import com.jeeplus.test.materialManagement.materialType.domain.MaterialTypeInfo;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author: 王强
 * @create: 2022-11-25 09:13
 **/
@Service
public class CwReimbursementTypeService {

    @Resource
    private CwReimbursementTypeMapper mapper;

    public List<CwReimbursementTypeInfo> bxList2(CwReimbursementTypeInfo info) {
        LambdaQueryWrapper<CwReimbursementTypeInfo> wrapper = new LambdaQueryWrapper<>();
        if(StringUtils.isNotBlank(info.getName())){
            //根据type模糊查询
            List<CwReimbursementTypeInfo> cwReimbursementTypeInfoList = mapper.selectList(new QueryWrapper<CwReimbursementTypeInfo>().lambda()
                    .like(StringUtils.isNotBlank(info.getName()), CwReimbursementTypeInfo::getName, info.getName())
            );
            List<String> collect = cwReimbursementTypeInfoList.stream().map(CwReimbursementTypeInfo::getId).collect(Collectors.toList());
            //materialTypeInfoList的父级id全部获取
            List<String> cupIdList = cwReimbursementTypeInfoList.stream().map(CwReimbursementTypeInfo::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 -> {
                    CwReimbursementTypeInfo byId = mapper.selectById(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<CwReimbursementTypeInfo> list = mapper.selectList(new LambdaQueryWrapper<CwReimbursementTypeInfo>().eq(CwReimbursementTypeInfo::getParentId, item));
                if (CollectionUtil.isNotEmpty(list)) {
                    List<String> collect1 = list.stream().map(CwReimbursementTypeInfo::getId).collect(Collectors.toList()).stream().distinct().collect(Collectors.toList());
                    if (CollectionUtil.isNotEmpty(collect1)) {
                        childIdList.addAll(collect1);
                        //获取collect的下级的下级的id
                        collect1.stream().forEach(i -> {
                            List<CwReimbursementTypeInfo> l = mapper.selectList(new LambdaQueryWrapper<CwReimbursementTypeInfo>().eq(CwReimbursementTypeInfo::getParentId, i));
                            if (CollectionUtil.isNotEmpty(l)) {
                                List<String> collect2 = l.stream().map(CwReimbursementTypeInfo::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(CwReimbursementTypeInfo::getId,idList);
            }else{
                return new ArrayList<>();
            }
        }
        if (ObjectUtil.isNotEmpty(info)) {
            if (StringUtils.isNotBlank(info.getLike())){
                wrapper.likeRight(CwReimbursementTypeInfo::getSort,info.getLike());
            }
        }
//        if (info.getSort() != null) {
//            wrapper.like(CwReimbursementTypeInfo::getSort, info.getSort());
//        }

        wrapper.eq(BaseEntity::getDelFlag, 0);
        wrapper.orderByAsc(CwReimbursementTypeInfo::getSort);
        //查当前登陆人的父级部门的id为江苏兴光的
//        OfficeDomain officeInfo = mapper.officeInfo(info.getOfficeId());
//        if (null != officeInfo && officeInfo.getGrade().equals("2")){
//            info.setOfficeId(officeInfo.getId());
//        } else if (null != officeInfo && officeInfo.getGrade().equals("3")) {
//            officeInfo = mapper.officeInfo2(officeInfo.getId());
//            if (null != officeInfo){
//                info.setOfficeId(officeInfo.getId());
//            }
//        }
        //使用递归的方式来查当前登陆人部门父节点信息
        List<OfficeDomain> officeDomains = mapper.officeInfo3(info.getOfficeId());
        if (null != officeDomains && officeDomains.size()>0){
            for (int i=0;i<officeDomains.size()-1;i++){
                //当get(i)的父级id与 i+1的id相同，并且i+的部门层级为1的时候
                if (officeDomains.get(i).getParentId().equals(officeDomains.get(i+1).getId()) && StringUtils.isNotBlank(officeDomains.get(i+1).getGrade()) &&
                        officeDomains.get(i+1).getGrade().equals("1")){
                    info.setOfficeId(officeDomains.get(i).getId());
                }
            }
        }
        return mapper.bxList2(wrapper,info.getOfficeId());
    }

    public List<CwReimbursementTypeInfo> list(CwReimbursementTypeInfo info) {
        QueryWrapper<CwReimbursementTypeInfo> wrapper = new QueryWrapper<>();
        if(StringUtils.isNotBlank(info.getName())){
            //根据type模糊查询
            List<CwReimbursementTypeInfo> cwReimbursementTypeInfoList = mapper.selectList(new QueryWrapper<CwReimbursementTypeInfo>().lambda()
                    .like(StringUtils.isNotBlank(info.getName()), CwReimbursementTypeInfo::getName, info.getName())
            );
            List<String> collect = cwReimbursementTypeInfoList.stream().map(CwReimbursementTypeInfo::getId).collect(Collectors.toList());
            //materialTypeInfoList的父级id全部获取
            List<String> cupIdList = cwReimbursementTypeInfoList.stream().map(CwReimbursementTypeInfo::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 -> {
                    CwReimbursementTypeInfo byId = mapper.selectById(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<CwReimbursementTypeInfo> list = mapper.selectList(new LambdaQueryWrapper<CwReimbursementTypeInfo>().eq(CwReimbursementTypeInfo::getParentId, item));
                if (CollectionUtil.isNotEmpty(list)) {
                    List<String> collect1 = list.stream().map(CwReimbursementTypeInfo::getId).collect(Collectors.toList()).stream().distinct().collect(Collectors.toList());
                    if (CollectionUtil.isNotEmpty(collect1)) {
                        childIdList.addAll(collect1);
                        //获取collect的下级的下级的id
                        collect1.stream().forEach(i -> {
                            List<CwReimbursementTypeInfo> l = mapper.selectList(new LambdaQueryWrapper<CwReimbursementTypeInfo>().eq(CwReimbursementTypeInfo::getParentId, i));
                            if (CollectionUtil.isNotEmpty(l)) {
                                List<String> collect2 = l.stream().map(CwReimbursementTypeInfo::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("a.id",idList);
            }else{
                return new ArrayList<>();
            }
        }
//        wrapper.eq(CwReimbursementTypeInfo::getBusinessType, "1");

        wrapper.eq("a.del_flag", 0);
        wrapper.orderByAsc("a.sort");
        return mapper.findList(wrapper);
    }


    /**
     * 根据id查询项目详情
     * @param id
     * @return
     */
    public CwReimbursementTypeInfo getById(String id) {
        CwReimbursementTypeInfo info = mapper.getById(id);
        if( null != info && null != info.getOfficeDTOList() && info.getOfficeDTOList().size()>0){
            List<String> officeIdList = Lists.newArrayList();
            for (OfficeDTO office : info.getOfficeDTOList()) {
                officeIdList.add(office.getId());
            }
            info.setOfficeIdList(officeIdList);
        }
        return info;
    }

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

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

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

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

    public String save(CwReimbursementTypeInfo 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(CwReimbursementTypeInfo 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.setCreateById(userDto.getId());
        info.setCreateTime(new Date());
        info.setUpdateById(userDto.getId());
        info.setUpdateTime(new Date());
        info.setDelFlag(0);
        // 生成序号/层级
        getNo(info);
        //对关联的公司id进行处理
        if (null != info.getOfficeIdList() && info.getOfficeIdList().size()>0) {
            //首先删除原有关联信息
            mapper.deleteReimbursementTypeOfficeInfo(info.getId());
            //将新的关联信息进行保存
            mapper.saveReimbursementTypeOfficeInfo(info.getId(),info.getOfficeIdList());
        }
        info.setOfficeIdList(null);
        mapper.insert(info);
        return "操作完成";
    }

    /**
     * 修改
     * @param info
     * @return
     */
    public String update(CwReimbursementTypeInfo info) {
        // 获取当前登录人信息
        UserDTO userDto = SpringUtil.getBean(IUserApi.class).getByToken(TokenProvider.getCurrentToken ( ));
//        UserDTO userDto = UserUtils.getCurrentUserDTO();
        info.setUpdateById(userDto.getId());
        info.setUpdateTime(new Date());
        //对关联的公司id进行处理
        if (null != info.getOfficeIdList() && info.getOfficeIdList().size()>0) {
            //首先删除原有关联信息
            mapper.deleteReimbursementTypeOfficeInfo(info.getId());
            //将新的关联信息进行保存
            mapper.saveReimbursementTypeOfficeInfo(info.getId(),info.getOfficeIdList());
//            info.setOfficeIdList(null);
        } else if (null != info.getOfficeIdList() && info.getOfficeIdList().isEmpty()){
            //首先删除原有关联信息
            mapper.deleteReimbursementTypeOfficeInfo(info.getId());
        }
        info.setOfficeIdList(null);
        mapper.updateById(info);
        return "操作完成";
    }

    /**
     * 生成序号/层级
     * @param info
     * @return
     */
    public CwReimbursementTypeInfo getNo(CwReimbursementTypeInfo info) {
        CwReimbursementTypeInfo parentInfo = null;
        if (!"0".equals(info.getParentId())) {
            //根据parentId查询父节点信息
            LambdaQueryWrapper<CwReimbursementTypeInfo> 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;
    }
}
