<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" @click="resetQuery">重置</el-button>
              <el-button v-hasPermi="['msg:emailtemp:add']" type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-if="false" v-hasPermi="['msg:emailtemp:add']" type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-if="false" v-hasPermi="['msg:emailtemp:editstatus']" type="primary" :disabled="single" @click="handleEditStatus()">模板确认</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="emailtempList" @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="模板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" disabled 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 label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="详情" placement="top">
              <el-button v-hasPermi="['msg:emailtemp:detail']" link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button v-hasPermi="['msg:emailtemp:remove']" link type="primary" icon="Delete" @click="handleDelete(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 {
  listEmailtemp,
  getEmailtemp,
  delEmailtemp,
  addEmailtemp,
  updateEmailtemp,
  attachmentList,
  editStatusEmailtemp,
  uploadTempFile,
  queryEmailTemplateList,
  deleteFile,
  getSelectTempCode,
  editParamsParsingtemp
} from '@/api/msg/emailtemp';
import { EmailtempVO, EmailtempQuery, EmailtempForm } from '@/api/msg/emailtemp/types';
import { constructModuleEnumTree, queryMSMTemplateList, selectMSMTempByTempCode } 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 router = useRouter();

const emailtempList = ref<EmailtempVO[]>([]);
const fujian = 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 dateRangeApply = ref<[DateModelType, DateModelType]>(['', '']);
const queryFormRef = ref<ElFormInstance>();
const emailtempFormRef = ref<ElFormInstance>();
const tempCode = ref([]);
const fileType = ref(['xlsx', 'pdf', 'docx']);
const fileLoading = ref(false);
const fileList = ref([]);
const paramsLoading = ref(false);
const disabled = ref(false);
const templateList = ref([]); // 存储所有模板数据
const filteredList = ref([]); // 存储过滤后的模板数据
const likeName = ref(''); // 存储用户输入的模糊查询关键词
const moduleTreeOptions = ref<any[]>([]);

const data = reactive<SinglePageData<EmailtempQuery>>({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    templateCode: undefined,
    templateName: undefined,
    system: undefined,
    module: undefined,
    applyDate: undefined,
    params: {}
  },
  rules: {}
});
const { queryParams, rules } = toRefs(data);

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

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  emailtempFormRef.value?.resetFields();
  fileList.value = [];
};

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

/** 重置按钮操作 */
const resetQuery = () => {
  dateRangeApply.value = ['', ''];
  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 handleAdd = () => {
  // router.push('/msg/template/email/templatedetail');
  proxy.$router.push({
    path: '/msg/template/email/templatedetail/',
    query: {
      templateId: '',
      sign: 'add'
    }
  });
};

const getList = async () => {
  loading.value = true;
  queryParams.value = proxy?.addDateRange(queryParams.value, dateRangeApply.value, 'Apply');
  const res = await listEmailtemp(queryParams.value);
  emailtempList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 修改按钮操作 */
const handleUpdate = async (row?: EmailtempVO) => {
  //router.push('/msg/template/email/templatedetail/' + row.templateId);
  proxy.$router.push({
    path: '/msg/template/email/templatedetail/',
    query: {
      templateId: row.templateId,
      sign: 'update'
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: EmailtempVO) => {
  const _templateIds = row?.templateId || ids.value;
  await proxy?.$modal
    .confirm('是否要删除"' + row.templateName + '",版本号为"' + row.versionNumber + '"的模板信息？')
    .finally(() => (loading.value = false));
  await delEmailtemp(_templateIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};
const handleEditStatus = async (row?: EmailtempVO) => {
  const templateId = row?.templateId || ids.value[0];
  await proxy?.$modal.confirm('是否确认定义编号为"' + templateId + '"的模板？').finally(() => (loading.value = false));
  await editStatusEmailtemp(templateId);
  proxy?.$modal.msgSuccess('操作成功');
  await getList();
};

const handleParamsParsing = async (row?: EmailtempVO) => {
  const templateId = row?.templateId || ids.value[0];
  await proxy?.$modal.confirm('是否确认解析编号为"' + templateId + '"的模板参数？').finally(() => (loading.value = false));
  await editParamsParsingtemp(templateId);
  proxy?.$modal.msgSuccess('操作成功');
  await getList();
};
const handleBeforeUpload = () => {
  if (!form.value.attachmentType) {
    alert('请先选择附件类型！');
    return;
  }
};
const handleFileListUpdate = async (res: any) => {
  fileLoading.value = true;
  try {
    await uploadTempFile(res, form.value.templateId, form.value.attachmentType);
  } catch (error) {}
  await queryPageList();
  fileLoading.value = false;
};

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

const handleFileDelete = (row) => {
  proxy?.$modal.confirm('确定要删除吗？').then(async () => {
    fileLoading.value = true;
    paramsLoading.value = true;
    await deleteFile(row.attachmentId);
    await queryPageList();
    proxy?.$modal.msgSuccess('删除成功');
  });
};

/** 获取所有已审核通过的模板列表 */
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 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('apply');
  getModuleTree();
});
</script>
