<script setup lang="ts">
import type { DrawerPlacement, UploadFileInfo, UploadInst } from 'naive-ui';
import { ref } from 'vue';
import { useMessage } from 'naive-ui';
import { fetchGetLybList } from '@/service/api/exploitation';
import { useTable, useTableOperate } from '@/hooks/common/table';
import { useAppStore } from '@/store/modules/app';
import LybSearch from './modules/lvyuebiao-search.vue'; // 表格数据初始化

const appStore = useAppStore();
const {
  columns,
  columnChecks,
  data,
  getData,
  getDataByPage,
  loading,
  mobilePagination,
  searchParams,
  resetSearchParams
} = useTable({
  apiFn: fetchGetLybList,
  showTotal: true,
  apiParams: {
    current: 1,
    size: 10,
    OrderLineNumber: null, // 订单+行号，作为主键
    PurchaseOrderNumber: null, // 采购订单号
    PurchaseOrderLineItem: null, // 采购订单行项目号
    PurchaseRequestNumber: null, // 采购申请号（可选）
    StockUnit: null, // 库存单位
    MaterialType: null, // 物资类型
    ProjectName: null, // 项目名称
    MaterialCode: null, // 物料编码
    MaterialName: null, // 物资名称
    OrderQuantity: null, // 订单数量
    MaterialUnit: null, // 物料单位
    SupplierName: null, // 供应商名称
    PlannedDeliveryDate: null, // 采购订单计划交货日期
    ERPSystemFactory: null, // ERP系统工厂
    ProjectCode: null, // 项目编码
    ContractUnitPrice: null, // 签约单价(不含税)
    ContractTotalPrice: null, // 签约总价(不含税)
    ProjectType: null, // 项目类型
    ProcurementMethod: null, // 采购方式
    MajorCategory: null, // 大类
    MiddleCategory: null, // 中类
    SubCategory: null, // 小类
    ExtraField1: null, // 扩展字段1，格式 "yyyy-MM-dd HH:mm:ss"
    ExtraField2: null, // 扩展字段2
    CreateTimeEnd: null, // 扩展字段2
    CreateTimeStart: null // 扩展字段2
  },
  columns: () => [
    {
      type: 'selection',
      align: 'center',
      width: 48
    },
    {
      key: 'index',
      title: '序号',
      width: 40,
      align: 'center'
    },
    {
      key: 'OrderLineNumber',
      title: '订单+行号',
      align: 'center',
      width: 100
    },
    {
      key: 'PurchaseOrderNumber',
      title: '采购订单号',
      align: 'center',
      width: 100
    },
    {
      key: 'PurchaseOrderLineItem',
      title: '采购订单行项目号',
      align: 'center',
      width: 100
    },
    {
      key: 'PurchaseRequestNumber',
      title: '采购申请号',
      align: 'center',
      width: 100
    },
    {
      key: 'StockUnit',
      title: '库存单位',
      align: 'center',
      width: 100
    },
    {
      key: 'MaterialType',
      title: '物资类型',
      align: 'center',
      width: 100
    },
    {
      key: 'ProjectName',
      title: '项目名称',
      align: 'center',
      width: 200
    },
    {
      key: 'MaterialCode',
      title: '物料编码',
      align: 'center',
      width: 100
    },
    {
      key: 'MaterialName',
      title: '物资名称',
      align: 'center',
      width: 200
    },
    {
      key: 'OrderQuantity',
      title: '订单数量',
      align: 'center',
      width: 100
    },
    {
      key: 'MaterialUnit',
      title: '物料单位',
      align: 'center',
      width: 100
    },
    {
      key: 'SupplierName',
      title: '供应商名称',
      align: 'center',
      width: 150
    },
    {
      key: 'PlannedDeliveryDate',
      title: '计划交货日期',
      align: 'center',
      width: 100
    },
    {
      key: 'ERPSystemFactory',
      title: 'ERP系统工厂',
      align: 'center',
      width: 100
    },
    {
      key: 'ProjectCode',
      title: '项目编码',
      align: 'center',
      width: 100
    },
    {
      key: 'ContractUnitPrice',
      title: '签约单价(不含税)',
      align: 'center',
      width: 100
    },
    {
      key: 'ContractTotalPrice',
      title: '签约总价(不含税)',
      align: 'center',
      width: 100
    },
    {
      key: 'ProjectType',
      title: '项目类型',
      align: 'center',
      width: 100
    },
    {
      key: 'ProcurementMethod',
      title: '采购方式',
      align: 'center',
      width: 100
    },
    {
      key: 'MajorCategory',
      title: '大类',
      align: 'center',
      width: 100
    },
    {
      key: 'MiddleCategory',
      title: '中类',
      align: 'center',
      width: 100
    },
    {
      key: 'SubCategory',
      title: '小类',
      align: 'center',
      width: 100
    },
    {
      key: 'ExtraField1',
      title: '导入时间',
      align: 'center',
      width: 150
    }
  ]
});
const active = ref(false);
const placement = ref<DrawerPlacement>('right');
function handleAdd() {
  active.value = true;
}
const fileListLength = ref(0);
const uploadRef = ref<UploadInst | null>(null);

const handleChange = (options: { fileList: UploadFileInfo[] }) => {
  fileListLength.value = options.fileList.length;
};

const upload = uploadRef;
const message = useMessage();

const handleClick = () => {
  uploadRef.value?.submit();
  if (uploadRef.value === null) {
    message.warning('未选择上传的履约表文件');
  }
};
const handleFinish = ({ event }: { file: UploadFileInfo; event?: ProgressEvent }) => {
  message.success((event?.target as XMLHttpRequest).response);
  active.value = false;
};
const handleerror = ({ event }: { file: UploadFileInfo; event?: ProgressEvent }) => {
  message.warning((event?.target as XMLHttpRequest).response, { duration: 5000 });
};
const { checkedRowKeys } = useTableOperate(data, getData);
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <LybSearch v-model:model="searchParams" @reset="resetSearchParams" @search="getDataByPage" />
    <NCard title="履约表信息" :bordered="false" size="small" class="sm:flex-1-hidden card-wrapper">
      <template #header-extra>
        <TableHeaderOperationE
          v-model:columns="columnChecks"
          :disabled-delete="checkedRowKeys.length === 0"
          :loading="loading"
          @add="handleAdd"
          @refresh="getData"
        />
      </template>
      <NDataTable
        v-model:checked-row-keys="checkedRowKeys"
        :columns="columns"
        :data="data"
        size="small"
        :flex-height="!appStore.isMobile"
        :scroll-x="3500"
        :loading="loading"
        remote
        :row-key="row => row.OrderLineNumber"
        :pagination="mobilePagination"
        class="sm:h-full"
      />
    </NCard>
    <NDrawer v-model:show="active" :width="502" :placement="placement">
      <NDrawerContent title="导入履约表">
        <NFlex justify="center">
          <NUpload
            ref="upload"
            multiple
            directory-dnd
            action="http://localhost:58926/api/FileUpload/Upload"
            :default-upload="false"
            :max="1"
            @change="handleChange"
            @finish="handleFinish"
            @error="handleerror"
          >
            <NUploadDragger>
              <!-- <SvgIcon icon="solar:upload-square-broken" /> -->
              <div class="divheight"></div>
              <NText>点击或者拖动文件到该区域来上传</NText>
              <div class="divheight"></div>
            </NUploadDragger>
          </NUpload>
          <NPopconfirm :show-icon="false" @positive-click="handleClick">
            <template #trigger>
              <NButton>导入履约表</NButton>
            </template>
            确定导入当前履约表吗？
          </NPopconfirm>
        </NFlex>
        <div class="center-link">
          <a
            class="download-link"
            href="http://localhost:58926/res/%E8%87%AA%E5%AE%9A%E4%B9%89%E7%89%A9%E8%B5%84%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xlsx"
            download="履约表模板.xlsx"
          >
            下载履约表模板
          </a>
        </div>
      </NDrawerContent>
    </NDrawer>
  </div>
</template>

<style scoped>
.divheight {
  height: 100px;
}
.center-link {
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中（可选） */
  margin-top: 2vh;
  color: #888;
}
</style>
