<script setup lang="tsx">
import { NButton, NPopconfirm, NTag } from 'naive-ui';
import { DeleteGoodsProperty, fetchGetGoodsPropertyList } 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 MtlAttributeOperateDrawer from './modules/mtlattribute-operate-drawer.vue';

// 表格数据初始化
const appStore = useAppStore();
const {
  columns,
  columnChecks,
  data,
  getData,
  getDataByPage,
  loading,
  mobilePagination,
  searchParams,
  resetSearchParams
} = useTable({
  apiFn: fetchGetGoodsPropertyList,
  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_NAME',
      title: '物料类型',
      align: 'center',
      width: 120
    },
    {
      key: 'GOODS_PROPERTY_CODE',
      title: '库存编码',
      align: 'center',
      width: 180
    },
    {
      key: 'GOODS_PROPERTY_NAME',
      title: '名称',
      align: 'center',
      width: 120
    },
    {
      key: 'GOODS_PROPERTY_REMARK',
      title: '计划编码',
      align: 'center',
      width: 100
    },
    {
      key: 'GOODS_PROPERTY_FIELDTYPE',
      title: '显示类型',
      align: 'center',
      width: 100
    },
    {
      key: 'GOODS_PROPERTY_ORDER',
      title: '排序',
      align: 'center',
      width: 100
    },
    {
      key: 'GOODS_PROPERTY_FLAG',
      title: '同步SG186',
      align: 'center',
      width: 100,
      render: row => {
        if (row.GOODS_PROPERTY_FLAG === null) {
          return null;
        }

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

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

        return <NTag type={tagMap[row.GOODS_PROPERTY_FLAG]}>{label}</NTag>;
      }
    },
    {
      key: 'GOODS_PROPERTY_VALID',
      title: '是否必选',
      align: 'center',
      width: 120
    },
    {
      key: 'GOODS_PROPERTY_DATASOURCE',
      title: '数据源',
      align: 'center',
      width: 200
    },
    {
      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_PROPERTY_ID)}>
            {$t('common.edit')}
          </NButton>
          <NPopconfirm onPositiveClick={() => handleDelete(row.GOODS_PROPERTY_ID)}>
            {{
              default: () => $t('common.confirmDelete'),
              trigger: () => (
                <NButton type="error" ghost size="small">
                  {$t('common.delete')}
                </NButton>
              )
            }}
          </NPopconfirm>
        </div>
      )
    }
  ]
});

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

// 批量删除
async function handleBatchDelete() {
  // request
  const deluserlist: number[] = [];
  checkedRowKeys.value.forEach(item => {
    deluserlist.push(Number(item));
  });
  const delinfo = await DeleteGoodsProperty(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 DeleteGoodsProperty([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_PROPERTY_ID: '序号',
    GOODS_TYPE_NAME: '物料类型',
    GOODS_PROPERTY_CODE: '库存编码',
    GOODS_PROPERTY_NAME: '名称',
    GOODS_PROPERTY_REMARK: '计划编码',
    GOODS_PROPERTY_FIELDTYPE: '显示类型',
    GOODS_PROPERTY_ORDER: '排序',
    GOODS_PROPERTY_FLAG: '同步SG186',
    GOODS_PROPERTY_VALID: '是否必选',
    GOODS_PROPERTY_DATASOURCE: '数据源'
  };

  // 获取表头
  const headers = Object.keys(datacsv[0]);
  // 只保留有映射的列
  const translatedHeaders = headers
    .filter(header => headerMap[header]) // 过滤没有映射的列
    .map(header => headerMap[header]); // 进行映射
  // const translatedHeaders = headers.map(header => headerMap[header] || header);
  csvRows.push(translatedHeaders.join(','));
  console.log(translatedHeaders.join(','));
  // 添加数据行
  for (const row of datacsv) {
    const values = translatedHeaders.map(translatedHeader => {
      // 找到原始列名
      const originalHeader = Object.keys(headerMap).find(key => headerMap[key] === translatedHeader);

      if (!originalHeader) {
        return ''; // 如果找不到原始列名，返回空字符串
      }

      // 获取原始列的数据
      let value = row[originalHeader];

      if (typeof value !== 'string') {
        value = String(value); // 将任何非字符串类型转换为字符串
      }

      // 特殊处理字段
      if (originalHeader === 'GOODS_PROPERTY_FLAG') {
        value = value === '0' ? '禁用' : '启用';
      }
      if (originalHeader === 'GOODS_PROPERTY_VALID') {
        value = value === '0' ? '禁用' : '启用';
      }
      if (originalHeader === 'GOODS_PROPERTY_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 fetchGetGoodsPropertyList(getcodedata);
  console.log(con);
  exportToCSV(con.data?.data.records as Api.Material.GoodsProperty[], `物料属性.csv`);
}
// 修改
function edit(id: number) {
  handleEdit(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
        :scroll-x="1382"
        :row-key="row => row.GOODS_PROPERTY_ID"
        :pagination="mobilePagination"
        class="sm:h-full"
      />
      <MtlAttributeOperateDrawer
        v-model:visible="drawerVisible"
        :operate-type="operateType"
        :row-data="editingData"
        @submitted="getDataByPage"
      />
    </NCard>
  </div>
</template>

<style scoped></style>
