<template>
  <avue-crud ref="crud" :page="page" :data="dataList" :option="tableOption" @on-load="getDataList">
    <template slot="menuLeft">
      <el-button type="success" icon="el-icon-download" size="small" @click="exportToCSVFile">导出结果至Excel</el-button>
    </template>
  </avue-crud>
</template>

<script lang="ts">
import Vue from 'vue'
import { IPage } from '@/utils/vo'
import httpx from '@/utils/httpx'
import { tableOption } from "@/avue/crud/liveroomInviteStats"
import datasheet2csv from "@/utils/datasheet2csv"
import { download_blob } from "@/utils/index"
import { datetime_format } from '@/utils/formatters'

const getPages = (count: number) => {
  return {
    total: count,
    currentPage: 1,
    pageSize: count,
    pageSizes: [count],
    layout: '', //隐藏分页
  }
}

export default Vue.extend({
  props: {
    daterange: { type: Array, }, // string[]
    roomId: { type: Number },
    roomInfo: { type: Object }
  },
  data() {
    return {
      dataListLoading: false,
      page: getPages(10),
      dataList: [] as {
        manager_info: string,
        count: number,
      }[],
    }
  },

  methods: {
    getDataList(page?: IPage, query?: never, done?: Function) {
      if (this.roomId <= 0) {
        return
      } else if (this.daterange.length !== 2) {
        this.dataList = []
        return
      }
      const [start, end] = this.daterange

      this.dataListLoading = true
      httpx.post(httpx.makeurl('/rooms/invitesCountList'), {
        startTime: start,
        endTime: end,
        roomId: this.roomId,
      }).then(({ data }) => {
        this.dataList = data.invitesList
        this.dataListLoading = false
        this.page = getPages(data.invitesList.length)
        if (done) {
          done()
        }
      })
    },

    exportToCSVFile() {
      const blob = datasheet2csv(
        this.dataList,
        (v) => [v.manager_info, v.count],
        ['客户经理信息', '有效邀约数量']
      )
      const start = (this.daterange[0] as string).replaceAll(':', "-")
      const end = (this.daterange[1] as string).replaceAll(':', "-")
      download_blob(blob, `客户邀约记录_${this.roomInfo.title}_${start}至${end}.csv`)
    },
  },

  watch: {
    daterange() {
      this.getDataList()
    }
  },

  computed: {
    tableOption() { return tableOption }
  },
})
</script>