<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="templateCode">
              <el-select
                v-model="queryParams.templateName"
                placeholder="请输入模版名称"
                clearable
                @change="handleTemplateChange"
                @clear="clearTemplateSelection"
              >
                <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="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="versionEnableStatus">
              <el-select v-model="queryParams.versionEnableStatus" placeholder="请选择启用状态" clearable>
                <el-option v-for="dict in version_enable_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-row>
              <el-form-item v-if="true" label="归属模块" prop="module">
                <el-cascader
                  v-model="queryParams.modulePath"
                  :options="moduleTreeOptions"
                  :props="moduleProps"
                  :show-all-levels="false"
                  placeholder="请选择所属模块"
                  clearable
                  filterable
                  style="width: 100%"
                />
              </el-form-item>
              <!--            <el-form-item label="启用状态" prop="versionEnableStatus">-->
              <!--              <el-select v-model="queryParams.versionEnableStatus" placeholder="请选择启用状态" clearable>-->
              <!--                <el-option label="启用" value="Y" />-->
              <!--                <el-option label="停用" value="N" />-->
              <!--              </el-select>-->
              <!--            </el-form-item>-->
              <!-- 新增：短信通道筛选 -->
              <el-form-item label="短信通道" prop="smsSendChannel">
                <el-select v-model="queryParams.smsSendChannel" placeholder="请选择短信通道" clearable>
                  <el-option v-for="dict in channels" :key="dict.providerId" :label="dict.providerName" :value="dict.providerId" />
                  />
                </el-select>
              </el-form-item>
            </el-row>
            <el-form-item style="width: 100%">
              <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="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="versionList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column v-if="false" label="模板唯一标识" align="center" prop="templateId" />
        <el-table-column label="模板编码" 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" />
        <el-table-column label="模板内容" align="center" prop="templateContent" 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="versionNumber" />
        <el-table-column label="短信通道" align="center" prop="smsSendChannel">
          <template #default="scope">
            <span v-if="scope.row.smsSendChannel">
              {{ getChannelName(scope.row.smsSendChannel) }}
            </span>
            <span v-else class="text-gray-400">未配置</span>
          </template>
        </el-table-column>
        <el-table-column v-if="false" label="模板内容" align="center" prop="templateContent" />
        <el-table-column v-if="false" label="版本申请状态" align="center" prop="versionApplyStatus" />
        <!--        <el-table-column label="版本是否启用" align="center" prop="versionEnableStatus">-->
        <!--          <template #default="scope">-->
        <!--            <el-switch-->
        <!--              v-model="scope.row.versionEnableStatus"-->
        <!--              v-hasPermi="['msg:version:changestatus']"-->
        <!--              active-value="Y"-->
        <!--              inactive-value="N"-->
        <!--              @change="handleStatusChange(scope.row)"-->
        <!--            ></el-switch>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <el-table-column label="版本启用状态" align="center" prop="versionEnableStatus">
          <template #default="scope">
            <el-tag :type="scope.row.versionEnableStatus === 'Y' ? 'success' : 'danger'">
              {{ scope.row.versionEnableStatus === 'Y' ? '已启用' : '已停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="审批" align="center">
          <template #default="scope">
            <el-tag v-if="scope.row.hasPendingAudit" type="warning">待审批</el-tag>
            <span v-else>-</span>
            <!-- 审批按钮，当有待审批申请时显示 -->
            <el-button
              v-if="scope.row.hasPendingAudit"
              v-hasPermi="['msg:version:approve']"
              type="primary"
              size="small"
              @click="handleApprove(scope.row)"
              >审批</el-button
            >
          </template>
        </el-table-column>
        <el-table-column label="启停日志" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <!-- 原有的查看日志按钮 -->
            <el-button v-hasPermi="['msg:version:log']" link type="primary" icon="View" @click="handleStatusLog(scope.row)">查看</el-button>
          </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="logDialogVisible" title="模板启停记录" width="800px">
      <el-tabs v-model="activeLogTab">
        <!-- 操作日志标签页 -->
        <!--        <el-tab-pane label="操作日志" name="operation">-->
        <!--          <el-table :data="operationLogs" v-loading="logLoading">-->
        <!--            <el-table-column prop="createTime" label="操作时间" align="center" width="180">-->
        <!--              <template #default="scope">-->
        <!--                {{ parseTime(scope.row.createTime) }}-->
        <!--              </template>-->
        <!--            </el-table-column>-->
        <!--            <el-table-column prop="userName" label="操作人" align="center" />-->
        <!--            <el-table-column prop="versionEnableStatus" label="操作行为" align="center">-->
        <!--              <template #default="scope">-->
        <!--                <dict-tag :options="version_enable_status" :value="scope.row.versionEnableStatus" />-->
        <!--              </template>-->
        <!--            </el-table-column>-->
        <!--            <el-table-column prop="templateName" label="模板名称" align="center" />-->
        <!--            <el-table-column prop="templateCode" label="模板编码" align="center" />-->
        <!--          </el-table>-->
        <!--          <pagination-->
        <!--            v-show="operationLogTotal > 0"-->
        <!--            small-->
        <!--            layout="prev, pager, next"-->
        <!--            v-model:page="operationLogQuery.pageNum"-->
        <!--            v-model:limit="operationLogQuery.pageSize"-->
        <!--            :total="operationLogTotal"-->
        <!--            @pagination="getOperationLogs"-->
        <!--          />-->
        <!--        </el-tab-pane>-->

        <!-- 审核日志标签页 -->
        <el-tab-pane label="审核日志" name="audit">
          <el-table v-loading="logLoading" :data="auditLogs">
            <el-table-column prop="applyTime" label="申请时间" align="center" width="180">
              <template #default="scope">
                {{ parseTime(scope.row.applyTime) }}
              </template>
            </el-table-column>
            <el-table-column prop="applyUserName" label="申请人" align="center" />
            <el-table-column prop="auditTime" label="审批时间" align="center" width="180">
              <template #default="scope">
                {{ scope.row.auditTime ? parseTime(scope.row.auditTime) : '-' }}
              </template>
            </el-table-column>
            <el-table-column prop="auditUserName" label="审批人" align="center" />
            <el-table-column label="审批状态" align="center">
              <template #default="scope">
                <el-tag v-if="scope.row.auditStatus === '0'" type="warning">待审批</el-tag>
                <el-tag v-else-if="scope.row.auditStatus === '1'" type="success">已批准</el-tag>
                <el-tag v-else-if="scope.row.auditStatus === '2'" type="danger">已拒绝</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="currentStatus" label="申请状态" align="center">
              <template #default="scope">
                <dict-tag :options="version_enable_status" :value="scope.row.currentStatus" />
              </template>
            </el-table-column>
            <el-table-column prop="targetStatus" label="预期状态" align="center">
              <template #default="scope">
                <dict-tag :options="version_enable_status" :value="scope.row.targetStatus" />
              </template>
            </el-table-column>
            <el-table-column prop="applyReason" label="申请原因" align="center" show-overflow-tooltip />
            <el-table-column prop="auditComment" label="审批意见" align="center" show-overflow-tooltip />
          </el-table>
          <pagination
            v-show="auditLogTotal > 0"
            v-model:page="auditLogQuery.pageNum"
            v-model:limit="auditLogQuery.pageSize"
            small
            layout="prev, pager, next"
            :total="auditLogTotal"
            @pagination="getAuditLogs"
          />
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
    <!-- 新增: 审批对话框 -->
    <el-dialog v-model="approveDialog.visible" :title="approveDialog.title" width="600px">
      <el-form :model="approveForm" label-width="120px">
        <el-row>
          <el-form-item label="模板名称">
            <el-input v-model="approveForm.templateName" readonly />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="模板编码">
            <el-input v-model="approveForm.templateCode" readonly />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="申请状态">
            <el-tag :type="approveForm.currentStatus === 'Y' ? 'success' : 'danger'">
              {{ approveForm.currentStatus === 'Y' ? '已启用' : '已停用' }}
            </el-tag>
          </el-form-item>
          <el-form-item label="预期状态">
            <el-tag :type="approveForm.targetStatus === 'Y' ? 'success' : 'danger'">
              {{ approveForm.targetStatus === 'Y' ? '启用' : '停用' }}
            </el-tag>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="申请人">
            <el-input v-model="approveForm.applyUserName" readonly />
          </el-form-item>
          <el-form-item label="申请时间">
            <el-input v-model="approveForm.applyTime" readonly />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="申请原因">
            <el-input v-model="approveForm.applyReason" type="textarea" readonly :rows="3" />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="审批意见" prop="auditComment" required>
            <el-input v-model="approveForm.auditComment" type="textarea" placeholder="请输入审批意见" :rows="4" :validate-event="false" />
          </el-form-item>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="approveDialog.visible = false">取消</el-button>
        <el-button type="success" @click="submitApprove('1')">通过</el-button>
        <el-button type="danger" @click="submitApprove('2')">拒绝</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Version" lang="ts">
import {
  listVersion,
  getVersion,
  delVersion,
  addVersion,
  updateVersion,
  changeMesVsersionStatus,
  getStatusApply,
  changeStatusApprove,
  listVersionByAudit
} from '@/api/msg/version';
import { VersionVO, VersionQuery, VersionForm } from '@/api/msg/version/types';
import { TemplateInfoVO } from '@/api/print/template/templateInfotypes';
import { changeTemplateVsersionStatus } from '@/api/print/template';
import { constructModuleEnumTree, queryMSMTemplateList, getStatusLog, getAuditHistory } from '@/api/msg/mestemp';
import { getServiceConfig } from '@/api/msg/smsmanual/manual';
import { parseTime } from '@/utils/ruoyi';

//====模板名称模糊查询相关
const selectedTemplateValue = ref('');
const likeName = ref('');
const filterByTemplateName = () => {
  if (!likeName.value) {
    filteredList.value = templateList.value;
    return;
  }

  const searchText = likeName.value.toLowerCase();
  filteredList.value = templateList.value.filter(
    (item) => item.templateName.toLowerCase().includes(searchText) || item.templateCode.toLowerCase().includes(searchText)
  );
};
const clearTemplateSelection = () => {
  queryParams.value.templateCode = undefined;
};

//===============审批对话框相关开始
// 新增: 审批对话框相关变量
const approveDialog = reactive({
  visible: false,
  title: '审批申请'
});

const approveForm = reactive({
  auditId: undefined,
  templateId: undefined,
  templateName: '',
  templateCode: '',
  templateType: '',
  currentStatus: '',
  targetStatus: '',
  applyUserName: '',
  applyTime: '',
  applyReason: '',
  auditComment: ''
});

// 新增: 处理审批操作
const handleApprove = async (row: VersionVO) => {
  try {
    // 获取申请详情
    const res = await getStatusApply({ templateId: row.templateId });

    // 填充审批表单
    Object.assign(approveForm, res.data);
    approveForm.auditComment = '';

    approveDialog.title = `审批 - ${row.templateName}`;
    approveDialog.visible = true;
  } catch (error) {
    proxy?.$modal.msgError('获取申请详情失败');
  }
};

// 新增: 提交审批
const submitApprove = async (auditStatus: string) => {
  if (!approveForm.auditComment) {
    proxy?.$modal.msgWarning('请填写审批意见');
    return;
  }

  try {
    // 准备审批数据
    const approveData = {
      auditId: approveForm.auditId,
      auditStatus: auditStatus,
      auditComment: approveForm.auditComment,
      templateId: approveForm.templateId,
      templateCode: approveForm.templateCode,
      templateName: approveForm.templateName,
      templateType: approveForm.templateType,
      currentStatus: approveForm.currentStatus,
      targetStatus: approveForm.targetStatus
    };
    //  console.log('提交审批数据:', approveData);
    // 提交审批
    await changeStatusApprove(approveData);

    proxy?.$modal.msgSuccess('审批已提交');
    approveDialog.visible = false;
    getList(); // 刷新列表
  } catch (error) {
    proxy?.$modal.msgError('提交审批失败');
  }
};
// ================审批对话框结束

//============启停记录开始
// 新增: 日志标签页相关变量
const activeLogTab = ref('audit');
const operationLogs = ref<any[]>([]);
const auditLogs = ref<any[]>([]);
const operationLogTotal = ref(0);
const auditLogTotal = ref(0);
// 操作日志查询参数
const operationLogQuery = reactive({
  pageNum: 1,
  pageSize: 10,
  templateId: undefined
});
// 审核日志查询参数
const auditLogQuery = reactive({
  pageNum: 1,
  pageSize: 10,
  templateId: undefined
});

// +++ 新增: 启停记录相关变量 +++
const logDialogVisible = ref(false);
const logLoading = ref(false);
const statusLogs = ref<any[]>([]);
const logTotal = ref(0);
const currentTemplate = ref<any>(null);
// 启停记录查询参数
const logQueryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  templateId: undefined
});

// +++ 新增: 处理启停记录查询 +++
const handleStatusLog = (row: VersionVO) => {
  currentTemplate.value = row;
  logQueryParams.templateId = row.templateId;
  logDialogVisible.value = true;
  getStatusLogs();
};
// 修改: 获取启停记录
const getStatusLogs = async () => {
  try {
    logLoading.value = true;

    // 重置查询参数
    operationLogQuery.templateId = currentTemplate.value.templateId;
    auditLogQuery.templateId = currentTemplate.value.templateId;

    // 重置页码
    operationLogQuery.pageNum = 1;
    auditLogQuery.pageNum = 1;

    // 获取操作日志
    // await getOperationLogs();

    // 获取审核日志
    await getAuditLogs();
  } finally {
    logLoading.value = false;
  }
};
// 新增: 获取操作日志
const getOperationLogs = async () => {
  const requestData = {
    templateId: currentTemplate.value.templateId,
    pageNum: operationLogQuery.pageNum,
    pageSize: operationLogQuery.pageSize
  };

  const res = await getStatusLog(requestData);
  operationLogs.value = res.rows;
  operationLogTotal.value = res.total;
};

// 新增: 获取审核日志
const getAuditLogs = async () => {
  const requestData = {
    templateId: currentTemplate.value.templateId,
    pageNum: auditLogQuery.pageNum,
    pageSize: auditLogQuery.pageSize
  };

  const res = await getAuditHistory(requestData);
  auditLogs.value = res.rows;
  auditLogTotal.value = res.total;
};
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { msg_system, print_module, version_enable_status } = toRefs<any>(proxy?.useDict('msg_system', 'print_module', 'version_enable_status'));
// 新增：存储通道列表
const channels = ref<any[]>([]);
const versionList = ref<VersionVO[]>([]);
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 moduleTreeOptions = ref<any[]>([]);
const templateList = ref<any[]>([]);
const filteredList = ref<any[]>([]);
const moduleProps = {
  value: 'value',
  label: 'label',
  children: 'children',
  checkStrictly: true // 可以选择任意一级
};

const queryFormRef = ref<ElFormInstance>();
const versionFormRef = ref<ElFormInstance>();

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

const initFormData: VersionForm = {
  templateId: undefined,
  templateCode: undefined,
  templateType: undefined,
  templateName: undefined,
  system: undefined,
  module: undefined,
  versionNumber: undefined,
  templateContent: undefined,
  versionApplyStatus: undefined,
  versionEnableStatus: undefined,
  auditResult: undefined,
  rollbackReason: undefined,
  description: undefined,
  applyDate: undefined,
  modulePath: []
};
const data = reactive<PageData<VersionForm, VersionQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    templateCode: undefined,
    templateType: undefined,
    templateName: undefined,
    system: undefined,
    module: undefined,
    versionNumber: undefined,
    templateContent: undefined,
    versionApplyStatus: undefined,
    versionEnableStatus: undefined,
    auditResult: undefined,
    rollbackReason: undefined,
    description: undefined,
    applyDate: undefined,
    modulePath: [],
    params: {},
    smsSendChannel: undefined
  },
  rules: {
    templateId: [{ required: true, message: '模板唯一标识不能为空', trigger: 'blur' }],
    templateCode: [{ required: true, message: '模板编码不能为空', trigger: 'blur' }],
    templateType: [{ required: true, message: '模板类型 0短信 1邮件 2微信不能为空', trigger: 'change' }],
    templateName: [{ required: true, message: '模板名称不能为空', trigger: 'blur' }],
    versionNumber: [{ required: true, message: '版本号不能为空', trigger: 'blur' }],
    templateContent: [{ required: true, message: '模板内容不能为空', trigger: 'blur' }],
    versionApplyStatus: [{ required: true, message: '版本申请状态不能为空', trigger: 'change' }],
    versionEnableStatus: [{ required: true, message: '版本启用状态不能为空', trigger: 'change' }],
    auditResult: [{ required: true, message: '审核结论不能为空', trigger: 'blur' }],
    rollbackReason: [{ required: true, message: '回退原因不能为空', trigger: 'blur' }],
    description: [{ required: true, message: '说明不能为空', trigger: 'blur' }],
    applyDate: [{ required: true, message: '申请日期不能为空', trigger: 'blur' }]
  }
});

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

/** 查询短信模板版本管理列表 */
const getList = async () => {
  loading.value = true;
  const res = await listVersionByAudit(queryParams.value);
  versionList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

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

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

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

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

  // 重置模板搜索相关字段
  likeName.value = '';
  selectedTemplateValue.value = '';
  queryParams.value.templateName = undefined;
  queryParams.value.templateCode = undefined;
  // 重置过滤后的模板列表
  filteredList.value = templateList.value;

  // 重置其他查询参数
  queryParams.value.modulePath = [];
  queryParams.value.smsSendChannel = undefined;

  handleQuery();
};
// 新增：获取通道列表
const getSmsSendChannels = async () => {
  try {
    const res = await getServiceConfig();
    channels.value = res.data;
  } catch (error) {}
};
/** 多选框选中数据 */
const handleSelectionChange = (selection: VersionVO[]) => {
  ids.value = selection.map((item) => item.templateId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加短信模板版本管理';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: VersionVO) => {
  reset();
  const _templateId = row?.templateId || ids.value[0];
  const res = await getVersion(_templateId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改短信模板版本管理';
};

/** 提交按钮 */
const submitForm = () => {
  versionFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.templateId) {
        await updateVersion(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addVersion(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: VersionVO) => {
  const _templateIds = row?.templateId || ids.value;
  await proxy?.$modal.confirm('是否确认删除短信模板版本管理编号为"' + _templateIds + '"的数据项？').finally(() => (loading.value = false));
  await delVersion(_templateIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'msg/version/export',
    {
      ...queryParams.value
    },
    `version_${new Date().getTime()}.xlsx`
  );
};

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

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

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];

    //  console.log('模块树数据:', moduleTreeOptions.value);
  } catch (error) {
    moduleTreeOptions.value = [];
  }
};

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();
  getModuleTree();
  quryTemplateList('auditPass').then(() => {
    // 初始化时显示所有模板选项
    filteredList.value = templateList.value;
  });
  getSmsSendChannels();
});
// 新增：根据通道ID获取通道名称的方法
const getChannelName = (channelId: string) => {
  const channel = channels.value.find((ch) => ch.providerId === channelId);
  return channel ? channel.providerName : channelId;
};
/**
 * 版本是否启用方法
 *
 */
const handleStatusChange = async (row: VersionVO) => {
  if (!row.smsSendChannel) {
    proxy?.$modal.alert('不选择短信通道，不能做版本启用');
    row.versionEnableStatus = row.versionEnableStatus === 'Y' ? 'N' : 'Y'; // 恢复开关状态
    return;
  }
  let text = row.versionEnableStatus === 'Y' ? '启用' : '停用';
  try {
    await proxy?.$modal.confirm('确认要"' + text + '""' + row.templateName + '"模版吗?');
    await changeMesVsersionStatus(row);
    proxy?.$modal.msgSuccess(text + '成功');
  } catch {
    row.versionEnableStatus = row.versionEnableStatus === 'Y' ? 'N' : 'Y';
  }
};
// +++ 添加 watch 监听模块路径变化 +++
watch(
  () => queryParams.value.modulePath,
  (newVal) => {
    if (newVal && newVal.length > 0) {
      // 取最后一级作为模块值
      queryParams.value.module = newVal[newVal.length - 1];
    } else {
      queryParams.value.module = undefined;
    }
  }
);
</script>
