<template>
  <box-content class="stats-wrapper">
    <div class="search">
      <SearchForm
        size="mini"
        :that="this"
        :search-data="searchData"
        :search-form="enrollStats_form"
        :search-handle="enrollStats_handle"
        @search="handleSearch"
        @reset="handleReset"
        @export="handleExportExcel"
      >
        <!-- 选择自定义slot -->
        <template slot="hospitalSlot">
          <el-select
            v-model="searchData.HospitalId"
            placeholder="Hospital"
            style="width:130px"
            clearable
          >
            <el-option
              v-for="(item,index) in hospitalList"
              :key="index"
              :label="item.HospitalName"
              :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="enrollmentStats"
      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="Hospital"
        sortable="custom"
        label="Hospital"
        min-width="120"
        show-overflow-tooltip
      />
      <el-table-column
        label="Name"
        show-overflow-tooltip
        min-width="100"
        prop="FirstName"
        sortable="custom"
      >
        <template slot-scope="scope">{{ scope.row.LastName }} / {{ scope.row.FirstName }}</template>
      </el-table-column>
      <el-table-column
        prop="ChineseName"
        sortable="custom"
        label="Name CN"
        min-width="100"
        show-overflow-tooltip
      />

      <el-table-column
        prop="ReviewerCode"
        label="ID"
        min-width="70"
        show-overflow-tooltip
        sortable="custom"
      />
      <el-table-column
        prop="Pending"
        label="Pending"
        min-width="100"
        show-overflow-tooltip
        sortable="custom"
      />
      <el-table-column
        prop="Approved"
        label="Approved"
        min-width="100"
        show-overflow-tooltip
        sortable="custom"
      />
      <el-table-column
        prop="Reading"
        label="Reading"
        min-width="100"
        show-overflow-tooltip
        sortable="custom"
      />
      <el-table-column
        prop="Finished"
        label="Finished"
        min-width="110"
        show-overflow-tooltip
        sortable="custom"
      />
      <el-table-column
        prop="Total"
        label="Total"
        min-width="90"
        show-overflow-tooltip
        sortable="custom"
      />
      <el-table-column
        prop="EntryRate"
        label="Entry Rate"
        min-width="110"
        show-overflow-tooltip
        sortable="custom"
      >
        <template slot-scope="scope">{{ scope.row.EntryRate }}%</template>
      </el-table-column>
    </el-table>
    <pagination class="page" :total="total" :page.sync="searchData.PageIndex" :limit.sync="searchData.PageSize" @pagination="getList" />
  </box-content>
</template>
<script>
import { getEnrollStatByReviewer } from '@/api/statistics'
import { exportExcelWithTotal } from '@/utils/export'
import { mapGetters } from 'vuex'
import store from '@/store'
import { enrollStats_form, enrollStats_handle } from '../statistics'
import Pagination from '@/components/Pagination'

import BoxContent from '@/components/BoxContent'
import SearchForm from '@/components/BaseForm/search-form'
const searchDataDefault = () => {
  return {
    HospitalId: '',
    Reviewer: '',
    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 {
  components: { Pagination, BoxContent, SearchForm },
  data() {
    return {
      list: [],
      searchData: searchDataDefault(),
      enrollStats_form,
      enrollStats_handle,
      total: 0,
      listLoading: false,
      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(['hospitalList'])
  },
  created() {
    store.dispatch('global/getHospital')
  },
  mounted() {
    this.getList()
  },
  methods: {
    // 获取入组医生列表信息
    getList() {
      this.listLoading = true
      getEnrollStatByReviewer(this.searchData)
        .then((res) => {
          this.listLoading = false
          this.list = res.Result.CurrentPageData
          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(() => {
        if(this.$refs.enrollmentStats){
          this.$refs.enrollmentStats.doLayout()
        }
      })
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 2) {
          sums[index] = 'Total (Current Page)'
          return
        }

        if (column.property === 'EntryRate') 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';
        }
      })
      sums[11] = (((sums[9] + sums[8]) * 100) / sums[10]).toFixed(2) + '%'
      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: 'Hospital', width: 25 },
        { key: 'LastName', width: 15 },
        { key: 'FirstName', width: 15 },
        { key: 'ChineseName', width: 10 },
        { key: 'ReviewerCode', width: 10 },
        { key: 'Pending', width: 10 },
        { key: 'Approved', width: 10 },
        { key: 'Reading', width: 10 },
        { key: 'Finished', width: 10 },
        { key: 'Total', width: 10 },
        { key: 'Rate', width: 20 }
      ]
      const conditional = `Beginning Month:${this.searchData.BeginDate}  End Month:${this.searchData.EndDate}`
      const headerArr = [
        '',
        'Hospital',
        'Surname',
        'Given Name',
        'Name CN',
        'Reviewer ID',
        'Pending',
        'Approved',
        'Reading',
        'Finished',
        'Total',
        'Entry rate(%)'
      ]

      var pending = 0
      var approved = 0
      var reading = 0
      var finished = 0
      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.Rate = element.EntryRate / 100
        pending += element.Pending
        approved += element.Approved
        reading += element.Reading
        finished += element.Finished
        total += element.Total
      })
      const totalRow = [
        '',
        'Total',
        '',
        '',
        '',
        '',
        pending,
        approved,
        reading,
        finished,
        total,
        (reading + finished) / total
      ]
      const numFmts = [{ colIndex: 12, format: '0.00%' }]
      exportExcelWithTotal(
        sheetName,
        columns,
        'Enrollments Statistics',
        conditional,
        headerArr,
        exportExcelData,
        totalRow,
        numFmts
      )
    }
  }
}
</script>
