<template>
  <div class="p-4">
    <!-- <GrowCard :loading="loading" class="enter-y" /> -->
    <BasicTable @register="registerTable" :loading="loading">
      <template #toolbar>
        <a-button type="primary" @click="handleExport">导出数据</a-button>
      </template>
      <template #Time="{ record }">
        <Time :value="record.createTime" mode="datetime" />
      </template>
    </BasicTable>
    <!-- <div class="md:flex enter-y">
      <div class="md:w-1/2 enter-y">
        <Card class="w-full">
          <VisitAnalysisBar :loading="loading" />
        </Card>
      </div>
      <div class="!md:mx-2"></div>
      <Card class="md:w-1/2 enter-y">

        <VisitAnalysis :loading="loading" />
      </Card>
    </div>
    <div class="md:flex enter-y mt-4">
      <Card class="md:w-1/2 md:w-full"> </Card>
    </div> -->
  </div>
</template>
<script lang="ts" setup>
  import { ref } from 'vue';
  import { BasicTable, useTable, BasicColumn, FormProps } from '/@/components/Table';
  // import { useI18n } from '/@/hooks/web/useI18n';
  // import GrowCard from './components/GrowCard.vue';
  import {
    liveRoomStaticsApi,
    // bulletChatStaticsApi,
    companyChatExportApi,
  } from '/@/api/dashboard/analysis';
  import { Time } from '/@/components/Time';

  import { ListApi as ListCorporationApi } from '/@/api/corporation/list';
  import { listRoomsApi } from '/@/api/scene/list';
  import { ListApi as ListLiveApi } from '/@/api/scene/live';

  import { dateUtil, formatToDate } from '/@/utils/dateUtil';

  const loading = ref(true);
  // const { t } = useI18n();
  const today = formatToDate(dateUtil(new Date()));
  const priorDate = formatToDate(dateUtil(new Date().setDate(new Date().getDate() - 30)));

  const columns: BasicColumn[] = [
    {
      title: '企业名称',
      dataIndex: 'companyName',
      width: 120,
    },
    {
      title: '房间名称',
      dataIndex: 'liveRoomName',
      width: 120,
    },
    {
      title: '直播场景名称',
      dataIndex: 'brandName',
      width: 120,
    },
    {
      title: '主持人',
      dataIndex: 'anchorName',
      width: 120,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      slots: { customRender: 'Time' },
      width: 150,
    },
    {
      title: '总观看人数',
      dataIndex: 'spectatorNum',
      // sorter: true,
      width: 120,
    },
    {
      title: '总直播时长(min)',
      dataIndex: 'duration',
      // sorter: true,
      width: 120,
    },
    {
      title: '总分享数',
      dataIndex: 'shareNum',
      // sorter: true,
      width: 120,
    },
  ];
  const searchForm: Partial<FormProps> = {
    labelWidth: 100,
    schemas: [
      {
        field: 'companyId',
        label: '请选择企业',
        component: 'ApiSelect',
        required: false,
        componentProps: {
          api: ListCorporationApi,
          resultField: 'list',
          labelField: 'name',
          valueField: 'id',
          immediate: false,
          showSearch: true,
          optionFilterProp: 'label',
          // onChange: function (_, opt) {
          //   // Reflect.set(modalRecord, 'shippingName', opt.label);
          // },
          params: {
            page: 1,
            limit: 1000,
          },
        },
        colProps: {
          lg: 24,
          md: 24,
          xl: 12,
          xxl: 12,
          // xl: 5,
          // xxl: 12,
        },
      },
      {
        field: 'liveRoomId',
        label: '请选择房间',
        component: 'ApiSelect',
        colProps: {
          lg: 24,
          md: 24,
          xl: 12,
          xxl: 12,
        },
        componentProps: {
          api: listRoomsApi,
          resultField: 'list',
          labelField: 'name',
          valueField: 'id',
          immediate: false,
          showSearch: true,
          optionFilterProp: 'label',
          // onChange: function (_, opt) {
          //   // Reflect.set(modalRecord, 'shippingName', opt.label);
          // },
          params: {
            page: 1,
            limit: 1000,
            state: 103,
          },
        },
      },
      {
        field: 'brandId',
        label: '请选择直播场景',
        labelWidth: 130,
        component: 'ApiSelect',
        colProps: {
          lg: 24,
          md: 24,
          xl: 12,
          xxl: 12,
        },
        componentProps: {
          api: ListLiveApi,
          resultField: 'list',
          labelField: 'name',
          valueField: 'id',
          immediate: false,
          showSearch: true,
          optionFilterProp: 'label',
          params: {
            page: 1,
            limit: 1000,
          },
        },
      },
      {
        field: 'time',
        label: '时间段',
        defaultValue: [priorDate, today],
        component: 'RangePicker',
        colProps: {
          lg: 24,
          md: 24,
          xl: 12,
          xxl: 12,
        },
        componentProps: {
          format: 'YYYY-MM-DD',
          // placeholder: ['开始时间', '结束时间'],
          // showTime: { format: 'HH:mm:ss' },
          disabledDate(current) {
            // console.log('current', current, date);
            return current && current > dateUtil().endOf('day');
          },
        },
        rules: [
          {
            required: true,
            // @ts-ignore
            validator: async (rule, value) => {
              if (!value) {
                return Promise.reject('请选择时间段');
              }
              const days = Math.abs(value[1].diff(value[0], 'days'));
              console.log('days', days);
              if (days > 30) {
                return Promise.reject('选择时间段应小于30天');
              }
              if (days < 1) {
                return Promise.reject('至少选择2天以上');
              }
              return Promise.resolve();
            },

            trigger: 'change',
          },
        ],
      },
    ],
    resetFunc: handleReset,
  };

  const searchInfo = ref({
    liveRoomId: '',
    companyId: '',
    brandId: '',
    limit: 20,
    page: 1,
    time: [priorDate, today],
  });

  const [registerTable] = useTable({
    title: '',
    columns: columns,
    useSearchForm: true,
    formConfig: searchForm,
    api: liveRoomStaticsApi,
    beforeFetch: (data) => {
      console.log('beforeFetch', data);
      data.time = data.time.map((item) => formatToDate(item));
      searchInfo.value = data;
      return data;
    },
    afterFetch: function (data) {
      console.log('data', data);
      return data;
    },
    searchInfo: searchInfo,
    handleSearchInfoFn(data) {
      searchInfo.value = Object.assign(searchInfo.value, data);
      console.log(searchInfo.value);
    },
  });

  async function handleExport() {
    const data = await companyChatExportApi(searchInfo.value);
    const downloadBlob = new Blob([data], {
      type: 'application/msexcel',
    });
    const url = URL.createObjectURL(downloadBlob);
    const a: HTMLAnchorElement = document.createElement('a');
    document.body.appendChild(a);
    a.style.display = 'none';
    a.href = url;
    const name = new Date().getTime();
    a.download = `${name}.csv`;
    a.click();
    window.URL.revokeObjectURL(url);
  }
  async function handleReset() {
    searchInfo.value = {
      liveRoomId: '',
      companyId: '',
      brandId: '',
      limit: 20,
      page: 1,
      time: [priorDate, today],
    };
  }
</script>
