package com.xinelu.manage.service.agencycategory.impl;

import com.xinelu.common.constant.Constants;
import com.xinelu.common.utils.SecurityUtils;
import com.xinelu.common.utils.StringUtils;
import com.xinelu.common.utils.codes.GenerateSystemCodeUtil;
import com.xinelu.manage.domain.agencycategory.AgencyCategory;
import com.xinelu.manage.mapper.agencycategory.AgencyCategoryMapper;
import com.xinelu.manage.service.agencycategory.IAgencyCategoryService;
import com.xinelu.manage.vo.agencycategory.AgencyCategoryTreeVO;
import com.xinelu.manage.vo.agencycategory.AgencyCategoryVO;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;


/**
 * 机构类别Service业务层处理
 *
 * @author xinelu
 * @date 2024-02-26
 */
@Service
public class AgencyCategoryServiceImpl implements IAgencyCategoryService {
    @Resource
    private AgencyCategoryMapper agencyCategoryMapper;
    @Resource
    private GenerateSystemCodeUtil generateSystemCodeUtil;

    /**
     * 查询机构类别
     *
     * @param id 机构类别主键
     * @return 机构类别
     */
    @Override
    public AgencyCategory selectAgencyCategoryById(Long id) {
        return agencyCategoryMapper.selectAgencyCategoryById(id);
    }

    /**
     * 查询机构类别列表
     *
     * @param agencyCategory 机构类别
     * @return 机构类别
     */
    @Override
    public List<AgencyCategory> selectAgencyCategoryList(AgencyCategory agencyCategory) {
        return agencyCategoryMapper.selectAgencyCategoryList(agencyCategory);
    }

    /**
     * 新增机构类别
     *
     * @param agencyCategory 机构类别
     * @return 结果
     */
    @Override
    public int insertAgencyCategory(AgencyCategory agencyCategory) {
        if (Objects.nonNull(agencyCategory.getParentCategoryId())) {
            AgencyCategory parentAgencyCategory = agencyCategoryMapper.selectAgencyCategoryById(agencyCategory.getParentCategoryId());
            agencyCategory.setCategoryLevel((parentAgencyCategory.getCategoryLevel() == null ? 0 : parentAgencyCategory.getCategoryLevel()) + 1);
        }
        agencyCategory.setCreateTime(LocalDateTime.now());
        agencyCategory.setCreateBy(SecurityUtils.getUsername());
        agencyCategory.setCategoryCode(Constants.CATEGORY_CODE + generateSystemCodeUtil.generateSystemCode(Constants.CATEGORY_CODE));
        return agencyCategoryMapper.insertAgencyCategory(agencyCategory);
    }

    /**
     * 修改机构类别
     *
     * @param agencyCategory 机构类别
     * @return 结果
     */
    @Override
    public int updateAgencyCategory(AgencyCategory agencyCategory) {
        agencyCategory.setUpdateTime(LocalDateTime.now());
        agencyCategory.setUpdateBy(SecurityUtils.getUsername());
        return agencyCategoryMapper.updateAgencyCategory(agencyCategory);
    }

    /**
     * 批量删除机构类别
     *
     * @param ids 需要删除的机构类别主键
     * @return 结果
     */
    @Override
    public int deleteAgencyCategoryByIds(Long[] ids) {
        return agencyCategoryMapper.deleteAgencyCategoryByIds(ids);
    }

    /**
     * 删除机构类别信息
     *
     * @param id 机构类别主键
     * @return 结果
     */
    @Override
    public int deleteAgencyCategoryById(Long id) {
        return agencyCategoryMapper.deleteAgencyCategoryById(id);
    }

    /**
     * 查询机构类别信息列表 - 树图
     *
     * @return AgencyCategoryVO
     */
    @Override
    public List<AgencyCategoryTreeVO> agencyCategoryList() {
        List<AgencyCategoryVO> agencyCategoryList = agencyCategoryMapper.selectAgencyCategoryVOList(null);
        for (AgencyCategoryVO agencyCategory : agencyCategoryList) {
            agencyCategory.setValue(agencyCategory.getId());
        }
        List<AgencyCategoryVO> agencyTree = buildDeptTree(agencyCategoryList);
        return agencyTree.stream().map(AgencyCategoryTreeVO::new).collect(Collectors.toList());
    }

    public List<AgencyCategoryVO> buildDeptTree(List<AgencyCategoryVO> agencyCategoryList) {
        List<AgencyCategoryVO> returnList = new ArrayList<AgencyCategoryVO>();
        List<Long> tempList = new ArrayList<Long>();
        for (AgencyCategoryVO agencyCategory : agencyCategoryList) {
            tempList.add(agencyCategory.getId());
        }
        for (AgencyCategoryVO agencyCategory : agencyCategoryList) {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(agencyCategory.getParentCategoryId())) {
                recursionFn(agencyCategoryList, agencyCategory);
                returnList.add(agencyCategory);
            }
        }
        if (returnList.isEmpty()) {
            returnList = agencyCategoryList;
        }
        return returnList;
    }

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

    private List<AgencyCategoryVO> getChildList(List<AgencyCategoryVO> list, AgencyCategoryVO t) {
        List<AgencyCategoryVO> tlist = new ArrayList<AgencyCategoryVO>();
        Iterator<AgencyCategoryVO> it = list.iterator();
        while (it.hasNext()) {
            AgencyCategoryVO n = (AgencyCategoryVO) it.next();
            if (StringUtils.isNotNull(n.getParentCategoryId()) && n.getParentCategoryId().longValue() == t.getId().longValue()) {
                tlist.add(n);
            }
        }
        return tlist;
    }

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