<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">
                <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.modulePath"
                :options="moduleTreeOptions"
                :props="moduleProps"
                :show-all-levels="false"
                placeholder="请选择所属模块"
                clearable
                filterable
                style="width: 100%"
              />
            </el-form-item>
            <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 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" 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>{{ getChannelName(scope.row.smsSendChannel) }}</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" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="查看详情" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">配置</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="通道配置记录" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button
              link
              type="primary"
              icon="View"
              @click="handleChannelLog(scope.row)"
              v-hasPermi="['msg:channel:log']"
            >
              通道记录
            </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="dialog.visible" :title="dialog.title" width="80%" 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-form-item label="短信名称" prop="templateName" label-width="100px">
            <el-input v-model="form.templateName" placeholder="请输入模板名称" readonly />
          </el-form-item>
        </el-row>
        <el-row>
          <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-form-item label="版本" prop="versionNumber" label-width="100px">
            <el-input v-model="form.versionNumber" placeholder="请输入版本号" readonly />
          </el-form-item>
        </el-row>

        <el-form-item label="短信内容" prop="templateContent" label-width="100px">
          <el-input v-model="form.templateContent" type="textarea" placeholder="请输入内容" style="width: 1200px" readonly />
        </el-form-item>
        <el-form-item label="增加/调整原因" prop="description" label-width="100px">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" style="width: 1200px" 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-table v-loading="loading" :data="temp" @selection-change="handleSelectionChange">-->
        <!--          <el-table-column type="selection" width="55" align="center" />-->
        <!--          <el-table-column label="风控规则编码" align="center" prop="templateCode" />-->
        <!--          <el-table-column label="风控规则描述" align="center" prop="templateName" />-->
        <!--          <el-table-column label="风控规则参数" align="center" prop="templateName" />-->
        <!--        </el-table>-->
        <msg-risk-control ref="msgRiskControlRef" :disabled="true"></msg-risk-control>
        <div style="margin-top: 20px">
          <el-row>
            <el-form-item label="发送通道" prop="smsSendChannel" label-width="100px">
              <el-select v-model="form.smsSendChannel" placeholder="请选择发送通道">
                <el-option v-for="dict in channel" :key="dict.providerId" :label="dict.providerName" :value="dict.providerId"></el-option>
              </el-select>
            </el-form-item>
          </el-row>
        </div>
      </el-form>
      <el-button v-hasPermi="['msg:smsSendChannel:save']" :loading="buttonLoading" type="primary" @click="save()">保存</el-button>
    </el-dialog>
    <el-dialog v-model="channelLogDialogVisible" title="通道配置记录" width="800px">
      <el-table :data="channelLogs" v-loading="channelLogLoading">
        <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="smsSendChannel" label="通道" align="center">
          <template #default="scope">
            <span>{{ getChannelName(scope.row.smsSendChannel) }}</span>
          </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="channelLogTotal > 0"
        small
        layout="prev, pager, next"
        v-model:page="channelLogQueryParams.pageNum"
        v-model:limit="channelLogQueryParams.pageSize"
        :total="channelLogTotal"
        @pagination="getChannelLogs"
      />
    </el-dialog>
  </div>
</template>

<script setup name="Version" lang="ts">
import { listVersion, saveSendChannels } from '@/api/msg/version';
import { VersionVO, VersionQuery, VersionForm } from '@/api/msg/version/types';
import { ReviewVO } from '@/api/msg/review/types';
import { getReview } from '@/api/msg/review';
import { constructModuleEnumTree, queryMSMTemplateList,getChannelLog  } from '@/api/msg/mestemp';
import { getServiceConfig } from '@/api/msg/smsmanual/manual';
import MsgRiskControl from '@/views/msg/riskControl/msgRiskControl.vue';
import { parseTime } from '@/utils/ruoyi';

// +++ 新增: 通道配置记录相关变量 +++
const channelLogDialogVisible = ref(false);
const channelLogLoading = ref(false);
const channelLogs = ref<any[]>([]);
const channelLogTotal = ref(0);
const currentChannelTemplate = ref<any>(null);
const channelLogQueryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  templateId: undefined
});
// +++ 新增: 处理通道配置记录查询 +++
const handleChannelLog = (row: VersionVO) => {
  currentChannelTemplate.value = row;
  channelLogQueryParams.templateId = row.templateId;
  channelLogDialogVisible.value = true;
  getChannelLogs();
};
// +++ 新增: 获取通道配置记录 +++
const getChannelLogs = async () => {
  try {
    channelLogLoading.value = true;

    const requestParams = {
      templateId: currentChannelTemplate.value.templateId,
      pageNum: channelLogQueryParams.pageNum,
      pageSize: channelLogQueryParams.pageSize
    };

    const res = await getChannelLog(requestParams);
    channelLogs.value = res.rows;
    channelLogTotal.value = res.total;
  } finally {
    channelLogLoading.value = false;
  }
};
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { msg_system, print_module } = toRefs<any>(proxy?.useDict('msg_system', 'print_module'));

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 channel = ref([]);
const moduleTreeOptions = ref<any[]>([]);
const templateList = ref<any[]>([]);
const filteredList = ref<any[]>([]);
const likeName = ref('');
const msgRiskControlRef = ref();
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,
  smsSendChannel: 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: {}
  },
  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 listVersion(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();
  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) => {
  reset();
  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 save = async () => {
  // 检查发送通道是否为空
  if (!form.value.smsSendChannel) {
    proxy?.$modal.alert('短信发送通道不能为空');
    return;
  }

  // 获取当前选中的通道 label
  const selectedChannel = channel.value.find((item) => item.providerId === form.value.smsSendChannel);
  const channelLabel = selectedChannel?.providerName;

  // 弹窗提示（非阻断，用户需手动确认）
  try {
    await ElMessageBox.confirm(`是否选择 "${channelLabel}" 作为 "${form.value.templateName}" 的发送通道？`, '确认保存', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    // 用户点击确认后，执行保存操作
    buttonLoading.value = true;
    await saveSendChannels(form.value);
    proxy?.$modal.msgSuccess('保存成功');
    dialog.visible = false;
  } catch (error) {
    // 用户点击取消时，不执行任何操作
    //  console.log('用户取消保存');
  } finally {
    buttonLoading.value = false;
    getList();
  }
};

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 = () => {
  if (likeName.value) {
    // 过滤操作
    filteredList.value = templateList.value.filter((item) => {
      return item.templateName.includes(likeName.value);
    });
  } else {
    // 如果 likeName 为空，显示原始列表
    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 getSmsSendChannel = async () => {
  const res = await getServiceConfig();
  channel.value = res.data;
  //  console.log(channel.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 = [];
  }
};

// 监听表单中的modulePath变化
watch(
  () => form.value.modulePath,
  (newVal) => {
    if (newVal && newVal.length > 0) {
      form.value.module = newVal[newVal.length - 1];
    } else {
      form.value.module = '';
    }
  }
);

// 监听查询参数中的modulePath变化
watch(
  () => queryParams.value.modulePath,
  (newVal) => {
    if (newVal && newVal.length > 0) {
      queryParams.value.module = newVal[newVal.length - 1];
    } else {
      queryParams.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;
});

// 获取通道名称的映射
const channelMap = computed(() => {
  const map: Record<string, string> = {};
  channel.value.forEach((item) => {
    map[item.providerId] = item.providerName;
  });
  return map;
});

// 获取通道名称的方法
const getChannelName = (id: string) => {
  return channelMap.value[id] || id;
};
onMounted(() => {
  getList();
  getSmsSendChannel();
  getModuleTree();
  quryTemplateList('auditPass');
});
</script>
