<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-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="emailtempList" @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" prop="emailType">
          <template #default="scope">
            <dict-tag :options="msg_email_type" :value="scope.row.emailType" />
          </template>
        </el-table-column>

        <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 label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="详情" placement="top">
              <el-button v-hasPermi="['msg:viewemail:detail']" 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>
  </div>
</template>

<script setup name="Emailtemp" lang="ts">
import { addEmailtemp, updateEmailtemp, queryControlVersionList, queryEmailTemplateList } from '@/api/msg/emailtemp';
import { EmailtempVO, EmailtempQuery, EmailtempForm } from '@/api/msg/emailtemp/types';
import { constructModuleEnumTree } from '@/api/msg/mestemp';

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

const emailtempList = ref<EmailtempVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const templateId = ref(null);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const queryFormRef = ref<ElFormInstance>();
const emailtempFormRef = ref<ElFormInstance>();
const templateList = ref([]); // 存储所有模板数据
const filteredList = ref([]); // 存储过滤后的模板数据
const likeName = ref(''); // 存储用户输入的模糊查询关键词
const moduleTreeOptions = ref<any[]>([]);

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

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
};
const data = reactive<PageData<EmailtempForm, EmailtempQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    templateCode: undefined,
    templateName: undefined,
    system: undefined,
    module: undefined,
    applyDate: undefined,
    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' }],
    system: [{ required: true, message: '归属系统不能为空', trigger: 'blur' }],
    module: [{ required: true, message: '归属模块不能为空', trigger: 'blur' }],
    templateContent: [{ required: true, message: '模板内容不能为空', trigger: 'blur' }],
    emailType: [{ required: true, message: '邮件类型 0内网邮件 1外网邮件不能为空', trigger: 'change' }],
    // versionApplyStatus: [{ required: true, message: '版本申请状态不能为空', trigger: 'change' }],
    // versionEnableStatus: [{ required: true, message: '版本启用状态不能为空', trigger: 'change' }],
    description: [{ required: true, message: '说明不能为空', trigger: 'blur' }]
    // applyDate: [{ required: true, message: '申请日期不能为空', trigger: 'blur' }]
  }
});

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

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

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

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

const getList = async () => {
  loading.value = true;
  const res = await queryControlVersionList(queryParams.value);
  emailtempList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

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

/** 获取所有已审核通过的模板列表 */
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];
  //  console.log('queryParams:' + queryParams.value.templateCode);
};

const handleUpdate = async (row?: EmailtempVO) => {
  proxy.$router.push({
    path: '/msg/template/email/templatedetail/',
    query: {
      templateId: row.templateId,
      sign: 'view'
    }
  });
};

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();
  quryTemplateList('auditPass');
  getModuleTree();
});
</script>
