<template>
  <div class="container">
    <a-card class="general-card" title="">
      <a-row>
        <a-col :flex="1">
          <a-form
            :model="formModel"
            :label-col-props="{ span: 4 }"
            :wrapper-col-props="{ span: 18 }"
            label-align="left"
          >
            <a-row :gutter="16">
              <a-col :span="8">
                <a-form-item
                  :label="$t('searchTable.form.month')"
                  label-col-flex="60px"
                >
                  <a-month-picker v-model="formModel.time" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-button type="primary" @click="downloadExcel">
                  <template #icon>
                    <icon-download />
                  </template>
                  {{ $t('searchTable.form.down') }}
                </a-button>
              </a-col>
            </a-row>
          </a-form>
        </a-col>
      </a-row>
      <a-table
        row-key="name"
        :loading="loading"
        :pagination="pagination"
        :columns="(cloneColumns as TableColumnData[])"
        :data="renderData"
        :bordered="false"
        :size="size"
        @page-change="onPageChange"
      >
        <template #index="{ rowIndex }">
          {{ rowIndex + 1 + (pagination.current - 1) * pagination.pageSize }}
        </template>
        <template #picture="{ record }">
          <div :key="record.id">
            <a-image width="40" :src="record.picture" />
          </div>
        </template>
      </a-table>
    </a-card>
  </div>
</template>

<script lang="ts" name="RecordListPage" setup>
import { computed, ref, reactive, watch, nextTick } from 'vue';
import type { TableColumnData } from '@arco-design/web-vue/es/table/interface';
import { useI18n } from 'vue-i18n';
import useLoading from '@/hooks/loading';
import { Pagination } from '@/types/global';
import { queryRecordList, getCheckInList } from '@/api/record';
import type { RecordParams, DataList } from '@/api/record';
import { useIntervalFn } from '@vueuse/core';
import dayjs from 'dayjs';

interface FaceParams {
  pageIndex: number;
  personNumber: number;
  time: string;
}
type SizeProps = 'mini' | 'small' | 'medium' | 'large';
type Column = TableColumnData & { checked?: true };

const { loading, setLoading } = useLoading(true);
const { t } = useI18n();
const renderData = ref<DataList[]>([]);
const generateFormModel = () => {
  return {
    pageIndex: 1,
    personNumber: 20,
    time: dayjs().format('YYYY-MM'),
  } as FaceParams;
};
const formModel = ref<FaceParams>(generateFormModel());

const cloneColumns = ref<Column[]>([
  {
    title: t('recordList.columns.index'),
    dataIndex: 'index',
    slotName: 'index',
    ellipsis: true,
    tooltip: true,
    width: 60,
  },
  {
    title: t('recordList.columns.time'),
    dataIndex: 'time',
    ellipsis: true,
    tooltip: true,
    width: 180,
  },
  {
    title: t('recordList.columns.picture'),
    dataIndex: 'picture',
    slotName: 'picture',
    width: 100,
  },
  {
    title: t('recordList.columns.name'),
    dataIndex: 'name',
    ellipsis: true,
    tooltip: true,
  },
  {
    title: t('recordList.columns.nameCh'),
    dataIndex: 'nameCh',
  },
  {
    title: t('recordList.columns.company'),
    dataIndex: 'company',
    ellipsis: true,
  },
  {
    title: t('recordList.columns.Position'),
    dataIndex: 'Position',
    ellipsis: true,
    tooltip: { position: 'left' },
  },
  {
    title: t('recordList.columns.id'),
    dataIndex: 'id',
    ellipsis: true,
  },
  {
    title: t('recordList.columns.result'),
    dataIndex: 'result',
    ellipsis: true,
  },
]);
const size = ref<SizeProps>('medium');

const basePagination: Pagination = {
  current: 1,
  pageSize: 20,
};
const pagination = reactive({
  ...basePagination,
});
const fetchData = async () => {
  setLoading(true);
  try {
    queryRecordList(formModel.value).then(res => {
      renderData.value = res.data;
      pagination.current = formModel.value.pageIndex;
      pagination.pageSize = pagination.pageSize;
      pagination.total = res.total;
    });
  } catch (err) {
    // you can report use errorHandler or other
  } finally {
    setLoading(false);
  }
};
fetchData();
const { pause, resume, isActive } = useIntervalFn(() => {
  /* your function */
  formModel.value.pageIndex = 1;
  fetchData();
}, 1000);
const onPageChange = (current: number) => {
  formModel.value.pageIndex = current;
  fetchData();
};
const downloadExcel = () => {
  setLoading(true);
  const params = {
    time: formModel.value.time,
  };
  getCheckInList(params)
    .then(res => {
      const contentDisposition = res.headers['content-disposition'];
      const filenameMatch = contentDisposition.match(/filename="?(.+)"?/);
      const filename = filenameMatch
        ? filenameMatch[1].replace(/"+$/, '')
        : 'default.xlsx';
      const blob = new Blob([res.data], {
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      });
      const downloadUrl = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = downloadUrl;
      link.setAttribute('download', filename);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(downloadUrl);
    })
    .finally(() => {
      setLoading(false);
    });
};
</script>

<style scoped lang="less">
.container {
  padding: 10px;

  :deep(.arco-list-content) {
    overflow-x: hidden;
  }

  :deep(.arco-card-meta-title) {
    font-size: 14px;
  }

  .general-card {
    padding-top: 10px;
  }
}
</style>
