<template>
  <div class="p-2">
    <el-row :gutter="20">
      <el-col :lg="24" :xs="24">
        <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-form-item label="模板编码" prop="templateCode">
                  <el-input v-model="queryParams.templateCode" placeholder="请输入模板编码" clearable @keyup.enter="handleQuery" />
                </el-form-item>
                <el-form-item label="模板名称" prop="templateName">
                  <el-input v-model="queryParams.templateName" placeholder="请输入模板名称" clearable @keyup.enter="handleQuery" />
                </el-form-item>
                <el-form-item label="模板类型" prop="templateType">
                  <el-select v-model="queryParams.templateType" placeholder="请选择模板类型" clearable>
                    <el-option v-for="dict in template_type" :key="dict.value" :label="dict.label" :value="dict.value" />
                  </el-select>
                </el-form-item>
                <el-form-item label="状态" prop="status">
                  <el-select v-model="queryParams.status" placeholder="模板状态" clearable>
                    <el-option v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.label" :value="dict.value" />
                  </el-select>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                  <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                </el-form-item>
              </el-form>
            </el-card>
          </div>
        </transition>
        <el-card shadow="hover">
          <template #header>
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button v-hasPermi="['system:template:add']" type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button v-hasPermi="['system:template:edit']" type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
                >修改</el-button
                >
              </el-col>
              <el-col :span="1.5">
                <el-button v-hasPermi="['system:template:remove']" type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()">
                  删除
                </el-button>
              </el-col>
              <!-- <el-col :span="1.5">
                <el-button v-hasPermi="['system:template:export']" type="warning" plain icon="Download" @click="handleExport">导出</el-button>
              </el-col> -->
              <right-toolbar v-model:show-search="showSearch" @query-table="getList"></right-toolbar>
            </el-row>
          </template>
          <el-table v-loading="loading" :data="templateList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="模板编号" align="center" prop="templateId" />
            <el-table-column label="模板编码" align="center" prop="templateCode" />
            <el-table-column label="模板名称" align="center" prop="templateName" />
            <el-table-column label="模板类型" align="center" prop="templateType">
              <template #default="scope">
                <dict-tag :options="template_type" :value="scope.row.templateType" />
              </template>
            </el-table-column>
            <el-table-column label="文件名" align="center" prop="originalName">
              <template #default="scope">
                {{ scope.row.originalName || scope.row.fileName || '未命名文件' }}
              </template>
            </el-table-column>
            <el-table-column label="文件大小" align="center" prop="fileSize">
              <template #default="scope">
                {{ formatFileSize(scope.row.fileSize) }}
              </template>
            </el-table-column>
            <el-table-column label="状态" align="center" prop="status">
              <template #default="scope">
                <dict-tag :options="sys_normal_disable" :value="scope.row.status" />
              </template>
            </el-table-column>
            <el-table-column label="创建时间" align="center" prop="createTime" width="180">
              <template #default="scope">
                <span>{{ proxy.parseTime(scope.row.createTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="250" align="center" class-name="small-padding fixed-width">
              <template #default="scope">
                <el-tooltip content="下载" placement="top">
                  <el-button v-hasPermi="['system:template:download']" link type="primary" icon="Download" @click="handleDownload(scope.row)"></el-button>
                </el-tooltip>
                <el-tooltip content="编辑" placement="top">
                  <el-button v-hasPermi="['system:template:edit']" link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
                </el-tooltip>
                <el-tooltip content="删除" placement="top">
                  <el-button v-hasPermi="['system:template: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>

        <!-- 引入模板表单组件 -->
        <template-form
          v-model:visible="formVisible"
          :edit-type="editType"
          :row-data="currentRow"
          @save="handleSave"
        />
      </el-col>
    </el-row>
  </div>
</template>

<script setup name="Template" lang="ts">
import { delTemplate, listTemplate } from '@/api/system/template';
import { delAttachments } from '@/api/common/syscommon';
import { TemplateQuery, TemplateVO } from '@/api/system/template/types';
import TemplateForm from './templateForm.vue';

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

// 表单控制状态
const formVisible = ref(false);
const editType = ref('');
const currentRow = ref<TemplateVO | null>(null);

const templateList = ref<TemplateVO[]>([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<number | string>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const queryFormRef = ref<ElFormInstance>();

// 查询参数
const queryParams = reactive<TemplateQuery>({
  pageNum: 1,
  pageSize: 10,
  templateCode: '',
  templateName: '',
  templateType: '',
  status: ''
});

/** 查询模板列表 */
const getList = async () => {
  loading.value = true;
  try {
    const res = await listTemplate(queryParams);
    templateList.value = res.rows;
    total.value = res.total;
  } finally {
    loading.value = false;
  }
};

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

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

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

/** 新增按钮操作 */
const handleAdd = () => {
  currentRow.value = null;
  editType.value = 'add';
  formVisible.value = true;
};

/** 修改按钮操作 */
const handleUpdate = (row?: TemplateVO) => {
  if (row) {
    currentRow.value = row;
  } else {
    const selectedTemplate = templateList.value.find((item) => item.templateId === ids.value[0]);
    currentRow.value = selectedTemplate || null;
  }
  editType.value = 'edit';
  formVisible.value = true;
};

/** 保存成功后的处理 */
const handleSave = () => {
  getList();
};

/** 下载按钮操作 */
const handleDownload = async (row: TemplateVO) => {
  try {
    // 使用统一的下载方法
    // proxy?.$download.attach('/resource/buscommon/download', row.attId, AttachBusCodeConstant.SYS_TEMPLATE_UPLOAD.code);
  } catch (error) {
    proxy?.$modal.msgError('下载失败');
  }
};

/** 删除按钮操作 */
const handleDelete = async (row?: TemplateVO) => {
  try {
    // 确定要删除的模板ID
    const templateIds = row?.templateId || ids.value;
    // 获取附件ID（单个删除时）
    let attachmentId = null;
    if (row && row.attId) {
      attachmentId = row.attId;
    }
    // 确认删除
    await proxy?.$modal.confirm('是否确认删除模板编号为"' + templateIds + '"的数据项？');
    // 删除模板
    const deleteResult = await delTemplate(templateIds);
    // 如果模板删除成功且有附件ID（单个删除时），删除关联的附件
    if (deleteResult.code === 200 && attachmentId) {
      try {
        // await delAttachments(attachmentId, AttachBusCodeConstant.SYS_TEMPLATE_UPLOAD.code);
      } catch (error) {
        // 这里只记录错误，不影响主流程
      }
    }
    // 重新加载列表
    await getList();
    proxy?.$modal.msgSuccess('删除成功');
  } catch (error) {
    if(error == 'cancel'){
      proxy?.$modal.msgError('删除取消');
    }else{
      proxy?.$modal.msgError('删除失败');
    }

  }
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'system/template/export',
    {
      ...queryParams
    },
    `template_${new Date().getTime()}.xlsx`
  );
};

/** 格式化文件大小 */
const formatFileSize = (size: number) => {
  if (!size) return '0 B';

  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(size) / Math.log(k));

  return parseFloat((size / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};

onMounted(() => {
  getList();
});
</script>
