package com.ruoyi.cms.service.impl;

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

import com.alibaba.fastjson2.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.cms.constant.CommonConstant;
import com.ruoyi.cms.domain.JobApply;
import com.ruoyi.cms.util.IndustryUtils;
import com.ruoyi.common.core.domain.TreeSelect;
import com.ruoyi.common.core.domain.entity.Industry;
import com.ruoyi.common.core.domain.entity.Industry;
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.IndustryMapper;
import com.ruoyi.cms.service.IIndustryService;

/**
 * 行业Service业务层处理
 *
 * @author LishunDong
 * @date 2024-11-12
 */
@Service
public class IndustryServiceImpl extends ServiceImpl<IndustryMapper,Industry> implements IIndustryService
{
    @Autowired
    private IndustryMapper industryMapper;

    /**
     * 查询行业
     *
     * @param industryId 行业主键
     * @return 行业
     */
    @Override
    public Industry selectIndustryByIndustryId(Long industryId)
    {
        return industryMapper.selectById(industryId);
    }

    /**
     * 查询行业列表
     *
     * @param industry 行业
     * @return 行业
     */
    @Override
    public List<Industry> selectIndustryList(Industry industry)
    {
        return industryMapper.selectIndustryList(industry);
    }

    /**
     * 新增行业
     *
     * @param industry 行业
     * @return 结果
     */
    @Override
    public int insertIndustry(Industry industry)
    {
        int insert = industryMapper.insert(industry);
        if(insert>0){
            removeIndustryCache();
        }
        return insert;
    }

    /**
     * 修改行业
     *
     * @param industry 行业
     * @return 结果
     */
    @Override
    public int updateIndustry(Industry industry)
    {
        int i = industryMapper.updateById(industry);
        if(i>0){
            removeIndustryCache();
        }
        return i;
    }

    /**
     * 批量删除行业
     *
     * @param industryIds 需要删除的行业主键
     * @return 结果
     */
    @Override
    public int deleteIndustryByIndustryIds(Long[] industryIds)
    {
        int i = industryMapper.deleteBatchIds(Arrays.asList(industryIds));
        if(i>0){
            removeIndustryCache();
        }
        return i;
    }

    @Override
    public List<TreeSelect> buildIndustryTreeSelect(List<Industry> industryList) {
        List<Industry> industryTree = buildIndustryTree(industryList);
        return industryTree.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

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

    private void recursionFn(List<Industry> list, Industry t)
    {
        // 得到子节点列表
        List<Industry> childList = getChildList(list, t);
        t.setChildren(childList);
        for (Industry tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }
    /**
     * 得到子节点列表
     */
    private List<Industry> getChildList(List<Industry> list, Industry t)
    {
        List<Industry> tlist = new ArrayList<Industry>();
        Iterator<Industry> it = list.iterator();
        while (it.hasNext())
        {
            Industry n = (Industry) it.next();
            if (n.getParentId().longValue() == t.getIndustryId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

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

    @Override
    public boolean hasChildByIndustryId(Long industryId) {
        return industryMapper.selectCount(Wrappers.<Industry>lambdaQuery().eq(Industry::getParentId, industryId))>0;
    }
    public static void removeIndustryCache()
    {
        SpringUtils.getBean(RedisCache.class).deleteObject(CommonConstant.JOB_TITLE);
    }

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

    public static List<TreeSelect> getIndustryCache()
    {
        JSONArray arrayCache = SpringUtils.getBean(RedisCache.class).getCacheObject(CommonConstant.JOB_TITLE);
        if (StringUtils.isNotNull(arrayCache))
        {
            return arrayCache.toList(TreeSelect.class);
        }
        return null;
    }
    @Override
    public List<TreeSelect> appIndustry() {
        List<TreeSelect> industryCache = getIndustryCache();
        if(Objects.isNull(industryCache))
        {
            List<Industry> jobTitleList = this.selectIndustryList(null);
            return this.buildIndustryTreeSelect(jobTitleList);
        }
        return industryCache;
    }

    @Override
    public void importData() {
        // 读取 Excel 并构建树结构
        List<Industry> industries = IndustryUtils.readExcel("D:\\indus.xlsx");

        // 存储到数据库
        this.saveIndustries(industries);
    }

    /**
     * 存储 Industry 列表到数据库
     */
    public void saveIndustries(List<Industry> industries) {
        for (Industry industry : industries) {
            saveIndustryRecursive(industry);
        }
    }

    /**
     * 递归存储 Industry
     */
    private void saveIndustryRecursive(Industry industry) {
        industryMapper.insert(industry); // 存储当前节点
        for (Industry child : industry.getChildren()) {
            saveIndustryRecursive(child); // 递归存储子节点
        }
    }


}
