<template>
  <div class="modern-page-container">
    <div class="page-wrapper">
      <!-- 内容卡片 -->
      <el-card class="content-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span class="card-title">
              <el-icon class="title-icon"><Document /></el-icon>
              采购品目管理
            </span>
            <div class="header-actions">
              <el-button 
                icon="FolderAdd" 
                type="primary"
                v-auth="'purchase_purchasingcategory_add'"
                @click="formDialogRef.openDialog('add')">
                新增
              </el-button>
              <el-button 
                icon="Download" 
                type="success"
                v-auth="'purchase_purchasingcategory_import'"
                @click="handleDownloadTemplate">
                下载模板
              </el-button>
              <el-upload
                ref="uploadRef"
                :show-file-list="false"
                :before-upload="handleBeforeUpload"
                :http-request="handleImport"
                accept=".xlsx,.xls"
                v-auth="'purchase_purchasingcategory_import'">
                <el-button icon="Upload" type="warning" :loading="importLoading">
                  导入
                </el-button>
              </el-upload>
              <el-button
                icon="Download" 
                type="info"
                v-auth="'purchase_purchasingcategory_export'"
                @click="handleExport">
                导出
              </el-button>
              <right-toolbar class="ml10" />
            </div>
          </div>
        </template>

        <!-- 树形表格（懒加载：仅首屏加载根节点，展开时再加载子节点） -->
        <el-table 
          ref="tableRef"
          :data="state.dataList" 
          v-loading="state.loading" 
          stripe
          lazy
          :load="loadTreeNode"
          :cell-style="tableStyle.cellStyle" 
          :header-cell-style="tableStyle.headerCellStyle"
          class="modern-table"
          row-key="code"
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
          <el-table-column type="index" label="序号" width="70" align="center">
            <template #header>
              <el-icon><List /></el-icon>
            </template>
            <template #default="{ $index, row }">
              {{ getRowIndex($index, row) }}
            </template>
          </el-table-column>
          <el-table-column prop="code" label="品目编码" min-width="150" show-overflow-tooltip>
            <template #header>
              <el-icon><DocumentCopy /></el-icon>
              <span style="margin-left: 4px">品目编码</span>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="品目名称" min-width="200" show-overflow-tooltip>
            <template #header>
              <el-icon><Document /></el-icon>
              <span style="margin-left: 4px">品目名称</span>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" min-width="200" show-overflow-tooltip>
            <template #header>
              <el-icon><EditPen /></el-icon>
              <span style="margin-left: 4px">备注</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" fixed="right" width="150">
            <template #default="scope">
              <el-button 
                icon="Edit" 
                link 
                type="primary"
                v-auth="'purchase_purchasingcategory_edit'"
                @click="formDialogRef.openDialog('edit', scope.row)">
                编辑
              </el-button>
              <el-button 
                icon="Delete" 
                link 
                type="danger"
                v-auth="'purchase_purchasingcategory_del'"
                @click="handleDelete(scope.row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>

    <!-- 编辑、新增表单对话框 -->
    <FormDialog ref="formDialogRef" @refresh="getDataList" />
  </div>
</template>

<script setup lang="ts" name="PurchasingCategory">
import { ref, reactive, defineAsyncComponent } from 'vue'
import { BasicTableProps, useTable } from "/@/hooks/table";
import { getTreeRoots, getTreeChildren, delObj, downloadTemplate, importData, exportData } from "/@/api/purchase/purchasingcategory";
import { useMessage, useMessageBox } from "/@/hooks/message";
import { List, Document, DocumentCopy, EditPen } from '@element-plus/icons-vue'

const FormDialog = defineAsyncComponent(() => import('./form.vue'));

const tableRef = ref()
const formDialogRef = ref()
const uploadRef = ref()
const importLoading = ref(false)

const queryTreeRoots = () => {
  return getTreeRoots().then((res: any) => {
    const list = res?.data ?? [];
    return { data: Array.isArray(list) ? list : [] };
  });
};

const loadTreeNode = (row: any, treeNode: any, resolve: (data: any[]) => void) => {
  const parentCode = row?.code;
  if (!parentCode) {
    resolve([]);
    return;
  }
  getTreeChildren(parentCode)
    .then((res: any) => {
      const list = res?.data ?? [];
      resolve(Array.isArray(list) ? list : []);
    })
    .catch(() => resolve([]));
};

const state: BasicTableProps = reactive<BasicTableProps>({
  pageList: queryTreeRoots,
  queryForm: {},
  isPage: false,
});

const { getDataList, tableStyle } = useTable(state);

const getRowIndex = (index: number, row: any) => {
  return index + 1;
};

const handleDelete = async (row: any) => {
  try {
    await useMessageBox().confirm('确定要删除该记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
  } catch {
    return;
  }

  try {
    const deleteId = row.id || row.code;
    await delObj(deleteId);
    useMessage().success('删除成功');
    getDataList();
  } catch (err: any) {
    useMessage().error(err.msg || '删除失败');
  }
};

const handleDownloadTemplate = async () => {
  try {
    const res: any = await downloadTemplate();
    downloadFile(res, '采购品目导入模板.xlsx');
  } catch (err: any) {
    useMessage().error(err.msg || '下载模板失败');
  }
};

const handleBeforeUpload = (file: File) => {
  const isExcel = file.name.endsWith('.xlsx') || file.name.endsWith('.xls');
  if (!isExcel) {
    useMessage().error('请上传Excel文件');
    return false;
  }
  return true;
};

const handleImport = async (options: any) => {
  importLoading.value = true;
  try {
    const res: any = await importData(options.file);
    useMessage().success(res.msg || '导入成功');
    getDataList();
  } catch (err: any) {
    useMessage().error(err.msg || '导入失败');
  } finally {
    importLoading.value = false;
  }
};

const handleExport = async () => {
  try {
    const res: any = await exportData();
    downloadFile(res, '采购品目数据.xlsx');
  } catch (err: any) {
    useMessage().error(err.msg || '导出失败');
  }
};

const downloadFile = (blob: Blob, fileName: string) => {
  const url = window.URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.href = url;
  link.download = fileName;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  window.URL.revokeObjectURL(url);
};
</script>

<style scoped lang="scss">
@import '/@/assets/styles/modern-page.scss';
</style>

