<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 v-if="false" label="归属模块" prop="module">
              <el-cascader
                v-model="queryParams.module"
                :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-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="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="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 align="center" label="是否启用" prop="versionEnableStatus">
          <template #default="scope">
            <el-switch v-model="scope.row.versionEnableStatus" active-value="Y" inactive-value="N" :disabled="true"></el-switch>
          </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" 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:viewsms:query']" link type="primary" icon="Edit" @click="handleUpdate(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="95%" append-to-body>
      <el-form ref="mestempFormRef" :model="form" :rules="rules" :inline="true">
        <el-row>
          <el-form-item label="短信编码" prop="templateCode" label-width="100px">
            <el-input v-model="form.templateCode" placeholder="请输入模板编码" readonly />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="短信名称" prop="templateName" label-width="100px">
            <el-input v-model="form.templateName" placeholder="请输入模板名称" readonly />
          </el-form-item>
          <el-form-item label="归属系统" prop="system" label-width="100px">
            <el-select v-model="form.system" placeholder="请选择所属系统" disabled>
              <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" label-width="100px">
            <el-cascader
              v-model="form.modulePath"
              :options="moduleTreeOptions"
              :props="moduleProps"
              :show-all-levels="false"
              placeholder="请选择所属模块"
              disabled
              style="width: 100%"
            />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="版本" prop="versionNumber" label-width="100px">
            <el-input v-model="form.versionNumber" placeholder="请输入版本号" readonly />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="短信内容" prop="templateContent" label-width="100px">
            <el-input v-model="form.templateContent" type="textarea" placeholder="请输入内容" style="width: 800px" readonly />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="增加/调整原因" prop="description" label-width="100px">
            <el-input v-model="form.description" type="textarea" placeholder="请输入内容" style="width: 800px" readonly />
          </el-form-item>
          <el-form-item v-if="false" label="申请日期" prop="applyDate">
            <el-date-picker v-model="form.applyDate" clearable type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择申请日期">
            </el-date-picker>
          </el-form-item>
        </el-row>
        <!-- 风控规则模板-->
        <msg-risk-control ref="msgRiskControlRef" :disabled="true"></msg-risk-control>
      </el-form>
    </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="applicant" align="center" />
        <el-table-column label="申请时间" prop="applyDate" align="center" />
        <el-table-column label="部门编号" prop="deptId" align="center" />
        <el-table-column label="审核人" prop="auditer" align="center" />
        <el-table-column label="审核时间" prop="auditTime" align="center" />

        <el-table-column label="审批结果" prop="auditResult" align="center">
          <template #default="scope">
            <el-tag v-if="scope.row.auditResult === '0'" type="warning">未审批</el-tag>
            <el-tag v-else-if="scope.row.auditResult === '1'" type="success">审批通过</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="回退原因" prop="rollbackReason" align="center" />
      </el-table>

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

<script setup name="Version" lang="ts">
import { listVersion } from '@/api/msg/version';
import { VersionVO, VersionQuery, VersionForm } from '@/api/msg/version/types';
import { constructModuleEnumTree, queryMSMTemplateList } from '@/api/msg/mestemp';
import { ReviewVO } from '@/api/msg/review/types';
import { getReview } from '@/api/msg/review';
import MsgRiskControl from '@/views/msg/riskControl/msgRiskControl.vue';
import { queryAuditInfo } from '@/api/msg/viewsms';
// 新增：导入获取短信通道的API
import { getServiceConfig } from '@/api/msg/smsmanual/manual';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { msg_system, print_module } = toRefs<any>(proxy?.useDict('msg_system', 'print_module'));
// 新增：模糊查询输入值
const likeName = ref('');
const clearTemplateSelection = () => {
  queryParams.value.templateCode = undefined; // 清除模板编码参数
};

// 在setup中添加响应式变量
const approvalDialog = reactive({
  visible: false,
  title: '审批流程查看'
});
const approvalLoading = ref(false);
const approvalProcessList = 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 msgRiskControlRef = ref();
// 新增：存储通道列表
const channels = 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: {}
});
// 添加查看审批流程方法
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 listVersion(queryParams.value);
  versionList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

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

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  // 重置级联选择器路径和短信通道
  queryParams.value.modulePath = [];
  queryParams.value.smsSendChannel = undefined;
  // 重置模板名称输入框
  likeName.value = '';
  queryParams.value.templateName = undefined; // 添加这行
  queryParams.value.templateCode = undefined;
  // 过滤后的列表
  filteredList.value = templateList.value;
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: VersionVO[]) => {
  ids.value = selection.map((item) => item.templateId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 修改按钮操作 */
const handleUpdate = async (row?: ReviewVO) => {
  const _templateId = row?.templateId || ids.value[0];
  const res = await getReview(_templateId);
  Object.assign(form.value, res.data);
  form.value.modulePath = findModulePath(form.value.module);
  dialog.visible = true;
  dialog.title = '查看短信模板配置';
  // 确保弹窗完全渲染后再加载风控规则
  nextTick(() => {
    if (msgRiskControlRef.value) {
      msgRiskControlRef.value.loadingPage(_templateId);
    }
  });
};

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

const quryTemplateList = async (codeSign) => {
  const res = await queryMSMTemplateList(codeSign);
  templateList.value = res.data.tempList;
  filteredList.value = templateList.value;
};
// 修改：实现模糊查询方法
const filterByTemplateName = (query = '') => {
  if (query) {
    // 使用trim()去除首尾空格，并转为小写进行不区分大小写的匹配
    const searchText = query.trim().toLowerCase();
    filteredList.value = templateList.value.filter(
      item =>
        item.templateName.toLowerCase().includes(searchText) ||
        item.templateCode.toLowerCase().includes(searchText)
    );
  } else {
    // 如果没有输入，则显示全部
    filteredList.value = templateList.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 getSmsSendChannels = async () => {
  try {
    const res = await getServiceConfig();
    channels.value = res.data;
  } catch (error) {
  }
};

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 = [];
  }
};

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;
});

// 新增：监听模块路径变化，将最后一级赋值给module
watch(
  () => queryParams.value.modulePath,
  (newVal) => {
    if (newVal && newVal.length > 0) {
      // 取最后一级作为模块值
      queryParams.value.module = newVal[newVal.length - 1];
    } else {
      queryParams.value.module = undefined;
    }
  }
);

onMounted(() => {
  getList();
  getModuleTree();
  quryTemplateList('auditPass');
  // 新增：获取短信通道列表
  getSmsSendChannels();
});
</script>
