<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-row>
              <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-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 filterable @change="selectTemp">
                  <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="申请日期">
                <el-date-picker
                  v-model="dateRangeApply"
                  value-format="YYYY-MM-DD"
                  type="daterange"
                  range-separator="-"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  style="width: 240px"
                >
                </el-date-picker>
              </el-form-item>
            </el-row>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" style="margin-left: 50px" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <el-table v-loading="loading" :data="emailAuditList" @selection-change="handleSelectionChange">
        <el-table-column v-if="false" type="selection" width="55" align="center" />
        <el-table-column v-if="false" label="模板唯一标识" align="center" prop="templateId" />
        <el-table-column label="模板ID" align="center" prop="templateCode" />
        <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 label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="查看" placement="top">
              <el-button v-hasPermi="['msg:emailaudit: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="1000px" append-to-body>
      <el-form ref="emailtempFormRef" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="0" style="width: 400px">
          <el-form-item label="模板编码" prop="templateCode" style="flex: 1">
            <el-select v-model="form.templateCode" placeholder="请输入模板编码" clearable filterable @change="selectTemp1">
              <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-row>
        <el-row :gutter="0">
          <el-form-item label="邮件名称" prop="templateName" style="flex: 1">
            <el-input v-model="form.templateName" placeholder="请输入邮件名称" :disabled="true" />
          </el-form-item>
          <el-form-item label="归属系统" prop="system" style="flex: 1">
            <el-select v-model="form.system" placeholder="请选择归属系统">
              <el-option v-for="dict in msg_system" :key="dict.value" :label="dict.label" :value="dict.value" :disabled="true"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="归属模块" prop="module" style="flex: 1">
            <el-select v-model="form.module" placeholder="请选择归属模块">
              <el-option v-for="dict in print_module" :key="dict.value" :label="dict.label" :value="dict.value" :disabled="true"></el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <el-row :gutter="0">
          <el-form-item label="版本号" prop="versionNumber">
            <el-input v-model="form.versionNumber" :disabled="true" />
          </el-form-item>
        </el-row>
        <el-row :gutter="0">
          <el-form-item label="增加/调整原因" prop="description" style="flex: 1">
            <el-input v-model="form.description" type="textarea" maxlength="1000" :disabled="true" />
          </el-form-item>
        </el-row>
        <el-row :gutter="0">
          <el-divider content-position="center"><span style="font-size: 15px; font-weight: bold">邮件模板</span></el-divider>
        </el-row>
        <el-form-item label="模板内容" prop="templateContent">
          <Editor v-model="form.templateContent" height="150px" :disabled="true" />
        </el-form-item>
        <el-row :gutter="0">
          <el-divider content-position="center"><span style="font-size: 15px; font-weight: bold">附件管理</span></el-divider>
        </el-row>
        <el-row :gutter="0">
          <el-table v-loading="loading" :data="fileList" @selection-change="handleSelectionChange">
            <el-table-column v-if="false" label="模板唯一标识" align="center" prop="attachmentId" />
            <el-table-column label="附件名称" align="center" prop="originalName" />
            <el-table-column label="附件类型" align="center" prop="attachmentType">
              <template #default="scope">
                <dict-tag :options="email_attachment_type" :value="scope.row.attachmentType" />
              </template>
            </el-table-column>
          </el-table>
        </el-row>
        <el-row :gutter="0">
          <el-divider content-position="center"><span style="font-size: 15px; font-weight: bold">风控规则</span></el-divider>
        </el-row>
        <el-row :gutter="0">
          <el-table v-loading="loading" :data="fujian" @selection-change="handleSelectionChange">
            <el-table-column v-if="false" label="风控唯一标识" align="center" prop="riskControlId" />
            <el-table-column label="风控规则编码" align="center" prop="riskControlCode">
              <!--template #default="scope">
                <dict-tag :options="msg_system" :value="scope.row.system" />
              </template>-->
            </el-table-column>
            <el-table-column label="风控规则描述" align="center" prop="description" />
            <el-table-column label="风控规则参数" align="center" prop="riskControlParam" />
          </el-table>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-hasPermi="['msg:emailtemp:auditpassed']"
            :loading="buttonLoading"
            type="primary"
            icon="Check"
            size="mini"
            style="margin-right: 20px"
            @click="handlePassed()"
            >审核通过</el-button
          >
          <el-button
            v-hasPermi="['msg:emailtemp:auditfailed']"
            type="danger"
            icon="Close"
            size="mini"
            style="margin-right: 20px"
            @click="handleFailed()"
            >审核回退</el-button
          >
        </div>
        <div style="width: 500px">
          <el-row :gutter="0">
            <el-form-item label="回退原因" prop="rollbackReason" style="flex: 1">
              <el-input v-model="form.rollbackReason" type="textarea" maxlength="1000" />
            </el-form-item>
          </el-row>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="EmailAudit" lang="ts">
import { listEmailAudit, updateEmailAuditFailed, updateEmailAuditPassed } from '@/api/msg/emailaudit';
import { EmailAuditVO, EmailAuditForm } from '@/api/msg/emailaudit/types';

import { EmailtempForm, EmailtempQuery, EmailtempVO } from '@/api/msg/emailtemp/types';
import { attachmentList, queryEmailTemplateList } from '@/api/msg/emailtemp';
import { constructModuleEnumTree } from '@/api/msg/mestemp';

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

const emailAuditList = ref<EmailtempVO[]>([]);
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 _templateId = ref(null);
const dateRangeApply = ref<[DateModelType, DateModelType]>(['', '']);
const tempCode = ref([]);
const fujian = ref<EmailtempVO[]>([]);
const fileList = ref([]);
const templateList = ref([]); // 存储所有模板数据
const filteredList = ref([]); // 存储过滤后的模板数据
const likeName = ref(''); // 存储用户输入的模糊查询关键词
const moduleTreeOptions = ref<any[]>([]);
const router = useRouter();
const queryFormRef = ref<ElFormInstance>();
const emailAuditFormRef = ref<ElFormInstance>();

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

const initFormData: EmailAuditForm = {
  auditId: undefined,
  templateId: undefined,
  templateCode: undefined,
  versionNumber: undefined,
  applicant: undefined,
  applicationTime: undefined,
  auditer: undefined,
  auditTime: undefined,
  auditResult: undefined,
  rollbackReason: undefined
};
const data = reactive<PageData<EmailtempForm, EmailtempQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    system: undefined,
    templateCode: undefined,
    templateName: undefined,
    module: undefined,
    params: {}
  },
  rules: {}
});

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

/** 查询申请、审核信息列表 */
const getList = async () => {
  loading.value = true;
  queryParams.value = proxy?.addDateRange(queryParams.value, dateRangeApply.value, 'Apply');
  const res = await listEmailAudit(queryParams.value);
  emailAuditList.value = res.rows;
  emailAuditList.value.map((item) => {
    const num = tempCode.value.findIndex((el) => el.label === item.templateCode);
    if (num === -1) {
      tempCode.value.push({
        label: item.templateCode,
        value: item.templateCode
      });
    }
  });
  total.value = res.total;
  loading.value = false;
};

/** 表单重置 */
const reset = () => {
  dateRangeApply.value = ['', ''];
  form.value = { ...initFormData };
  emailAuditFormRef.value?.resetFields();
};

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

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

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

/** 修改按钮操作 */
const handleUpdate = async (row?: EmailtempVO) => {
  // reset();
  // _templateId.value = row?.templateId || ids.value[0];
  // const res = await getEmailAudit(_templateId.value);
  // Object.assign(form.value, res.data);
  // await queryPageList();
  // dialog.visible = true;
  // dialog.title = '审核信息';
  // router.push('/msg/template/email/templatedetail/' + row.templateId);
  proxy.$router.push({
    path: '/msg/template/email/templatedetail/',
    query: {
      templateId: row.templateId,
      sign: 'audit'
    }
  });
};

/** 提交按钮 */ //关闭页面
const handlePassed = async () => {
  await updateEmailAuditPassed(_templateId.value);
  proxy?.$modal.msgSuccess('操作成功');
  dialog.visible = false;
  await getList();
};

const handleFailed = async () => {
  if (!form.value.rollbackReason) {
    alert('请录入审核回退原因');
  } else {
    await updateEmailAuditFailed(form.value);
    proxy?.$modal.msgSuccess('操作成功');
    dialog.visible = false;
    await getList();
  }
};

/** 查询消息模板配置列表 */
const queryPageList = async () => {
  const res = await attachmentList(form.value.templateId);
  fileList.value = res.data.attachments;
};

/** 获取所有已审核通过的模板列表 */
const quryTemplateList = async (codeSign) => {
  const res = await queryEmailTemplateList(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 {
    filteredList.value = templateList.value;
  }
};

/** 选择模板后的处理 */
const selectTemp = async (newVal) => {
  const val = newVal.split('&');
  queryParams.value.templateCode = val[0];
};

/** 选择模板后的处理 */
const selectTemp1 = async (newVal) => {
  const val = newVal.split('&');
  form.value.templateCode = val[0];
};

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

onMounted(() => {
  getList();
  quryTemplateList('audit');
  getModuleTree();
});
</script>

<style scoped>
.dialog-footer {
  text-align: left; /* 将按钮左对齐 */
  margin-bottom: 10px;
}
</style>
