package com.ruoyi.doubledefense.service.impl;

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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.constant.DeletedEnum;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.doubledefense.domain.ContractorTreeSelect;
import com.ruoyi.doubledefense.dto.ContractorDTO;
import com.ruoyi.system.dto.ContractorUserDTO;
import com.ruoyi.system.service.IContractorUserService;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.doubledefense.mapper.ContractorMapper;
import com.ruoyi.doubledefense.domain.Contractor;
import com.ruoyi.doubledefense.service.IContractorService;
import org.springframework.util.CollectionUtils;

/**
 * 承包商Service业务层处理
 *
 * @author ruoyi
 * @date 2023-08-04
 */
@Service
public class ContractorServiceImpl implements IContractorService {
    @Autowired
    private ContractorMapper contractorMapper;

    @Autowired
    private IContractorUserService contractorUserService;

    /**
     * 查询承包商
     *
     * @param id 承包商主键
     * @return 承包商
     */
    @Override
    public ContractorDTO selectContractorById(String id) {
        Contractor contractor = contractorMapper.selectById(id);
        if (Objects.nonNull(contractor)) {
            ContractorDTO contractorDTO = new ContractorDTO();
            BeanUtils.copyProperties(contractor, contractorDTO);
            return contractorDTO;
        }
        return null;
    }

    /**
     * 查询承包商列表
     *
     * @param contractorDTO 承包商
     * @return 承包商
     */
    @Override
    public List<ContractorDTO> selectContractorList(ContractorDTO contractorDTO) {
        Contractor contractor = new Contractor();
        BeanUtils.copyProperties(contractorDTO, contractor);
        contractor.setIsDel(DeletedEnum.VALID.getValue());
        List<Contractor> contractorList = contractorMapper.selectContractorList(contractor);
        if (CollectionUtils.isEmpty(contractorList)) {
            return Lists.newArrayList();
        }
        List<ContractorDTO> contractorDTOList = new ArrayList<>();
        for (Contractor contractor1 : contractorList) {
            ContractorDTO contractorDTO1 = new ContractorDTO();
            BeanUtils.copyProperties(contractor1, contractorDTO1);
            contractorDTOList.add(contractorDTO1);
        }
        return contractorDTOList;
    }

    /**
     * 查询承包商tree并包含用户
     *
     * @param isNeedUser 是否装载用户
     * @return
     */
    @Override
    public List<ContractorTreeSelect> selectContractorTreeListForApp(boolean isNeedUser) {
        Contractor contractor = new Contractor();
        contractor.setIsDel(DeletedEnum.VALID.getValue());
        List<Contractor> contractorList = contractorMapper.selectContractorList(contractor);
        if (CollectionUtils.isEmpty(contractorList)) {
            return Lists.newArrayList();
        }
        if (isNeedUser) {
            ContractorUserDTO contractorUser = new ContractorUserDTO();
            List<ContractorUserDTO> userList = contractorUserService.selectContractorUserList(contractorUser);
            Map<Long, List<ContractorUserDTO>> userMap = userList.stream().collect(Collectors.groupingBy(ContractorUserDTO::getContractorId));
            for (Contractor data : contractorList) {
                Long id = data.getId();
                if (userMap.containsKey(id)) {
                    List<ContractorUserDTO> list = userMap.get(id);
                    List<Contractor.UserSimple> sysUserList = new ArrayList<>();
                    for (ContractorUserDTO user : list) {
                        Contractor.UserSimple userSimple = new Contractor.UserSimple();
                        userSimple.setUserId(user.getId());
                        userSimple.setNickName(user.getCompellation());
                        sysUserList.add(userSimple);
                    }
                    data.setSysUserList(sysUserList);
                }
            }
        }

        return buildContractorTreeSelect(contractorList);
    }


    /**
     * 查询部门树结构信息
     *
     * @param contractorList 部门信息
     * @return 部门树信息集合
     */
    private List<ContractorTreeSelect> buildContractorTreeSelect(List<Contractor> contractorList) {
        List<Contractor> deptTrees = buildContractorTree(contractorList);
        return deptTrees.stream().map(ContractorTreeSelect::new).collect(Collectors.toList());
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @param depts 部门列表
     * @return 下拉树结构列表
     */
    private List<Contractor> buildContractorTree(List<Contractor> depts) {
        List<Contractor> returnList = new ArrayList<>();
        List<Long> tempList = depts.stream().map(Contractor::getId).collect(Collectors.toList());
        for (Contractor dept : depts) {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(dept.getParentId())) {
                recursionFn(depts, dept);
                returnList.add(dept);
            }
        }
        if (returnList.isEmpty()) {
            returnList = depts;
        }
        return returnList;
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<Contractor> list, Contractor t) {
        // 得到子节点列表
        List<Contractor> childList = getChildList(list, t);
        t.setChildren(childList);
        for (Contractor tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<Contractor> getChildList(List<Contractor> list, Contractor t) {
        List<Contractor> tlist = new ArrayList<>();
        Iterator<Contractor> it = list.iterator();
        while (it.hasNext()) {
            Contractor n = it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getId().longValue()) {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<Contractor> list, Contractor t) {
        return getChildList(list, t).size() > 0;
    }


    /**
     * 新增承包商
     *
     * @param contractorDTO 承包商
     * @return 结果
     */
    @Override
    public int insertContractor(ContractorDTO contractorDTO) {
        Contractor contractor = new Contractor();
        BeanUtils.copyProperties(contractorDTO, contractor);
        contractor.setCreateDefault();
        return contractorMapper.insert(contractor);
    }

    /**
     * 修改承包商
     *
     * @param contractorDTO 承包商
     * @return 结果
     */
    @Override
    public int updateContractor(ContractorDTO contractorDTO) {
        Contractor contractor = new Contractor();
        BeanUtils.copyProperties(contractorDTO, contractor);
        contractor.setUpdateDefault();
        return contractorMapper.updateById(contractor);
    }

    /**
     * 批量删除承包商
     *
     * @param ids 需要删除的承包商主键
     * @return 结果
     */
    @Override
    public int deleteContractorByIds(String[] ids) {
        Contractor contractor = new Contractor();
        contractor.setIsDel(DeletedEnum.INVALID.getValue());
        contractor.setUpdateDefault();
        LambdaQueryWrapper<Contractor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Contractor::getId, ids);
        return contractorMapper.update(contractor, queryWrapper);
    }

}
