<template>
  <BasicTable @register="registerTimeTable">
    <template #toolbar>
      <a-button type="primary" @click="handleExport">{{ t('routes.equity.exportExcel') }}</a-button>
    </template>
    <template #action="{ record }">
      <TableAction
        :actions="[
          {
            label: t('routes.account.detail'),
            onClick: handleEdit.bind(null, record),
          },
        ]"
      />
    </template>
  </BasicTable>
</template>
<script lang="ts">
  import { defineComponent, computed } from 'vue';
  import { BasicTable, useTable, FormProps, TableAction } from '/@/components/Table';
  import { Steps } from 'ant-design-vue';
  import { ListApi } from '/@/api/account';
  import { userListSchema } from './data';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useRouter } from 'vue-router';
  import { otherInfoStore } from '/@/store/modules/other';
  import { usePermissionStore } from '/@/store/modules/permission';
  import { useUserStore } from '/@/store/modules/user';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { formatToDateTime } from '/@/utils/dateUtil';
  import * as XLSX from 'xlsx-js-style';
  export default defineComponent({
    components: {
      BasicTable,
      TableAction,
      [Steps.Step.name]: Steps.Step,
    },
    setup() {
      const { t } = useI18n();
      const { setOverviewInfo } = otherInfoStore();
      const router = useRouter();
      const userStore = useUserStore();
      const isDev = computed(() => userStore.getSystemEnv);
      const permissionStore = usePermissionStore();
      const { getCheckPerm } = permissionStore;
      const { createMessage } = useMessage();

      function buildSearchParams(params: Recordable = {}) {
        const searchParams = { ...params };
        const timeList = searchParams.timeList || [];
        delete searchParams.timeList;
        return {
          ...searchParams,
          userCreateTimeStart: timeList[0],
          userCreateTimeEnd: timeList[1],
        };
      }

      const searchForm: Partial<FormProps> = {
        labelWidth: 100,
        schemas: [
          {
            field: 'userName',
            label: t('routes.equity.count'),
            component: 'Input',
            componentProps: {
              maxLength: 100,
              style: {
                width: '150px',
              },
            },
            colProps: {
              xl: 4,
              xxl: 4,
            },
          },
          {
            field: 'email',
            label: t('routes.account.email'),
            component: 'Input',
            ifShow: !isDev.value,
            componentProps: {
              maxLength: 100,
              style: {
                width: '200px',
              },
            },
            colProps: {
              xl: 6,
              xxl: 6,
            },
          },
          {
            field: 'timeList',
            label: t('routes.equity.userCreateTime'),
            component: 'RangePicker',
            componentProps: {
              valueFormat: 'YYYY-MM-DD',
              format: 'YYYY-MM-DD',
            },
            colProps: {
              xl: 10,
              xxl: 10,
            },
          },
        ],
      };
      const [registerTimeTable, { reload, getDataSource }] = useTable({
        api: ListApi,
        title: t('routes.account.name'),
        columns: userListSchema,
        useSearchForm: true,
        formConfig: searchForm,
        showTableSetting: true,
        showIndexColumn: false,
        rowKey: 'id',
        beforeFetch: buildSearchParams,
        fetchSetting: {
          pageField: 'pageNum',
          sizeField: 'pageSize',
          listField: 'list',
          totalField: 'total',
        },
        actionColumn: {
          width: 100,
          title: t('common.operating'),
          dataIndex: 'action',
          slots: { customRender: 'action' },
        },
        canResize: true,
      });
      function tabChange(val: string) {
        console.log('tabChange', val);
        reload();
      }
      function handleOpen(record: Recordable) {
        console.log('点击了启用', record);
      }
      function handleEdit(record: Recordable) {
        console.log('record', record);
        setOverviewInfo(record);
        router.push({ path: 'details' });
      }

      async function handleExport() {
        try {
          const exportList = getDataSource<Recordable>() || [];

          const headerList = [
            t('routes.account.id'),
            t('routes.equity.nickName'),
            t('routes.equity.userName1'),
            t('routes.equity.userCreateTime'),
            t('routes.account.vip'),
          ];

          const data = exportList.map((item) => [
            item.id ?? '-',
            item.nickName || '-',
            item.userName || '-',
            item.createTime ? formatToDateTime(item.createTime) : '-',
            item.vip == 0 ? t('common.no') : t('common.yes'),
          ]);

          const worksheet = XLSX.utils.aoa_to_sheet([headerList, ...data]);
          worksheet['!cols'] = [{ wch: 12 }, { wch: 18 }, { wch: 22 }, { wch: 24 }, { wch: 18 }];

          const headerStyle = {
            font: {
              name: '宋体',
              sz: 14,
              bold: true,
            },
            fill: {
              patternType: 'solid',
              fgColor: { rgb: 'C0C0C0' },
            },
            alignment: {
              horizontal: 'center',
              vertical: 'center',
              wrapText: true,
            },
            border: {
              top: { style: 'thin', color: { rgb: '000000' } },
              bottom: { style: 'thin', color: { rgb: '000000' } },
              left: { style: 'thin', color: { rgb: '000000' } },
              right: { style: 'thin', color: { rgb: '000000' } },
            },
          };
          const dataCellStyle = {
            alignment: {
              horizontal: 'center',
              vertical: 'center',
            },
          };

          headerList.forEach((_, index) => {
            const cellAddress = XLSX.utils.encode_cell({ r: 0, c: index });
            if (worksheet[cellAddress]) {
              worksheet[cellAddress].s = headerStyle as any;
            }
          });
          data.forEach((row, rowIndex) => {
            row.forEach((_, colIndex) => {
              const cellAddress = XLSX.utils.encode_cell({ r: rowIndex + 1, c: colIndex });
              if (worksheet[cellAddress]) {
                worksheet[cellAddress].s = dataCellStyle as any;
              }
            });
          });

          const sheetName = t('routes.account.name');
          const workbook = {
            SheetNames: [sheetName],
            Sheets: {
              [sheetName]: worksheet,
            },
          };
          XLSX.writeFile(workbook, `${Date.now()}${t('routes.dashboard.account')}.xlsx`);
          createMessage.success(t('common.optSuccess'));
        } catch (error) {
          console.log('export user list failed', error);
        }
      }
      return {
        registerTimeTable,
        handleOpen,
        tabChange,
        reload,
        handleEdit,
        handleExport,
        getCheckPerm,
        t,
      };
    },
  });
</script>
<style lang="less" scoped>
  .desc-wrap-BasicTable {
    background-color: #f0f2f5;
    .vben-basic-table-form-container {
      padding: 0;
    }
  }
</style>
