<template>
  <el-card shadow="hover">
    <el-row>
      <el-form-item label="模版附件" prop="materialAttfile">
        <!--@update:modelValue="handleFileListUpdate" 定义的是回调函数 -->
        <!-- v-model:modelValue="fileList" 引用组件监听的modelValue事件，通过fileList值清空引用的组件 -->
        <FileUpload
          ref="fileUploadRef"
          v-hasPermi="['print:temp:upload']"
          :file-size="10"
          :file-type="fileType"
          :show-file-list="false"
          @update:model-value="handleFileListUpdate"
        />
      </el-form-item>
    </el-row>
    <el-row>
      <el-table v-loading="fileLoading" :data="fileList" style="width: 580px">
        <el-table-column align="center" label="附件名称" prop="originalName" />
        <el-table-column v-if="showColumn" align="center" label="打印顺序" prop="printOrder">
          <template #default="scope">
            <el-input v-model="scope.row.printOrder" placeholder="打印顺序" @blur="handleBlurOrder(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column align="center" class-name="small-padding fixed-width" label="操作" width="240px">
          <template #default="scope">
            <el-button v-hasPermi="['print:temp:viewfile']" icon="View" link type="primary" @click="handleDownLoad(scope.row)">查看</el-button>
            <el-button
              v-if="tempInfo.versionRequestStatus !== '05'"
              v-hasPermi="['print:temp:deletefile']"
              icon="Delete"
              link
              type="primary"
              @click="handleDelete(scope.row)"
              >删除</el-button
            >
            <FileUpload
              v-if="tempInfo.versionRequestStatus !== '05'"
              v-hasPermi="['print:temp:reupload']"
              :file-size="10"
              :file-type="fileType"
              :is-show-button="true"
              :limit="1"
              :button-name="showButtonName"
              :button-icon="showButtonIcon"
              :is-show-tip="false"
              :show-file-list="false"
              @update:model-value="(uploadValue) => handleReUpdate(uploadValue, scope.row)"
            >
            </FileUpload>
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <el-row style="margin-top: 20px">
      <el-button v-hasPermi="['print:temp:paramsparsing']" icon="Setting" style="margin-left: 20px" type="primary" @click="ParamsParsing"
        >模版参数解析</el-button
      >
      <el-button v-hasPermi="['print:temp:lookWord']" icon="ChatLineRound" style="margin-left: 20px" type="primary" @click="lookWord"
        >word模版说明
      </el-button>
<!--      <el-button v-hasPermi="['print:temp:lookExcel']" icon="ChatLineRound" style="margin-left: 20px" type="primary" @click="lookExcel"-->
<!--        >Excel模版说明-->
<!--      </el-button>-->
    </el-row>
  </el-card>
  <el-card shadow="hover">
    <el-table v-loading="paramsLoading" :data="paramsList">
      <el-table-column align="center" label="附件名称" prop="originalName" />
      <el-table-column align="center" label="Sheet名称" prop="fileSheetName" />
      <el-table-column align="center" label="参数变量" prop="parameterName" />
      <el-table-column align="center" label="参数类型" prop="parameterType" />
      <el-table-column align="center" label="变量名称" prop="parameterDesc">
        <template #default="scope">
          <el-input v-model="scope.row.parameterDesc" placeholder="变量名称" @blur="handleBlur(scope.row)" />
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" v-model:limit="pageSize" v-model:page="pageNum" :total="total" @pagination="paramsList" />
  </el-card>
  <WordExplanation ref="wordRef" />
  <ExcelExplanation ref="excelRef" />
</template>
<script lang="ts" name="TemplateModule" setup>
import WordExplanation from '@/views/print/template/module/wordExplanation.vue';
import ExcelExplanation from '@/views/print/template/module/excelExplanation.vue';
import {
  deleteFile,
  paramsParsing,
  paramsUpdate,
  queryFileList,
  reUploadTempFile,
  templetToTest,
  updateTempFile,
  uploadTempFile
} from '@/api/print/template';
import { to } from 'await-to-js';
import { TemplateInfoVO } from '@/api/print/template/templateInfotypes';

const router = useRouter();
const { proxy } = getCurrentInstance();
const fileType = ref(['xlsx', 'pdf', 'docx']);
const fileLoading = ref(false);
const fileList = ref([]);
const paramsLoading = ref(false);
const paramsList = ref([]);
const templateID = ref(null);
const showColumn = ref(false);
const tempInfo = ref<TemplateInfoVO>();

const wordRef = ref<InstanceType<typeof WordExplanation>>();
const excelRef = ref<InstanceType<typeof ExcelExplanation>>();

const pageNum = ref(1);
const pageSize = ref(10);
const total = ref(0);

const showButtonName = ref('替换');
const showButtonIcon = ref('Edit');

const handleFileListUpdate = async (res: any) => {
  // 检查是否允许多文件
  if (tempInfo.value.multiTemplate === 'N' && fileList.value.length >= 1) {
    proxy?.$modal.alert('本模板当前版本不允许使用多文件模式，如需修改请返回基础信息进行修改');
    return; // 阻断上传
  }

  fileLoading.value = true;
  try {
    await uploadTempFile(res, templateID.value);
  } catch (error) {}
  await queryPageList();
  fileLoading.value = false;
};
const handleBlurOrder = async (row) => {
  if (!validatePrintOrder(row)) {
    return;
  }
  fileLoading.value = true;
  await updateTempFile(row);
  proxy?.$modal.msgSuccess('参数保存成功');
  fileLoading.value = false;
};

const validatePrintOrder = (row) => {
  // 1. 检查是否为有效正整数
  const printOrder = parseInt(row.printOrder, 10);
  if (isNaN(printOrder) || printOrder <= 0 || !Number.isInteger(printOrder)) {
    proxy?.$modal.msgError('打印顺序必须为正整数');
    return false;
  }

  // 2. 获取所有已存在的打印顺序
  const existingOrders = fileList.value
    .filter((item) => item !== row) // 排除当前正在编辑的行
    .map((item) => parseInt(item.printOrder, 10))
    .filter((order) => !isNaN(order) && order > 0);

  // 3. 添加当前值并检查连续性
  const allOrders = [...existingOrders, printOrder].sort((a, b) => a - b);

  // 检查是否形成连续自然数序列（从1开始）
  for (let i = 0; i < allOrders.length; i++) {
    if (allOrders[i] !== i + 1) {
      proxy?.$modal.msgError(`打印顺序必须组成连续序列(1,2,3...)，当前缺少 ${i + 1}`);
      return false;
    }
  }

  return true;
};

const lookWord = () => {
  wordRef.value?.show();
};
const lookExcel = () => {
  excelRef.value?.show();
};
const queryPageList = async () => {
  fileLoading.value = true;
  paramsLoading.value = true;
  const res = await queryFileList(templateID.value);
  fileList.value = res.data.attachments;
  paramsList.value = res.data.params;
  tempInfo.value = res.data.tempInfo;
  fileLoading.value = false;
  paramsLoading.value = false;
};

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

const handleBlur = async (row) => {
  paramsLoading.value = true;
  try {
    const res = await paramsUpdate(row);
    if (res.code == 200) {
      proxy?.$modal.msgSuccess('参数保存成功');
    }
  } catch (e) {
    row.parameterDesc = undefined;
  } finally {
    paramsLoading.value = false;
  }
};

const getTemp = async (templateId: string | number) => {
  templateID.value = templateId;
  await queryPageList();
};
const nextStep = async (callback) => {
  // 检查文件列表中的打印顺序
  if (fileList.value.length > 1) {
    for (let i = 0; i < fileList.value.length; i++) {
      const printOrder = parseInt(fileList.value[i].printOrder, 10);
      if (isNaN(printOrder) || printOrder <= 0) {
        proxy?.$modal.msgError('打印顺序必须维护');
        return;
      }
    }
  }

  // 根据参数列表的状态显示确认对话框
  let confirmMessage;
  if (paramsList.value.length === 0) {
    confirmMessage = '附件参数为空，请确认已做过【参数解析】？';
  } else {
    confirmMessage = '所有附件均已上传并【参数解析】？';
  }

  const confirmationResult = await proxy?.$modal.confirm(confirmMessage);
  if (!confirmationResult) {
    // 如果用户取消了确认对话框，则不继续执行
    return;
  }
  await templetToTest(templateID.value);
  callback();
};

const handleReUpdate = async (uploadValue: any, row) => {
  fileLoading.value = true;
  try {
    const data = {
      newOssid: uploadValue,
      oldOssid: row.ossId,
      attachmentId: row.attachmentId
    };
    await reUploadTempFile(data);
  } catch (error) {}
  await queryPageList();
  fileLoading.value = false;
};

watch(fileList, (newList) => {
  if (newList.length > 1) {
    showColumn.value = true;
  } else {
    showColumn.value = false;
  }
});

onMounted(() => {
  const route = useRoute();
  const templateId = route.params.templateId as string | undefined;
  if (templateId) {
    getTemp(templateId);
  }
});

/**
 * 对外暴露子组件方法
 */
defineExpose({
  getTemp,
  nextStep
});
</script>
