<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="归属系统" prop="system">
              <el-select v-model="queryParams.system" placeholder="请选择所属系统" clearable>
                <el-option v-for="dict in msg_system" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <!--            <el-form-item label="归属模块" prop="module">-->
            <!--              <el-select v-model="queryParams.module" placeholder="请选择所属模块" clearable>-->
            <!--                <el-option v-for="dict in print_module" :key="dict.value" :label="dict.label" :value="dict.value" />-->
            <!--              </el-select>-->
            <!--            </el-form-item>-->
            <el-form-item label="模板编码" prop="templateCode">
              <el-select v-model="queryParams.templateName" placeholder="请输入模版编码" clearable @change="handleTemplateChange">
                <template #header>
                  <el-input v-model="likeName" placeholder="可根据模版名称模糊查询" @input="filterByTemplateName"></el-input>
                </template>
                <el-option
                  v-for="dict in filteredList"
                  :key="dict.templateCode"
                  :label="dict.templateName + '-v' + dict.version"
                  :value="dict.templateCode + '&' + dict.version"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="开始日期" prop="applyDate">
              <el-date-picker v-model="queryParams.beginDate" clearable type="date" value-format="YYYY-MM-DD" placeholder="请选择申请日期" />
            </el-form-item>
            <el-form-item label="结束日期" prop="applyDate">
              <el-date-picker v-model="queryParams.endDate" clearable type="date" value-format="YYYY-MM-DD" placeholder="请选择申请日期" />
            </el-form-item>
            <el-form-item style="width: 100%">
              <el-button type="primary" plain icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
              <el-button v-hasPermi="['msg:mestemp:add']" type="primary" plain icon="Plus" @click="handleAdd">新增 </el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <!--          <el-col :span="1.5">-->
          <!--            <el-button v-hasPermi="['msg:mestemp:confirm']" :disabled="single" type="success" plain @click="templateConfirm">模板确认</el-button>-->
          <!--          </el-col>-->
          <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="mestempList">
        <el-table-column v-if="false" label="模板唯一标识" align="center" prop="templateId" />
        <el-table-column label="模板ID" align="center" prop="templateCode" />
        <el-table-column v-if="false" label="模板类型 0短信 1邮件 2微信" align="center" prop="templateType" />
        <el-table-column label="模板名称" align="center" prop="templateName" show-overflow-tooltip />
        <el-table-column label="归属系统" align="center" prop="system">
          <template #default="scope">
            <dict-tag :options="msg_system" :value="scope.row.system" />
          </template>
        </el-table-column>
        <el-table-column label="所属模块" align="center" prop="module">
          <template #default="scope">
            <span>{{ moduleValueToLabel[scope.row.module] || scope.row.module }}</span>
          </template>
        </el-table-column>
        <el-table-column label="短信内容" align="center" prop="templateContent" show-overflow-tooltip />
        <el-table-column label="版本号" align="center" prop="versionNumber" />
        <el-table-column v-if="false" label="版本申请状态" align="center" prop="versionApplyStatus" />
        <el-table-column v-if="false" label="版本启用状态" align="center" prop="versionEnableStatus" />
        <el-table-column v-if="false" label="说明" align="center" prop="description" />
        <el-table-column v-if="false" label="申请日期" align="center" prop="applyDate" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.applyDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
<!--            <el-tooltip content="审批流程" placement="top">-->
<!--              <el-button-->
<!--                link-->
<!--                type="primary"-->
<!--                icon="Document"-->
<!--                @click="viewApprovalProcess(scope.row)"-->
<!--              ></el-button>-->
<!--            </el-tooltip>-->
            <el-tooltip content="修改" placement="top">
              <el-button v-hasPermi="['msg:mestemp:edit']" link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button v-hasPermi="['msg:mestemp:remove']" link type="primary" icon="Delete" @click="handleDelete(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="确认" placement="top">
              <el-button v-hasPermi="['msg:mestemp:confirm']" link type="primary" icon="CircleCheck" @click="templateConfirm(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </el-card>
    <!-- 添加或修改消息模板配置对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="80%" append-to-body>
      <el-form ref="mestempFormRef" :model="form" :rules="rules" label-width="100px" :inline="true">
        <el-form-item label="模版编码" prop="templateCode">
          <el-select v-model="form.templateCode" placeholder="请输入模版编码" clearable @change="selectTemp">
            <template #header>
              <el-input v-model="dialogLikeName" placeholder="可根据模版名称模糊查询" @input="filterByTemplateNameDialog"></el-input>
            </template>
            <el-option
              v-for="dict in dialogFilteredList"
              :key="dict.templateCode"
              :label="dict.templateName + '-v' + dict.version"
              :value="dict.templateCode + '&' + dict.version"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="短信名称" prop="templateName">
          <el-input v-model="form.templateName" placeholder="请输入模板名称" />
        </el-form-item>
        <el-form-item label="归属系统" prop="system">
          <el-select v-model="form.system" placeholder="请选择所属系统">
            <el-option v-for="dict in msg_system" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="归属模块" prop="module">
          <el-cascader
            v-model="form.modulePath"
            :options="moduleTreeOptions"
            :props="moduleProps"
            :show-all-levels="false"
            placeholder="请选择所属模块"
            clearable
            filterable
            style="width: 100%"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="发送方式" prop="sendMethod">
          <el-select v-model="form.sendMethod" placeholder="请选择发送方式">
            <el-option v-for="dict in sms_send_method" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="短信类型" prop="smsType">
          <el-select v-model="form.smsType" placeholder="请选择短信类型">
            <el-option v-for="dict in sms_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-row>
          <el-form-item label="发送上限" prop="sendUpLimit">
            <el-input-number v-model="form.sendUpLimit" style="width: 240px" clearable />
          </el-form-item>
          <el-form-item label="发送下限" prop="sendUpLimit">
            <el-input-number v-model="form.sendLowLimit" style="width: 240px" clearable />
          </el-form-item>
          <el-form-item label="版本" prop="versionNumber">
            <el-input v-model="form.versionNumber" disabled />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="短信内容" prop="templateContent" style="width: 70%">
            <el-input v-model="form.templateContent" type="textarea" placeholder="请输入内容" :rows="6" />
            <!-- 将提示信息移动到短信内容输入框下方 -->
            <div class="tips-container">
              <el-text class="mx-1" type="primary">
                tips:
                <br />
                1、短信模版定义时使用两个大括号包含包围的元素作为变量参数，参数只能包含英文字母。 样例格式：<el-tag>{{ tipsKey }} </el-tag>
                <br />
                2、如果选择的服务商已包含了短信前、后缀，新定义模版时<el-tag type="danger">请勿</el-tag>添加前后缀信息。
              </el-text>
            </div>
          </el-form-item>
        </el-row>
        <el-form-item label="增加/调整原因" prop="description" style="width: 50%">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item v-if="form.rollbackReason != null" label="回退原因" prop="rollbackReason" style="width: 50%">
          <el-input v-model="form.rollbackReason" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <msg-risk-control ref="msgRiskControlRef"></msg-risk-control>

      <!--      <el-table v-loading="loading" :data="riskControlList" @selection-change="handleSelectionChange">-->
      <!--        <el-table-column type="selection" width="55" align="center" />-->
      <!--        <el-table-column label="风控规则编码" align="center" prop="riskCode" />-->
      <!--        <el-table-column label="风控规则描述" align="center" prop="riskDesc" />-->
      <!--        <el-table-column label="风控规则参数" align="center" prop="riskParms" />-->
      <!--        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">-->
      <!--          <template #default="scope">-->
      <!--            <el-tooltip content="编辑" placement="top">-->
      <!--              <el-button v-hasPermi="['msg:mestemp:edit']" link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>-->
      <!--            </el-tooltip>-->
      <!--            <el-tooltip content="删除" placement="top">-->
      <!--              <el-button v-hasPermi="['msg:mestemp:remove']" link type="primary" icon="Delete" @click="handleDelete(scope.row)"></el-button>-->
      <!--            </el-tooltip>-->
      <!--          </template>-->
      <!--        </el-table-column>-->
      <!--      </el-table>-->

      <template #footer>
        <!--        <div class="dialog-add">-->
        <!--          <el-button v-hasPermi="['msg:mestemp:add']" type="primary" plain icon="Plus" @click="handleAdd"></el-button>-->
        <!--        </div>-->
        <div class="dialog-footer">
          <el-button v-hasPermi="['msg:mestemp:add']" :loading="buttonLoading" type="primary" @click="submitForm">保存</el-button>
          <el-button v-hasPermi="['msg:mestemp:confirm']" :loading="buttonLoading" type="primary" :disabled="!hasSaved" @click="templateConfirm(form)"
            >完成</el-button
          >
          <el-button @click="cancel">关闭</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="approvalDialog.visible" :title="approvalDialog.title" width="60%">
      <el-table v-loading="approvalLoading" :data="approvalProcessList">
        <el-table-column label="审批节点" prop="nodeName" align="center" />
        <el-table-column label="审批人" prop="approver" align="center" />
        <el-table-column label="审批结果" prop="approvalResult" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.approvalResult === '通过' ? 'success' : 'danger'">
              {{ scope.row.approvalResult }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="审批时间" prop="approvalTime" align="center" />
        <el-table-column label="审批意见" prop="comment" align="center" />
      </el-table>

      <template #footer>
        <el-button @click="approvalDialog.visible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Mestemp" lang="ts">
import {
  listMestemp,
  getMestemp,
  delMestemp,
  addMestemp,
  updateMestemp,
  editStatusMsgtemp,
  queryMSMTemplateList,
  selectMSMTempByTempCode,
  constructModuleEnumTree
} from '@/api/msg/mestemp';
import { MestempVO, MestempQuery, MestempForm } from '@/api/msg/mestemp/types';
import MsgRiskControl from '@/views/msg/riskControl/msgRiskControl.vue';
import { updateTemplateRiskControl } from '@/api/msg/emailtemp';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { msg_system, print_module, sms_type, sms_send_method } = toRefs<any>(
  proxy?.useDict('msg_system', 'print_module', 'sms_send_method', 'sms_type')
);

const mestempList = ref<MestempVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const sign = ref();
const codeSign = ref();
const hasSaved = ref(false);
const tipsKey = ref('{{Keys}}');
const queryFormRef = ref<ElFormInstance>();
const mestempFormRef = ref<ElFormInstance>();
const riskControlList = ref([]);
const likeName = ref('');
const templateList = ref<any[]>([]);
const filteredList = ref<any[]>([]);
const dialogLikeName = ref('');
const dialogTemplateList = ref<any[]>([]);
const dialogFilteredList = ref<any[]>([]);
const moduleTreeOptions = ref<any[]>([]);
const msgRiskControlRef = ref();
const moduleProps = {
  value: 'value',
  label: 'label',
  children: 'children',
  checkStrictly: true
};

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

const initFormData: MestempForm = {
  templateId: undefined,
  templateCode: undefined,
  templateType: undefined,
  templateName: undefined,
  system: undefined,
  module: undefined,
  versionNumber: undefined,
  templateContent: undefined,
  versionApplyStatus: undefined,
  versionEnableStatus: undefined,
  description: undefined,
  applyDate: undefined,
  rollbackReason: undefined,
  modulePath: undefined,
  sendMethod: undefined,
  smsType: undefined,
  sendUpLimit: undefined,
  sendLowLimit: undefined
};
const data = reactive<PageData<MestempForm, MestempQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    templateCode: undefined,
    templateName: undefined,
    system: undefined,
    module: undefined,
    applyDate: undefined,
    versionApplyStatus: 0,
    endDate: undefined,
    beginDate: undefined,
    params: {}
  },
  rules: {
    templateName: [
      { required: true, message: '短信名称不能为空', trigger: 'blur' },
      { max: 50, message: '短信名称不能超过50个字', trigger: 'blur' }
    ],
    system: [{ required: true, message: '归属系统不能为空', trigger: 'blur' }],
    module: [{ required: true, message: '归属模块不能为空', trigger: 'blur' }],
    templateContent: [
      { required: true, message: '短信内容不能为空', trigger: 'blur' },
      { max: 1000, message: '增加/调整原因不能超过1000个字', trigger: 'blur' }
    ],
    description: [
      { required: true, message: '增加/调整原因不能为空', trigger: 'blur' },
      { max: 1000, message: '增加/调整原因不能超过1000个字', trigger: 'blur' }
    ]
  }
});
// 在setup中添加响应式变量
const approvalDialog = reactive({
  visible: false,
  title: '审批流程查看'
});
const approvalLoading = ref(false);
const approvalProcessList = ref<any[]>([]);
// 添加查看审批流程方法
// const viewApprovalProcess = async (row: MestempVO) => {
//   try {
//     approvalLoading.value = true;
//     approvalDialog.visible = true;
//     approvalDialog.title = `${row.templateName} - 审批流程`;
//
//     // 调用API获取审批流程数据
//     const res = await queryAuditInfo(row.templateId);
//     approvalProcessList.value = res.data;
//   } catch (error) {
//     proxy?.$modal.msgError('获取审批流程失败');
//   } finally {
//     approvalLoading.value = false;
//   }
// };
const { queryParams, form, rules } = toRefs(data);

/** 查询消息模板配置列表 */
const getList = async () => {
  loading.value = true;
  const res = await listMestemp(queryParams.value);
  mestempList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

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

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

  // 清空风控规则（确保弹窗关闭时也触发）
  if (msgRiskControlRef.value) {
    msgRiskControlRef.value.resetRiskControls();
  }
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  // 重置查询参数到初始状态
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    templateCode: undefined,
    system: undefined,
    module: undefined,
    applyDate: undefined,
    versionApplyStatus: 0,
    endDate: undefined,
    beginDate: undefined,
    params: {},
    templateName:undefined
  };
  // 重置模板名称过滤相关状态
  likeName.value = '';
  filteredList.value = templateList.value;
  handleQuery();
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset(); // 重置表单数据

  // 强制清空风控规则
  nextTick(() => {
    if (msgRiskControlRef.value) {
      msgRiskControlRef.value.resetRiskControls(); // 调用子组件方法清空
    }
  });

  sign.value = 'add';

  dialog.visible = true;
  dialog.title = '添加消息模板配置';
};

/** 模板确认按钮操作 */
const templateConfirm = async (formData?: MestempForm) => {
  const dataToConfirm = formData || form.value;


  if (!dataToConfirm.templateId) {
    proxy?.$modal.msgError('无法获取模板ID');
    return;
  }

  await proxy?.$modal.confirm(`是否确认定义模板编码为"${dataToConfirm.templateCode}"的模板？`).finally(() => (loading.value = false));

  await editStatusMsgtemp(dataToConfirm.templateId);
  dialog.visible = false;
  proxy?.$modal.msgSuccess('操作成功');
  await getList();
};

/** 修改按钮操作 */
const handleUpdate = async (row?: MestempVO) => {
  reset(); // 重置表单
  const _templateId = row?.templateId || ids.value[0];

  // 1. 加载模板数据
  const res = await getMestemp(_templateId);
  Object.assign(form.value, res.data);

  // 2. 计算模块路径
  form.value.modulePath = findModulePath(form.value.module);

  // 3. 确保弹窗 DOM 完全挂载
  dialog.visible = true; // 先打开弹窗（但隐藏内容）
  await nextTick(); // 等待弹窗渲染完成

  // 4. 加载风控规则数据
  if (msgRiskControlRef.value) {
    await msgRiskControlRef.value.loadingPage(_templateId);
  }

  // 5. 更新状态
  sign.value = 'update';
  dialog.title = '修改消息模板配置';
};

/** 提交按钮 */
const submitForm = () => {
  if (sign.value === 'add') {
    // 确保子组件已加载
    if (!msgRiskControlRef.value || !msgRiskControlRef.value.hasValidRules) {
      proxy?.$modal.msgError('风控规则组件未加载完成，请稍后重试');
      return;
    }

    // 检查风控规则是否有效
    const isValid = msgRiskControlRef.value.hasValidRules();
    if (!isValid) {
      proxy?.$modal.msgError('请添加完整有效的风控规则');
      return;
    }
  }
  mestempFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (sign.value === 'update') {
        await updateMestemp(form.value).finally(() => (buttonLoading.value = false));
        const riskControlData = getRiskControlData();
        const data = convertToRiskControlBos(riskControlData);
        await updateTemplateRiskControl(data);
        const res = await selectMSMTempByTempCode(form.value);
        Object.assign(form.value, res.data);
      } else {
        form.value.templateId = '';
        const res = await addMestemp(form.value).finally(() => (buttonLoading.value = false));
        Object.assign(form.value, res.data);
        const riskControlData = getRiskControlData();
        const data = convertToRiskControlBos(riskControlData);
        await updateTemplateRiskControl(data);
        sign.value = 'update';
      }
      hasSaved.value = true;
      proxy?.$modal.msgSuccess('操作成功');
      await getList();
      quryTemplateList('apply');
      quryTemplateListDialog('auditPass');
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: MestempVO) => {
  const _templateIds = row?.templateId || ids.value;
  const _templateName = row?.templateName || ids.value[0];
  const _versionNumber = row?.versionNumber || ids.value[1];
  await proxy?.$modal
    .confirm('是否要删除"' + _templateName + '"，版本号为"' + _versionNumber + '"的模板信息？')
    .finally(() => (loading.value = false));
  await delMestemp(_templateIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
  quryTemplateList('apply');
  quryTemplateListDialog('auditPass');
};

const handleTemplateChange = async (newVal) => {
  const val = newVal.split('&');
  queryParams.value.templateCode = val[0];
};

const selectTemp = async (newVal, querySign) => {
  const val = newVal.split('&');
  if (!querySign) {
    try {
      form.value = {
        ...initFormData,
        templateCode: val[0],
        versionNumber: val[1]
      };

      const response = await selectMSMTempByTempCode(form.value);
      Object.assign(form.value, response.data);
      form.value.modulePath = findModulePath(form.value.module);
      nextTick(() => {
        if (msgRiskControlRef.value) {
          msgRiskControlRef.value.loadingPage(form.value.templateId);
        }
      });
    } catch (error) {
      form.value = { ...initFormData };
      form.value.templateCode = '';
      form.value.versionNumber = '';
      nextTick(() => {
        if (msgRiskControlRef.value) {
          msgRiskControlRef.value.resetRiskControls();
        }
      });
    }
  }
};

//模糊查询
const filterByTemplateName = () => {
  if (likeName.value) {
    // 过滤操作
    filteredList.value = templateList.value.filter((item) => {
      return item.templateName.includes(likeName.value);
    });
  } else {
    // 如果 likeName 为空，显示原始列表
    filteredList.value = templateList.value;
  }
};

const filterByTemplateNameDialog = () => {
  if (dialogLikeName.value) {
    // 过滤操作
    dialogFilteredList.value = dialogTemplateList.value.filter((item) => {
      return item.templateName.includes(dialogLikeName.value);
    });
  } else {
    // 如果 likeName 为空，显示原始列表
    dialogFilteredList.value = dialogTemplateList.value;
  }
};

// 转换风险控制数据为后端需要的格式
const convertToRiskControlBos = (riskData) => {
  return riskData
    .map((item) => {
      // 对于每个参数键值对创建一个Bo对象
      return Object.entries(item.riskParams).map(([paramName, paramValue]) => ({
        templateId: form.value.templateId, // 从当前组件获取
        strategyId: item.strategyId,
        paramId: item.paramId,
        riskParamName: paramName,
        riskParamValue: paramValue.toString(), // 确保是字符串
        mediumType: 'EMAIL' // 根据实际情况设置，EMAIL或SMS
      }));
    })
    .flat(); // 将二维数组扁平化
};

const getRiskControlData = () => {
  if (msgRiskControlRef.value) {
    return msgRiskControlRef.value.riskList;
  }
  return [];
};

const quryTemplateList = async (codeSign) => {
  const res = await queryMSMTemplateList(codeSign);
  templateList.value = res.data.tempList;
  filteredList.value = templateList.value;
};

const quryTemplateListDialog = async (codeSign) => {
  const res = await queryMSMTemplateList(codeSign);
  dialogTemplateList.value = res.data.tempList;
  dialogFilteredList.value = dialogTemplateList.value;
};

// 新增方法：根据模块值查找完整路径
const findModulePath = (moduleValue) => {
  // 这里需要实现根据moduleValue在moduleTreeOptions中查找完整路径的逻辑
  // 这是一个示例实现，需要根据你的实际数据结构调整
  const findPath = (nodes, target, path = []) => {
    for (const node of nodes) {
      if (node.value === target) {
        return [...path, node.value];
      }
      if (node.children) {
        const found = findPath(node.children, target, [...path, node.value]);
        if (found) return found;
      }
    }
    return null;
  };

  return findPath(moduleTreeOptions.value, moduleValue) || [];
};

const getModuleTree = async () => {
  try {
    const res = await constructModuleEnumTree();

    // 如果返回的是字符串，先解析为JSON对象
    const data = typeof res.msg === 'string' ? JSON.parse(res.msg) : res.msg;

    // 处理数据 - 你提供的示例数据已经是正确的树形结构
    moduleTreeOptions.value = Array.isArray(data) ? data : [data];

  } catch (error) {
    moduleTreeOptions.value = [];
  }
};

// 添加watch
watch(
  () => form.value.modulePath,
  (newVal) => {
    if (newVal && newVal.length > 0) {
      form.value.module = newVal[newVal.length - 1];
    } else {
      form.value.module = undefined;
    }
  }
);

// 创建模块值到标签的映射
const moduleValueToLabel = computed(() => {
  const map: Record<string, string> = {};
  const buildMap = (nodes: any[]) => {
    nodes.forEach((node) => {
      map[node.value] = node.label;
      if (node.children) buildMap(node.children);
    });
  };
  buildMap(moduleTreeOptions.value);
  return map;
});

onMounted(() => {
  getList();
  quryTemplateList('apply');
  quryTemplateListDialog('auditPass');
  getModuleTree();

  // 调用子组件的 loadingPage 方法
  nextTick(() => {
    if (msgRiskControlRef.value) {
      msgRiskControlRef.value.loadingPage(loadtemplateId);
    }
  });
});
</script>

<style scoped>
.tips-container {
  margin-top: 10px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  border-left: 4px solid #409eff;
}

.tips-container .el-text {
  line-height: 1.6;
}

.tips-container .el-tag {
  margin: 0 2px;
  vertical-align: baseline;
}
.dialog-footer {
  text-align: left; /* 将按钮左对齐 */
}

.dialog-add {
  text-align: left; /* 将按钮左对齐 */
}
</style>
