<script setup lang="tsx">
import { NButton, NPopconfirm, NTag } from 'naive-ui';
import { DeleteGoodsType, fetchGetGoodsTypeList } from '@/service/api/planmg';
import { useTable, useTableOperate } from '@/hooks/common/table';
import { useAppStore } from '@/store/modules/app';
import { enablePropertyFLAGRecord } from '@/constants/business';
import { $t } from '@/locales';
import MtlTypeOperateDrawer from './modules/mtltype-operate-drawer.vue';

// 表格数据初始化
const appStore = useAppStore();
const { columns, columnChecks, data, getData, getDataByPage, loading, mobilePagination, searchParams } = useTable({
  apiFn: fetchGetGoodsTypeList,
  showTotal: true,
  apiParams: {
    current: 1,
    size: 10
  },
  columns: () => [
    {
      type: 'selection',
      align: 'center',
      width: 48
    },
    {
      key: 'index',
      title: $t('common.index'),
      width: 64,
      align: 'center'
    },
    {
      key: 'GOODS_TYPE_CODE',
      title: '编码',
      align: 'center'
    },
    {
      key: 'GOODS_TYPE_NAME',
      title: '名称',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'GOODS_TYPE_REMARK',
      title: '备注',
      align: 'center'
    },
    {
      key: 'GOODS_TYPE_FLAG',
      title: '标记',
      align: 'center',
      render: row => {
        if (row.GOODS_TYPE_FLAG === null) {
          return null;
        }

        const tagMap: Record<string, NaiveUI.ThemeColor> = {
          1: 'success',
          0: 'warning'
        };

        const label = $t(enablePropertyFLAGRecord[row.GOODS_TYPE_FLAG]);

        return <NTag type={tagMap[row.GOODS_TYPE_FLAG]}>{label}</NTag>;
      }
    },
    {
      key: 'operate',
      title: $t('common.operate'),
      align: 'center',
      width: 130,
      render: row => (
        <div class="flex-center gap-8px">
          <NButton type="primary" ghost size="small" onClick={() => edit(row.GOODS_TYPE_ID)}>
            {$t('common.edit')}
          </NButton>
          <NPopconfirm onPositiveClick={() => handleDelete(row.GOODS_TYPE_ID)}>
            {{
              default: () => $t('common.confirmDelete'),
              trigger: () => (
                <NButton type="error" ghost size="small">
                  {$t('common.delete')}
                </NButton>
              )
            }}
          </NPopconfirm>
        </div>
      )
    }
  ]
});

const { drawerVisible, operateType, editingData, handleAdd, handleEdit_Goods, checkedRowKeys } = useTableOperate(
  data,
  getData
);

// 批量删除
async function handleBatchDelete() {
  // request
  const deluserlist: number[] = [];
  checkedRowKeys.value.forEach(item => {
    deluserlist.push(Number(item));
  });
  const delinfo = await DeleteGoodsType(deluserlist);

  if (delinfo.response !== undefined) {
    if (delinfo.response.data.code === '0000') {
      window.$message?.success(delinfo.data?.msg as string);
      getData();
    }
  }
}
// 删除单个
async function handleDelete(id: number) {
  const delinfo = await DeleteGoodsType([id]);

  if (delinfo.response !== undefined) {
    if (delinfo.response.data.code === '0000') {
      window.$message?.success(delinfo.data?.msg as string);
      getData();
    }
  }
}
function exportToCSV(datacsv: Array<Record<string, any>>, filename: string) {
  const csvRows: string[] = [];

  // 定义表头映射
  const headerMap: Record<string, string> = {
    GOODS_TYPE_ID: '序号',
    GOODS_TYPE_CODE: '编码',
    GOODS_TYPE_NAME: '物料名称',
    GOODS_TYPE_REMARK: '物料信息',
    GOODS_TYPE_ORDER: '排序',
    GOODS_TYPE_FLAG: '物料状态'
  };

  // 获取表头
  const headers = Object.keys(datacsv[0]);
  const translatedHeaders = headers.slice(0, 6).map(header => headerMap[header] || header); // 只取前五列
  // const translatedHeaders = headers.map(header => headerMap[header] || header);
  csvRows.push(translatedHeaders.join(','));

  // 添加数据行
  for (const row of datacsv) {
    const values = headers.slice(0, 6).map(header => {
      // 强制转换为字符串
      let value = row[header];
      if (typeof value !== 'string') {
        value = String(value); // 将任何非字符串类型转换为字符串
      }
      if (header === 'GOODS_TYPE_FLAG') {
        if (value === '0') {
          value = '禁用';
        } else {
          value = '启用';
        }
      }
      if (header === 'GOODS_TYPE_CODE') {
        value = `="${value}"`; // 加等号，确保 Excel 将其作为文本处理
      }
      // 处理双引号和其他特殊字符
      const escaped = value.replace(/"/g, '""');
      return `"${escaped}"`; // 用双引号包裹
    });
    csvRows.push(values.join(','));
  }
  // 创建 Blob 对象并下载文件
  const csvString = csvRows.join('\n');
  const blob = new Blob([csvString], { type: 'text/csv' });
  const url = URL.createObjectURL(blob);

  const a = document.createElement('a');
  a.setAttribute('href', url);
  a.setAttribute('download', filename);
  a.click();
  URL.revokeObjectURL(url);
}
async function exportCsv() {
  const getcodedata = searchParams;
  getcodedata.size = 0;
  const con = await fetchGetGoodsTypeList(getcodedata);
  exportToCSV(con.data?.data.records as Api.Material.GoodsType[], `物料类型.csv`);
}
// 修改
function edit(id: number) {
  handleEdit_Goods(id);
}
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <NCard title=" " :bordered="false" size="small" class="sm:flex-1-hidden card-wrapper">
      <template #header-extra>
        <TableHeaderOperation
          v-model:columns="columnChecks"
          :disabled-delete="checkedRowKeys.length === 0"
          :loading="loading"
          @add="handleAdd"
          @delete="handleBatchDelete"
          @refresh="getData"
          @export="exportCsv"
        />
      </template>
      <NDataTable
        v-model:checked-row-keys="checkedRowKeys"
        :columns="columns"
        :data="data"
        size="small"
        :flex-height="!appStore.isMobile"
        :loading="loading"
        remote
        :row-key="row => row.GOODS_TYPE_ID"
        :pagination="mobilePagination"
        class="sm:h-full"
      />
      <MtlTypeOperateDrawer
        v-model:visible="drawerVisible"
        :operate-type="operateType"
        :row-data="editingData"
        @submitted="getDataByPage"
      />
    </NCard>
  </div>
</template>

<style scoped></style>
