package com.ruoyi.cms.service.impl;

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

import com.alibaba.fastjson2.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.cms.constant.CommonConstant;
import com.ruoyi.cms.domain.SubwayLine;
import com.ruoyi.cms.util.JobTitleUtils;
import com.ruoyi.common.core.domain.TreeSelect;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import com.ruoyi.cms.mapper.JobTitleMapper;
import com.ruoyi.common.core.domain.entity.JobTitle;
import com.ruoyi.cms.service.IJobTitleService;

/**
 * 岗位Service业务层处理
 *
 * @author Lishundong
 * @date 2024-11-12
 */
@Service
public class JobTitleServiceImpl extends ServiceImpl<JobTitleMapper,JobTitle> implements IJobTitleService
{
    @Autowired
    private JobTitleMapper jobTitleMapper;

    /**
     * 查询岗位
     *
     * @param jobId 岗位主键
     * @return 岗位
     */
    @Override
    public JobTitle selectJobTitleByJobId(Long jobId)
    {
        return jobTitleMapper.selectById(jobId);
    }

    /**
     * 查询岗位列表
     *
     * @param jobTitle 岗位
     * @return 岗位
     */
    @Override
    public List<JobTitle> selectJobTitleList(JobTitle jobTitle)
    {
        return jobTitleMapper.selectJobTitleList(jobTitle);
    }

    /**
     * 新增岗位
     *
     * @param jobTitle 岗位
     * @return 结果
     */
    @Override
    public int insertJobTitle(JobTitle jobTitle)
    {
        int insert = jobTitleMapper.insert(jobTitle);
        if(insert>0){
            removeJobTitleCache();
        }
        return insert;
    }

    /**
     * 修改岗位
     *
     * @param jobTitle 岗位
     * @return 结果
     */
    @Override
    public int updateJobTitle(JobTitle jobTitle)
    {
        int i = jobTitleMapper.updateById(jobTitle);
        if(i>0){
            removeJobTitleCache();
        }
        return i;
    }

    /**
     * 批量删除岗位
     *
     * @param jobIds 需要删除的岗位主键
     * @return 结果
     */
    @Override
    public int deleteJobTitleByJobIds(Long[] jobIds)
    {
        int i = jobTitleMapper.deleteBatchIds(Arrays.asList(jobIds));
        if(i>0){
            removeJobTitleCache();
        }
        return i;
    }

    @Override
    public List<TreeSelect> buildJobTitleTreeSelect(List<JobTitle> jobTitleList) {
        List<JobTitle> jobTitleTree = buildJobTitleTree(jobTitleList);
        return jobTitleTree.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    private List<JobTitle> buildJobTitleTree(List<JobTitle> jobTitleList) {
        List<JobTitle> returnList = new ArrayList<JobTitle>();
        List<Long> tempList = jobTitleList.stream().map(JobTitle::getJobId).collect(Collectors.toList());
        for (Iterator<JobTitle> iterator = jobTitleList.iterator(); iterator.hasNext();)
        {
            JobTitle jobTitle = (JobTitle) iterator.next();
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(jobTitle.getParentId()))
            {
                recursionFn(jobTitleList, jobTitle);
                returnList.add(jobTitle);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = jobTitleList;
        }
        return returnList;
    }

    private void recursionFn(List<JobTitle> list, JobTitle t)
    {
        // 得到子节点列表
        List<JobTitle> childList = getChildList(list, t);
        t.setChildren(childList);
        for (JobTitle tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }
    private boolean hasChild(List<JobTitle> list, JobTitle t)
    {
        return getChildList(list, t).size() > 0;
    }
    /**
     * 得到子节点列表
     */
    private List<JobTitle> getChildList(List<JobTitle> list, JobTitle t)
    {
        List<JobTitle> tlist = new ArrayList<JobTitle>();
        Iterator<JobTitle> it = list.iterator();
        while (it.hasNext())
        {
            JobTitle n = (JobTitle) it.next();
            if (n.getParentId().longValue() == t.getJobId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }
    public static void removeJobTitleCache()
    {
        SpringUtils.getBean(RedisCache.class).deleteObject(CommonConstant.JOB_TITLE);
    }

    public static void setJobTitleCache(List<TreeSelect> jobTitleList)
    {
        SpringUtils.getBean(RedisCache.class).setCacheObject(CommonConstant.JOB_TITLE, jobTitleList);
    }

    public static List<TreeSelect> getJobTitleCache()
    {
        JSONArray arrayCache = SpringUtils.getBean(RedisCache.class).getCacheObject(CommonConstant.JOB_TITLE);
        if (StringUtils.isNotNull(arrayCache))
        {
            return arrayCache.toList(TreeSelect.class);
        }
        return null;
    }
    @Override
    public boolean hasChildByJobId(Long jobId) {
        return jobTitleMapper.selectCount(Wrappers.<JobTitle>lambdaQuery().eq(JobTitle::getParentId, jobId))>0;
    }

    @Override
    public List<TreeSelect> appJobTitle() {
        List<TreeSelect> jobTitleCache = getJobTitleCache();
        if(Objects.isNull(jobTitleCache))
        {
            List<JobTitle> jobTitleList = this.selectJobTitleList(null);
            return this.buildJobTitleTreeSelect(jobTitleList);
        }
        return jobTitleCache;
    }

    @Override
    public void importJobTitle() {
        // 读取 Excel 并构建树结构
        List<JobTitle> jobTitles = JobTitleUtils.readExcel("D:\\job_category_standard.xlsx");

        this.saveJobTitles(jobTitles);
    }
    /**
     * 存储 JobTitle 列表到数据库
     */
    public void saveJobTitles(List<JobTitle> jobTitles) {
        for (JobTitle jobTitle : jobTitles) {
            saveJobTitleRecursive(jobTitle);
        }
    }

    /**
     * 递归存储 JobTitle
     */
    private void saveJobTitleRecursive(JobTitle jobTitle) {
        jobTitleMapper.insert(jobTitle); // 存储当前节点
        for (JobTitle child : jobTitle.getChildren()) {
            saveJobTitleRecursive(child); // 递归存储子节点
        }
    }

    @Override
    public List<JobTitle> levelOne() {
        return jobTitleMapper.selectList(Wrappers.<JobTitle>lambdaQuery().eq(JobTitle::getParentId, 0l));
    }
}
