<template>
  <box-content class="stats-wrapper">
    <div class="search">
      <SearchForm
        size="mini"
        :that="this"
        :search-data="searchData"
        :search-form="trialStats_form"
        :search-handle="trialStats_handle"
        @search="handleSearch"
        @reset="handleReset"
        @export="handleExportExcel"
      >
        <!-- 选择自定义slot -->
        <template slot="croSlot">
          <el-select
            ref="CROSelection"
            v-model="searchData.CROId"
            style="width:120px"
            clearable
          >
            <el-option
              v-for="(item) of croList"
              :key="item.Id"
              :label="item.CROName"
              :value="item.Id"
            />
          </el-select>
        </template>
        <template slot="beginDateSlot">
          <el-date-picker
            v-model="searchData.BeginDate"
            placeholder="Beginning Month"
            type="month"
            value-format="yyyy-MM"
            format="yyyy-MM"
            style="width:120px;"
            :picker-options="beginPickerOption"
            :clearable="false"
          />
        </template>
        <template slot="endDateSlot">
          <el-date-picker
            v-model="searchData.EndDate"
            size="small"
            placeholder="End Month"
            type="month"
            value-format="yyyy-MM"
            format="yyyy-MM"
            style="width:120px;"
            :picker-options="endpickerOption"
            :clearable="false"
          />
        </template>
        <template slot="exportSlot">
          <el-button
            type="primary"
            :disabled="arrID.length==0"
            @click="handleExportExcel"
          >Export Excel</el-button>
        </template>
      </SearchForm>

    </div>
    <el-table
      ref="trialStats"
      v-adaptive="{bottomOffset:45}"
      v-loading="listLoading"
      stripe
      height="100"
      :data="list"
      :summary-method="getSummaries"
      show-summary
      @sort-change="sortByColumn"
      @selection-change="handleSelectChange"
    >
      <el-table-column type="selection" />
      <el-table-column type="index" width="40" />

      <el-table-column
        prop="TrialCode"
        sortable="custom"
        label="Trial ID"
        min-width="100"
        show-overflow-tooltip
      />
      <el-table-column
        prop="Expedited"
        min-width="90"
        label="Expedited"
        show-overflow-tooltip
        sortable="custom"
      >
        <template
          slot-scope="scope"
        >{{ scope.row.Expedited==0?'No':scope.row.Expedited==1?'24H':'48H' }}</template>
      </el-table-column>
      <el-table-column
        prop="Indication"
        label="Indication"
        min-width="100"
        sortable="custom"
        show-overflow-tooltip
      />
      <el-table-column
        prop="Cro"
        label="CRO"
        min-width="80"
        sortable="custom"
        show-overflow-tooltip
      />
      <el-table-column
        prop="CreateTime"
        label="CreateTime"
        min-width="100"
        sortable="custom"
        show-overflow-tooltip
      />

      <el-table-column
        prop="ReviewerNameList"
        label="Reviewer Name"
        min-width="100"
        show-overflow-tooltip
      >
        <template slot-scope="scope">{{ scope.row.ReviewerNameList }}</template>
      </el-table-column>
      <el-table-column
        prop="ReviewerNameCNList"
        label="Reviewer Name CN"
        min-width="110"
        show-overflow-tooltip
      >
        <template slot-scope="scope">{{ scope.row.ReviewerNameCNList }}</template>
      </el-table-column>
      <el-table-column
        prop="EnrollCount"
        label="Entry Count"
        min-width="90"
        sortable="custom"
        show-overflow-tooltip
      />
    </el-table>
    <pagination class="page" :total="total" :page.sync="searchData.PageIndex" :limit.sync="searchData.PageSize" @pagination="getList" />
  </box-content>
</template>
<script>
import { formatUTCTime } from '@/utils/formatter'
import { getEnrollStatByTrial } from '@/api/statistics'
import { exportExcelWithTotal } from '@/utils/export'
import store from '@/store'
import { mapGetters } from 'vuex'
import { trialStats_form, trialStats_handle } from '../statistics'
import Pagination from '@/components/Pagination'

import BoxContent from '@/components/BoxContent'
import SearchForm from '@/components/BaseForm/search-form'
const searchDataDefault = () => {
  return {
    CroId: '',
    TrialCode: '',
    Indication: '',
    BeginDate: new Date(new Date().setMonth(new Date().getMonth() - 5)).format('yyyy-MM'),
    EndDate: new Date().format('yyyy-MM'),
    PageIndex: 1,
    PageSize: 20
  }
}
export default {
  name: 'WorkloadStats',
  components: { Pagination, BoxContent, SearchForm },
  data() {
    return {
      trialStats_form,
      trialStats_handle,
      searchData: searchDataDefault(),
      list: [],
      listLoading: false,
      total: 0,
      arrID: [],
      beginPickerOption: {
        disabledDate: (time) => {
          if (this.searchData.EndDate) {
            return time.getTime() > new Date(this.searchData.EndDate).getTime()
          } else {
            return time.getTime() > Date.now()
          }
        }
      },
      endpickerOption: {
        disabledDate: (time) => {
          if (this.searchData.BeginDate) {
            return (
              time.getTime() > Date.now() ||
              time.getTime() <= new Date(this.searchData.BeginDate).getTime()
            )
          } else {
            return time.getTime() > Date.now()
          }
        }
      }
    }
  },
  computed: {
    ...mapGetters(['croList'])
  },
  mounted() {
    this.getList()
    store.dispatch('global/getCROList')
  },
  methods: {
    // 获取项目入组统计信息
    getList() {
      this.listLoading = true
      getEnrollStatByTrial(this.searchData)
        .then((res) => {
          this.listLoading = false
          this.list = res.Result.CurrentPageData
          this.list.forEach((item) => {
            item.ReviewerNameList = item.ReviewerNameList.join(', ')
            item.ReviewerNameCNList = item.ReviewerNameCNList.join(', ')
            item.CreateTime = formatUTCTime(item.CreateTime)
          })
          this.total = res.Result.TotalCount
        })
        .catch(() => {
          this.listLoading = false
        })
    },
    // 查询
    handleSearch() {
      this.searchData.PageIndex = 1
      this.getList()
    },
    // 重置
    handleReset() {
      this.searchData = searchDataDefault()
      this.getList()
    },
    // 获取勾选行ID
    handleSelectChange(val) {
      const arr = []
      for (let index = 0; index < val.length; index++) {
        arr.push(val[index].Id)
      }
      this.arrID = arr
    },
    // 合计行
    getSummaries(param) {
      this.$nextTick(() => {
        this.$refs.trialStats.doLayout()
      })
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 2) {
          sums[index] = 'Total (Current Page)'
          return
        }
        const values = data.map((item) => Number(item[column.property]))
        if (!values.every((value) => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
        // sums[index] += ' ?';
        } else {
        // sums[index] = 'N/A';
        }
      })
      return sums
    },
    // 排序
    sortByColumn(column) {
      if (column.order === 'ascending') {
        this.searchData.Asc = true
      } else {
        this.searchData.Asc = false
      }
      this.searchData.SortField = column.prop
      this.searchData.PageIndex = 1
      this.getList()
    },
    // 导出Excel
    handleExportExcel() {
      const sheetName = `${this.searchData.BeginDate}~${this.searchData.EndDate}`
      const columns = [
        { key: 'Index', width: 5 },
        { key: 'TrialCode', width: 15 },
        { key: 'Expedited', width: 15 },
        { key: 'Indication', width: 15 },
        { key: 'Cro', width: 15 },
        { key: 'ReviewerNameList', width: 25 },
        { key: 'ReviewerNameCNList', width: 25 },
        { key: 'EnrollCount', width: 15 }
      ]
      const conditional = `Beginning Month:${this.searchData.BeginDate}  End Month:${this.searchData.EndDate}`
      const headerArr = [
        '',
        'Trial ID',
        'Expedited',
        'Indication',
        'CRO',
        'Reviewer Name',
        'Reviewer Name CN',
        'Enroll Count'
      ]
      var total = 0
      let index = 1
      var exportExcelData = this.list.filter(
        (item) => this.arrID.indexOf(item.Id) > -1
      )
      exportExcelData.forEach((element) => {
        element.Index = index++
        element.Expedited =
          element.Expedited === 0
            ? 'No'
            : element.Expedited === 1
              ? '24H'
              : '48H'
        total += element.EnrollCount
      })
      const totalRow = ['', 'Total', '', '', '', '', '', total]
      exportExcelWithTotal(
        sheetName,
        columns,
        'Enrollments Statistics',
        conditional,
        headerArr,
        exportExcelData,
        totalRow,
        []
      )
    }
  }
}
</script>
