<script setup lang="tsx">
import { onMounted, ref } from 'vue';
import type { DataTableInst } from 'naive-ui';
import { NButton, NPopconfirm, NTag } from 'naive-ui';
import { DeleteRole, fetchGetCodeALLList, fetchGetCodeList, fetchGetCodeList2 } from '@/service/api';
import { useTable, useTableOperate } from '@/hooks/common/table';
import { useAppStore } from '@/store/modules/app';
import { $t } from '@/locales';
import { enableStatusRecord } from '@/constants/business';
import CodeSearch from './modules/code-search.vue';
import CodeTypeSearch from './modules/codetype-search.vue';
import CodeOperateDrawer from './modules/code-operate-drawer.vue';

const selectOptions = ref([{ label: '临时方案货位分配起始点', value: '70' }]);
const Selectlabel = ref(' ');
// 默认选中值
const codeType = ref({ selectOption: selectOptions.value[0].value });

const fetchData = async () => {
  selectOptions.value = [];
  const response = await fetchGetCodeALLList();
  selectOptions.value = response.data?.data as Api.SystemManage.CodesOption[];
  codeType.value.selectOption = selectOptions.value[0].value;
  Selectlabel.value = selectOptions.value[0].label;
};

onMounted(() => {
  fetchData();
});

// 表格数据初始化
const appStore = useAppStore();
const {
  columns,
  columnChecks,
  data,
  getData,
  getDataByPage,
  loading,
  mobilePagination,
  searchParams,
  resetSearchParams
} = useTable({
  apiFn: fetchGetCodeList,
  showTotal: true,
  apiParams: {
    current: 1,
    size: 10,
    ITEM_ID: codeType.value.selectOption,
    // 如果要在 Form 中使用 searchParams，则需要定义以下属性，值为 null
    // 值不能是 undefined，否则 Form 中的属性将不是响应式的
    status: null,
    ITEM_LIST_NAME: null,
    ITEM_LIST_CODE: null,
    ITEM_LIST_REMARK: null
  },
  columns: () => [
    {
      type: 'selection',
      align: 'center',
      width: 48
    },
    {
      key: 'index',
      title: $t('common.index'),
      width: 64,
      align: 'center'
    },
    {
      key: 'ITEM_LIST_CODE',
      title: '编码',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'ITEM_LIST_NAME',
      title: '编码名称',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'ITEM_LIST_REMARK',
      title: '编码描述',
      minWidth: 120
    },
    {
      key: 'status',
      title: '编码状态',
      align: 'center',
      width: 100,
      render: row => {
        if (row.status === null) {
          return null;
        }

        const tagMap: Record<Api.Common.EnableStatus, NaiveUI.ThemeColor> = {
          1: 'success',
          2: 'warning'
        };

        const label = $t(enableStatusRecord[row.status]);

        return <NTag type={tagMap[row.status]}>{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.id)}>
            {$t('common.edit')}
          </NButton>
          <NPopconfirm onPositiveClick={() => handleDelete(row.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
  // onBatchDeleted,
  // onDeleted
  // closeDrawer
} = useTableOperate(data, getData);

// 批量删除
async function handleBatchDelete() {
  // request
  const deluserlist: number[] = [];
  checkedRowKeys.value.forEach(item => {
    deluserlist.push(Number(item));
  });
  const delinfo = await DeleteRole(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 DeleteRole([id]);

  if (delinfo.response !== undefined) {
    if (delinfo.response.data.code === '0000') {
      window.$message?.success(delinfo.data?.msg as string);
      getData();
    }
  }
}

const tableRef = ref<DataTableInst>();

function exportToCSV(datacsv: Array<Record<string, any>>, filename: string) {
  const csvRows: string[] = [];

  // 定义表头映射
  const headerMap: Record<string, string> = {
    id: '序号',
    ITEM_LIST_CODE: '编码',
    ITEM_LIST_NAME: '编码名称',
    ITEM_LIST_REMARK: '编码信息',
    status: '编码状态'
  };

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

  // 添加数据行
  for (const row of datacsv) {
    const values = headers.slice(0, 5).map(header => {
      // 只取前五列
      const escaped = `${row[header]}`.replace(/"/g, '""'); // 处理双引号
      return `"${escaped}"`; // 用双引号包裹
    });
    csvRows.push(values.join(','));
  }

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

  // // 添加数据行
  // for (const row of datacsv) {
  //   const values = headers.map(header => {
  //     const escaped = `${row[header]}`.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 fetchGetCodeList2(getcodedata);
  exportToCSV(con.data?.data.records as Api.SystemManage.Codes[], `${Selectlabel.value}.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">
    <CodeTypeSearch
      v-model:model="searchParams"
      :options="selectOptions"
      @search="getDataByPage"
      @update-label="Selectlabel = $event"
    />
    <CodeSearch v-model:model="searchParams" @reset="resetSearchParams" @search="getDataByPage" />
    <NCard :title="Selectlabel" :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
        ref="tableRef"
        v-model:checked-row-keys="checkedRowKeys"
        :columns="columns"
        :data="data"
        size="small"
        :flex-height="!appStore.isMobile"
        :scroll-x="702"
        :loading="loading"
        remote
        :row-key="row => row.id"
        :pagination="mobilePagination"
        class="sm:h-full"
      />
      <CodeOperateDrawer
        v-model:visible="drawerVisible"
        :operate-type="operateType"
        :row-data="editingData"
        @submitted="getDataByPage"
      />
    </NCard>
  </div>
</template>

<style scoped></style>
