<template>
  <div class="app-container">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[16px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="行业名称" prop="industryName">
              <el-input v-model="queryParams.industryName" placeholder="请输入行业名称" clearable style="width: 220px" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="行业状态" clearable style="width: 150px">
                <el-option v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="hover" class="table-card">
      <template #header>
        <el-row :gutter="10" class="mb8 op-row">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd()">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="info" plain icon="Sort" @click="toggleExpandAll">展开/折叠</el-button>
          </el-col>
          <right-toolbar v-model:show-search="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table
        ref="industryTableRef"
        v-loading="loading"
        :data="industryList"
        row-key="uniqueId"
        style="width: 100%"
        :header-cell-style="{ background: '#f8f9fb', color: '#666', fontWeight: 'bold' }"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        lazy
        :load="getChildrenList"
      >
        <el-table-column prop="industryName" label="行业名称" min-width="180" :show-overflow-tooltip="true">
          <template #default="scope">
            <span class="industry-name-text">{{ scope.row.industryName }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="orderNum" label="排序" align="center" width="100" />
        <el-table-column prop="status" label="状态" align="center" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === '0' ? 'success' : 'danger'" size="small" effect="light">
              {{ scope.row.status === '0' ? '正常' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" width="180" prop="createTime" />
        <el-table-column label="操作" align="right" width="180" fixed="right">
          <template #default="scope">
            <div class="op-btns">
              <el-tooltip content="修改" placement="top">
                <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" />
              </el-tooltip>
              <el-tooltip content="新增" placement="top">
                <el-button link type="primary" icon="Plus" @click="handleAdd(scope.row)" />
              </el-tooltip>
              <el-tooltip content="删除" placement="top">
                <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" />
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加或修改行业对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" destroy-on-close append-to-body width="600px">
      <el-form ref="industryFormRef" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="上级行业">
              <el-tree-select
                v-model="form.parentId"
                :data="industryOptions"
                :props="{ value: 'industryId', label: 'industryName', children: 'children' } as any"
                value-key="industryId"
                placeholder="选择上级行业"
                check-strictly
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="行业名称" prop="industryName">
              <el-input v-model="form.industryName" placeholder="请输入行业名称" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="显示排序" prop="orderNum">
              <el-input-number v-model="form.orderNum" controls-position="right" :min="0" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="行业状态">
              <el-radio-group v-model="form.status">
                <el-radio v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.label" :value="dict.value">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Industry" lang="ts">
import {
  listIndustry,
  getIndustry,
  addIndustry,
  updateIndustry,
  delIndustry,
  listIndustrySkill,
  getIndustrySkill,
  addIndustrySkill,
  updateIndustrySkill,
  delIndustrySkill
} from '@/api/system/industry/index';
import type { IndustryForm, IndustryQuery } from '@/api/system/industry/types';
import { ComponentInternalInstance, getCurrentInstance, reactive, ref, toRefs, onMounted } from 'vue';
import { handleTree } from '@/utils/ruoyi';

interface IndustryPageQuery extends IndustryQuery {
  parentId?: string | number;
}

interface IndustryPageForm extends IndustryForm {
  remark?: string;
}

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_normal_disable } = toRefs<any>(proxy?.useDict('sys_normal_disable'));

const industryList = ref<any[]>([]);
const loading = ref(true);
const industryOptions = ref<any[]>([]);
const showSearch = ref(true);
const isExpandAll = ref(false);
const industryTableRef = ref<ElTableInstance>();
const queryFormRef = ref<ElFormInstance>();
const industryFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: IndustryForm = {
  industryId: undefined,
  skillId: undefined,
  parentId: 0,
  industryName: '',
  orderNum: 0,
  status: '0',
  type: 'industry'
};

const data = reactive<PageData<IndustryPageForm, IndustryPageQuery>>({
  form: { ...initFormData },
  queryParams: {
    industryName: undefined,
    status: undefined
  },
  rules: {
    industryName: [{ required: true, message: "名称不能为空", trigger: "blur" }],
    orderNum: [{ required: true, message: "显示排序不能为空", trigger: "blur" }]
  }
});

const { queryParams, form, rules } = toRefs(data);

const getListData = <T = any>(res: any): T[] => {
  if (Array.isArray(res?.data)) {
    return res.data;
  }
  if (Array.isArray(res?.rows)) {
    return res.rows;
  }
  return [];
};

// 存储懒加载的 resolve 函数，用于局部刷新
const refreshMap = new Map<any, { row: any, treeNode: any, resolve: (data: any[]) => void }>();

/** 获取子行业列表 (支持跨表懒加载) */
const getChildrenList = async (row: any, treeNode: unknown, resolve: (data: any[]) => void) => {
  refreshMap.set(row.uniqueId, { row, treeNode, resolve });
  // 如果是二级节点，则查询三级职位表数据
  if (row.parentId !== 0 && row.type === 'industry') {
    const res = await listIndustrySkill({ industryId: row.industryId });
    const skills = getListData(res).map((s: any) => ({
      ...s,
      uniqueId: `skill_${s.skillId}`,
      industryName: s.skillName,
      type: 'skill',
      hasChildren: false
    }));
    resolve(skills);
  } else {
    // 处理一级节点的二级分类
    const res = await listIndustry({ parentId: row.industryId });
    const children = getListData(res).map((c: any) => ({
      ...c,
      uniqueId: `industry_${c.industryId}`,
      type: 'industry',
      hasChildren: true // 二级分类标记为可能有子职位
    }));
    resolve(children);
  }
};

/** 刷新局部懒加载节点 */
const refreshLazyNode = (parentId: any) => {
  if (parentId === 0 || parentId === undefined || parentId === null) {
    getList();
    return;
  }
  
  // 对于职位，其 parentId 是行业 ID，唯一标识是 industry_ID
  const uniqueId = `industry_${parentId}`;
  
  if (refreshMap.has(uniqueId)) {
    const { row, treeNode, resolve } = refreshMap.get(uniqueId)!;
    getChildrenList(row, treeNode, resolve);
  } else {
    getList();
  }
};

/** 查询行业列表 */
const getList = async () => {
  loading.value = true;
  try {
    // 始终开启懒加载模式，搜索时只过滤一级节点
    const params = { ...queryParams.value, parentId: 0 };
    const res = await listIndustry(params);
    const rawData = getListData(res);
    
    industryList.value = rawData.map((item: any) => ({
      ...item,
      uniqueId: `industry_${item.industryId}`,
      type: 'industry',
      hasChildren: true // 始终允许展开，以便查看下级内容
    }));
  } catch (e) {
    console.error(e);
  } finally {
    loading.value = false;
  }
};

/** 递归格式化搜索返回的树数据 */
const formatTreeData = (data: any[]): any[] => {
  return data.map(item => {
    const obj = {
      ...item,
      uniqueId: `industry_${item.industryId}`,
      type: 'industry',
      hasChildren: !!(item.children && item.children.length > 0)
    };
    if (item.children) {
      obj.children = formatTreeData(item.children);
    }
    return obj;
  });
};

/** 展开/折叠操作 */
const toggleExpandAll = () => {
  isExpandAll.value = !isExpandAll.value;
  toggleRowExpansionAll(industryList.value, isExpandAll.value);
};

/** 递归切换展开状态 */
const toggleRowExpansionAll = (data: any[], isExpansion: boolean) => {
  data.forEach(item => {
    industryTableRef.value?.toggleRowExpansion(item, isExpansion);
    if (item.children) {
      toggleRowExpansionAll(item.children, isExpansion);
    }
  });
};

/** 查询行业下拉树结构 */
const getTreeselect = async () => {
  const res = await listIndustry(); // 获取所有行业数据用于树选择
  const rawData = getListData(res);
  const industry: any = { industryId: 0, industryName: '主类目', children: [] };
  industry.children = handleTree(rawData, 'industryId');
  industryOptions.value = [industry];
};

/** 新增按钮操作 */
const handleAdd = (row?: any) => {
  reset();
  getTreeselect();
  if (row != null && row.industryId) {
    form.value.parentId = row.industryId;
    // 如果父节点是二级（parentId != 0），则新增的是三级职位
    if (row.parentId !== 0) {
      form.value.type = 'skill';
    } else {
      form.value.type = 'industry';
    }
  } else {
    form.value.parentId = 0;
    form.value.type = 'industry';
  }
  dialog.visible = true;
  dialog.title = form.value.type === 'skill' ? '添加职位' : '添加行业/分类';
};

/** 修改按钮操作 */
const handleUpdate = async (row: any) => {
  reset();
  await getTreeselect();
  if (row.type === 'skill') {
    const res = await getIndustrySkill(row.skillId);
    const skillData = res.data;
    form.value = {
      ...skillData,
      industryName: skillData.skillName, // 页面统一使用 industryName 显示
      parentId: skillData.industryId,    // 职位的上级是行业ID
      type: 'skill'
    };
  } else {
    const res = await getIndustry(row.industryId);
    form.value = {
      ...res.data,
      type: 'industry'
    };
  }
  dialog.visible = true;
  dialog.title = row.type === 'skill' ? '修改职位' : '修改行业/分类';
};

/** 提交按钮 */
const submitForm = () => {
  industryFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      if (form.value.type === 'skill') {
        const skillData = {
          skillId: form.value.skillId,
          industryId: form.value.parentId,
          skillName: form.value.industryName,
          orderNum: form.value.orderNum,
          status: form.value.status,
          remark: form.value.remark
        };
        if (form.value.skillId) {
          await updateIndustrySkill(skillData);
        } else {
          await addIndustrySkill(skillData);
        }
      } else {
        const industryData = {
          ...form.value,
          industryName: form.value.industryName
        };
        if (form.value.industryId) {
          await updateIndustry(industryData);
        } else {
          await addIndustry(industryData);
        }
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      refreshLazyNode(form.value.parentId);
    }
  });
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  getList();
};

/** 删除按钮操作 */
const handleDelete = async (row: any) => {
  await proxy?.$modal.confirm(`是否确认删除名称为"${row.industryName}"的数据项?`);
  const parentId = row.type === 'skill' ? row.industryId : row.parentId;
  
  if (row.type === 'skill') {
    await delIndustrySkill(row.skillId);
  } else {
    await delIndustry(row.industryId);
  }
  refreshLazyNode(parentId);
  proxy?.$modal.msgSuccess('删除成功');
};


/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 重置表单 */
const reset = () => {
  form.value = { ...initFormData };
  industryFormRef.value?.resetFields();
};

onMounted(() => {
  getList();
});
</script>

<style scoped>
.industry-name-text {
  font-weight: 500;
}
.op-btns {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}
</style>
