<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="emailtempFormRef" :model="form" :rules="rules" :inline="true" label-width="130px" label-position="left">
            <el-row :gutter="0">
              <el-form-item label="模板编码" prop="templateCode">
                <el-select v-model="form.templateCode" placeholder="请输入模版编码" :disabled="sign === 'audit'" clearable @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-row>
            <el-row :gutter="0">
              <el-form-item label="邮件类型" prop="emailType">
                <el-select v-model="form.emailType" placeholder="请选择归属系统" :disabled="sign === 'audit'">
                  <el-option v-for="dict in msg_email_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="邮件名称" prop="templateName">
                <el-input v-model="form.templateName" placeholder="请输入邮件名称" :disabled="form.auditResult === '1'" />
              </el-form-item>
              <el-form-item label="归属系统" prop="system">
                <el-select v-model="form.system" placeholder="请选择归属系统" :disabled="form.auditResult === '1'">
                  <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-row>
            <el-row :gutter="0">
              <el-form-item label="归属模块" prop="module">
                <el-cascader
                  v-model="form.module"
                  :options="moduleTreeOptions"
                  :props="moduleProps"
                  :show-all-levels="false"
                  :disabled="sign === 'audit'"
                  placeholder="请选择渠道"
                  clearable
                  filterable
                  style="width: 100%"
                />
              </el-form-item>
              <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">
                <el-input
                  v-model="form.description"
                  type="textarea"
                  :disabled="sign === 'audit'"
                  style="width: 300px"
                  rows="4"
                  show-word-limit
                  maxlength="1000"
                />
              </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
                :model-value="emailContent"
                ::read-only="sign === 'audit'"
                :file-size="0.5"
                height="150px"
                @update:model-value="handleContentUpdate"
              />
            </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 v-if="showFileSearch" :gutter="0" style="width: 300px">-->
            <!--              <el-form-item label="附件类型" prop="attachmentType">-->
            <!--                <el-select v-model="form.attachmentType" placeholder="请选择附件类型">-->
            <!--                  <el-option v-for="dict in email_attachment_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>-->
            <!--                </el-select>-->
            <!--              </el-form-item>-->
            <!--            </el-row>-->

            <!--            <el-row v-if="showFileSearch" :gutter="0" style="width: 800px">-->
            <!--              <el-form-item label="上传文件" prop="file">-->
            <!--                <FileUpload-->
            <!--                  ref="fileUploadRef"-->
            <!--                  :file-size="10"-->
            <!--                  :file-type="fileType"-->
            <!--                  :show-file-list="false"-->
            <!--                  :before-upload="handleBeforeUpload"-->
            <!--                  @update:model-value="handleFileListUpdate"-->
            <!--                />-->
            <!--              </el-form-item>-->
            <!--            </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-column label="操作" align="center" class-name="small-padding fixed-width">-->
            <!--                  <template #default="scope">-->
            <!--                    <el-tooltip content="删除" placement="top">-->
            <!--                      <el-button-->
            <!--                        v-hasPermi="['msg:emailtemp:remove']"-->
            <!--                        link-->
            <!--                        type="primary"-->
            <!--                        icon="Delete"-->
            <!--                        @click="handleFileDelete(scope.row)"-->
            <!--                      ></el-button>-->
            <!--                    </el-tooltip>-->
            <!--                  </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"> </el-table-column>-->
            <!--                <el-table-column label="风控规则描述" align="center" prop="description" />-->
            <!--                <el-table-column label="风控规则参数" align="center" prop="riskControlParam" />-->
            <!--                <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:emailrisk:remove']" link type="primary" icon="Delete" @click="handleDelete(scope.row)"></el-button>-->
            <!--                    </el-tooltip>-->
            <!--                  </template>-->
            <!--                </el-table-column>-->
            <!--              </el-table>-->
            <!--            </el-row>-->
            <!--            <el-row :gutter="0">-->
            <!--              <el-button type="primary" @click="handleQuery">+</el-button>-->
            <!--            </el-row>-->
            <msg-risk-control ref="msgRiskControlRef" :disabled="sign === 'audit'"></msg-risk-control>
          </el-form>
          <template #footer>
            <div class="dialog-footer">
              <el-button
                v-if="sign !== 'audit' && sign !== 'view'"
                v-hasPermi="['msg:emailtemp:confirm']"
                :loading="buttonLoading"
                type="primary"
                @click="submitForm"
                >确 定</el-button
              >
              <el-button
                v-if="sign === 'add' || sign === 'update'"
                v-hasPermi="['msg:emailtemp:editstatus']"
                type="primary"
                :disabled="!hasConfirmed"
                @click="handleEditStatus"
                >模板确认</el-button
              >
              <el-button v-if="sign !== 'audit'" @click="cancel">关闭页面</el-button>
              <el-button
                v-if="sign === 'audit'"
                v-hasPermi="['msg:emailtemp:auditpassed']"
                :loading="buttonLoading"
                type="primary"
                icon="Check"
                size="mini"
                style="margin-right: 20px"
                @click="handlePassed()"
                >审核通过</el-button
              >
              <el-button
                v-if="sign === 'audit'"
                v-hasPermi="['msg:emailtemp:auditfailed']"
                type="danger"
                icon="Close"
                size="mini"
                style="margin-right: 20px"
                @click="handleFailed()"
                >审核回退</el-button
              >
            </div>
          </template>
        </el-card>
        <el-dialog v-model="rollbackDialogVisible" title="审核回退原因" width="500px" :close-on-click-modal="false">
          <el-form>
            <el-form-item label="回退原因" prop="rollbackReason">
              <el-input v-model="form.rollbackReason" type="textarea" rows="4" maxlength="1000" placeholder="请输入回退原因" />
            </el-form-item>
          </el-form>
          <template #footer>
            <el-button @click="rollbackDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="confirmRollback">确 定</el-button>
          </template>
        </el-dialog>
      </div>
    </transition>
  </div>
</template>

<script setup lang="ts">
import { EmailtempForm, EmailtempQuery, EmailtempVO } from '@/api/msg/emailtemp/types';
import {
  addEmailtemp,
  editStatusEmailtemp,
  getEmailtemp,
  queryEmailTemplateList,
  updateEmailtemp,
  updateTemplateRiskControl
} from '@/api/msg/emailtemp';
import { constructModuleEnumTree, selectMSMTempByTempCode } from '@/api/msg/mestemp';
import { updateEmailAuditFailed, updateEmailAuditPassed } from '@/api/msg/emailaudit';
import MsgRiskControl from '@/views/msg/riskControl/msgRiskControl.vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const showSearch = ref(true);
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 emailContent = ref('');
const emailtempFormRef = ref<ElFormInstance>();
const templateId = ref('');
const sign = ref('');
const rollbackDialogVisible = ref(false);
const moduleTreeOptions = ref<any[]>([]);
const hasConfirmed = ref(false);
const msgRiskControlRef = ref();
const moduleProps = {
  value: 'value',
  label: 'label',
  children: 'children',
  checkStrictly: true,
  emitPath: false
};

const initFormData: EmailtempForm = {
  templateId: undefined,
  templateCode: undefined,
  templateType: undefined,
  templateName: undefined,
  system: undefined,
  module: undefined,
  versionNumber: undefined,
  templateContent: undefined,
  emailType: undefined,
  versionApplyStatus: undefined,
  versionEnableStatus: undefined,
  description: undefined,
  applyDate: undefined,
  rollbackReason: undefined
};
const data = reactive<PageData<EmailtempForm, EmailtempQuery>>({
  form: { ...initFormData },
  queryParams: {},
  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' }],
    emailType: [{ required: true, message: '邮件类型 0内网邮件 1外网邮件不能为空', trigger: 'blur' }],
    description: [{ required: true, message: '说明不能为空', trigger: 'blur' }]
  }
});
const { queryParams, form, rules } = toRefs(data);
const templateList = ref([]);
const filteredList = ref([]);
const likeName = ref('');
const buttonLoading = ref(false);

const selectTemp = async (newVal) => {
  try {
    const val = newVal.split('&');
    form.value.templateCode = val[0];

    form.value = {
      ...initFormData,
      templateCode: val[0],
      versionNumber: val[1]
    };

    const res = await selectMSMTempByTempCode(form.value);
    emailContent.value = res.data.templateContent;
    Object.assign(form.value, res.data);
    nextTick(() => {
      if (msgRiskControlRef.value) {
        msgRiskControlRef.value.loadingPage(form.value.templateId);
      }
    });
  } catch (error) {
    form.value = { ...initFormData };
    form.value.templateCode = '';
    form.value.versionNumber = '';
  }
};

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

/** 查询新增/修改页面已审核通过或正在定义模板编码以及详细信息 */
const quryTemplateList = async (codeSign) => {
  const res = await queryEmailTemplateList(codeSign);
  templateList.value = res.data.tempList;
  filteredList.value = templateList.value;
};
const handleContentUpdate = async (res: any) => {
  emailContent.value = res;
};

/** 提交按钮 */
const submitForm = () => {
  emailtempFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      form.value.templateContent = encodeURIComponent(emailContent.value);
      //  console.log(emailContent.value);
      if (sign.value === 'update') {
        await updateEmailtemp(form.value).finally(() => (buttonLoading.value = false));
        //  console.log(form.value);
        templateId.value = form.value.templateId;
        const riskControlData = getRiskControlData();
        //  console.log('风控规则数据:', riskControlData);
        const data = convertToRiskControlBos(riskControlData);
        //  console.log('请求数据：', data);
        await updateTemplateRiskControl(data);
        hasConfirmed.value = true;
      } else {
        form.value.templateId = '';
        const res = await addEmailtemp(form.value).finally(() => (buttonLoading.value = false));
        Object.assign(form.value, res.data);
        templateId.value = res.data.templateId;
        hasConfirmed.value = true;
        const riskControlData = getRiskControlData();
        const data = convertToRiskControlBos(riskControlData);
        await updateTemplateRiskControl(data);
        // const newPath = `/msg/template/email/templatedetail/${res.data.templateId}`;
        // const routeObj = { path: newPath };
        // proxy?.$tab.closePage();
        // proxy?.$tab.refreshPage(routeObj);
      }
      proxy?.$modal.msgSuccess('操作成功');
    }
  });
};

// 转换风险控制数据为后端需要的格式
const convertToRiskControlBos = (riskData) => {
  return riskData
    .map((item) => {
      // 对于每个参数键值对创建一个Bo对象
      return Object.entries(item.riskParams).map(([paramName, paramValue]) => ({
        templateId: templateId.value, // 从当前组件获取
        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 loadingPage = async () => {
  const res = await getEmailtemp(templateId.value);
  emailContent.value = res.data.templateContent;
  Object.assign(form.value, res.data);
};

//审核通过
const handlePassed = async () => {
  buttonLoading.value = true;
  await updateEmailAuditPassed(templateId.value);
  proxy?.$modal.msgSuccess('操作成功');
  buttonLoading.value = false;
  proxy?.$tab.closePage();
};

const handleFailed = () => {
  form.value.rollbackReason = ''; // 清空之前的内容
  rollbackDialogVisible.value = true;
  proxy?.$tab.closePage();
};

// 添加确认回退方法
const confirmRollback = async () => {
  if (!form.value.rollbackReason) {
    proxy?.$modal.msgError('请录入审核回退原因');
    return;
  }

  buttonLoading.value = true;
  //  console.log(form.value);
  try {
    await updateEmailAuditFailed(form.value);
    proxy?.$modal.msgSuccess('操作成功');
    rollbackDialogVisible.value = false;
  } catch (error) {
  } finally {
    buttonLoading.value = false;
  }
};

//审核回退
// const handleFailed = async () => {
//   if (!form.value.rollbackReason) {
//     alert('请录入审核回退原因');
//   } else {
//     await updateEmailAuditFailed(form.value);
//     proxy?.$modal.msgSuccess('操作成功');
//     dialog.visible = false;
//     await getList();
//   }
// };
const handleEditStatus = async () => {
  await proxy?.$modal.confirm('是否确认定义编号为"' + form.value.templateCode + '"的模板？');
  await editStatusEmailtemp(templateId.value);
  proxy?.$modal.msgSuccess('操作成功');
  proxy?.$tab.closePage();
};

const cancel = () => {
  proxy?.$tab.closePage();
};

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

onMounted(() => {
  const route = useRoute();
  const loadtemplateId = route.query.templateId as string | undefined;
  const loadSign = route.query.sign as string | undefined;

  if (loadtemplateId) {
    templateId.value = loadtemplateId;
    loadingPage();

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

  if (loadSign) {
    sign.value = loadSign;
  }
  quryTemplateList('auditPass');
  getModuleTree();
});
</script>

<style scoped lang="scss"></style>
