package com.ruoyi.web.modules.industryservice.support;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.ruoyi.common.core.domain.TreeSelect;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysDeptService;

/**
 * 填报乡镇 / 村字典（县 → 乡镇 → 村；乡镇为县级下 order_num &gt; 12 节点）
 */
@Component
public class TownDeptSupport
{
    @Autowired
    private ISysDeptService deptService;

    public List<SysDept> listReportTowns()
    {
        SysDept query = new SysDept();
        query.setParentId(YakHerdInventoryRules.TOWN_PARENT_ID);
        query.setStatus("0");
        List<SysDept> depts = deptService.selectDeptList(query);
        List<SysDept> towns = new ArrayList<>();
        if (depts == null)
        {
            return towns;
        }
        for (SysDept dept : depts)
        {
            if (dept == null || !"0".equals(dept.getDelFlag()))
            {
                continue;
            }
            if (dept.getOrderNum() != null && dept.getOrderNum() > YakHerdInventoryRules.TOWN_MIN_ORDER_NUM)
            {
                towns.add(dept);
            }
        }
        towns.sort((a, b) -> Integer.compare(
                a.getOrderNum() == null ? 0 : a.getOrderNum(),
                b.getOrderNum() == null ? 0 : b.getOrderNum()));
        return towns;
    }

    public List<SysDept> listVillagesUnderTown(Long townDeptId)
    {
        List<SysDept> villages = new ArrayList<>();
        if (townDeptId == null)
        {
            return villages;
        }
        SysDept query = new SysDept();
        query.setParentId(townDeptId);
        query.setStatus("0");
        List<SysDept> depts = deptService.selectDeptList(query);
        if (depts == null)
        {
            return villages;
        }
        for (SysDept dept : depts)
        {
            if (dept != null && "0".equals(dept.getDelFlag()))
            {
                villages.add(dept);
            }
        }
        villages.sort((a, b) -> Integer.compare(
                a.getOrderNum() == null ? 0 : a.getOrderNum(),
                b.getOrderNum() == null ? 0 : b.getOrderNum()));
        return villages;
    }

    /**
     * 县 → 乡镇 → 村 树；仅叶子村可选（前端 disable-branch-nodes，父级不设 disabled 以免无法点选子节点）。
     */
    public List<TreeSelect> buildVillageTree()
    {
        List<TreeSelect> townNodes = new ArrayList<>();
        for (SysDept town : listReportTowns())
        {
            TreeSelect townNode = new TreeSelect();
            townNode.setId(town.getDeptId());
            townNode.setLabel(town.getDeptName());
            List<TreeSelect> children = new ArrayList<>();
            for (SysDept village : listVillagesUnderTown(town.getDeptId()))
            {
                TreeSelect villageNode = new TreeSelect();
                villageNode.setId(village.getDeptId());
                villageNode.setLabel(village.getDeptName());
                children.add(villageNode);
            }
            townNode.setChildren(children);
            townNodes.add(townNode);
        }

        SysDept county = deptService.selectDeptById(YakHerdInventoryRules.TOWN_PARENT_ID);
        TreeSelect countyNode = new TreeSelect();
        countyNode.setId(YakHerdInventoryRules.TOWN_PARENT_ID);
        countyNode.setLabel(county != null && StringUtils.isNotEmpty(county.getDeptName())
                ? county.getDeptName()
                : "巴青县");
        countyNode.setChildren(townNodes);

        List<TreeSelect> roots = new ArrayList<>();
        roots.add(countyNode);
        return roots;
    }

    public Map<String, SysDept> townNameMap()
    {
        Map<String, SysDept> map = new LinkedHashMap<>();
        for (SysDept town : listReportTowns())
        {
            if (StringUtils.isNotEmpty(town.getDeptName()))
            {
                map.put(town.getDeptName().trim(), town);
            }
        }
        return map;
    }

    public SysDept requireReportTown(Long townDeptId)
    {
        if (townDeptId == null)
        {
            return null;
        }
        for (SysDept town : listReportTowns())
        {
            if (townDeptId.equals(town.getDeptId()))
            {
                return town;
            }
        }
        return null;
    }

    /**
     * 校验村属于填报乡镇，并返回村部门。
     */
    public SysDept requireReportVillage(Long villageDeptId)
    {
        if (villageDeptId == null)
        {
            return null;
        }
        SysDept village = deptService.selectDeptById(villageDeptId);
        if (village == null || !"0".equals(village.getDelFlag()) || !"0".equals(village.getStatus()))
        {
            return null;
        }
        if (requireReportTown(village.getParentId()) == null)
        {
            return null;
        }
        return village;
    }

    public SysDept resolveTownByName(String townName)
    {
        if (StringUtils.isEmpty(townName))
        {
            return null;
        }
        String normalized = normalizeTownName(townName.trim());
        SysDept town = townNameMap().get(normalized);
        if (town != null)
        {
            return town;
        }
        return townNameMap().get(townName.trim());
    }

    /**
     * 在指定乡镇下按村名解析村部门。
     */
    public SysDept resolveVillageByTownAndName(Long townDeptId, String villageName)
    {
        if (townDeptId == null || StringUtils.isEmpty(villageName))
        {
            return null;
        }
        String name = villageName.trim();
        for (SysDept village : listVillagesUnderTown(townDeptId))
        {
            if (name.equals(village.getDeptName()))
            {
                return village;
            }
        }
        return null;
    }

    /**
     * 模板乡镇名与 sys_dept 名称归一（如「扎色镇」→「杂色镇」）
     */
    public static String normalizeTownName(String townName)
    {
        if ("扎色镇".equals(townName))
        {
            return "杂色镇";
        }
        return townName;
    }

    public boolean isVillageUnderTown(Long villageDeptId, Long townDeptId)
    {
        if (villageDeptId == null)
        {
            return true;
        }
        if (townDeptId == null)
        {
            return false;
        }
        SysDept village = deptService.selectDeptById(villageDeptId);
        return village != null && "0".equals(village.getDelFlag()) && townDeptId.equals(village.getParentId());
    }

    public List<Map<String, Object>> toOptionList()
    {
        List<Map<String, Object>> options = new ArrayList<>();
        for (SysDept town : listReportTowns())
        {
            Map<String, Object> item = new LinkedHashMap<>();
            item.put("deptId", town.getDeptId());
            item.put("deptName", town.getDeptName());
            item.put("orderNum", town.getOrderNum());
            options.add(item);
        }
        return Collections.unmodifiableList(options);
    }
}
