<template>
  <confirm-dialog
    ref="dialog"
    size="lg fixed"
    title="在线时长报表"
    @confirm="onConfirm"
  >
    <template #default>
      <div class="l-flex__fill l-flex">
        <department-tree
          class="c-sibling-item c-sidebar u-width--xl"
          @change="onGroupChanged"
        />
        <div class="c-sibling-item far">
          <div class="c-sibling-item--v u-required">日期范围</div>
          <el-date-picker
            v-model="dateRange"
            class="c-sibling-item--v"
            type="daterange"
            range-separator="至"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions"
            :editable="false"
          />
        </div>
      </div>
    </template>
  </confirm-dialog>
</template>

<script>
import { mapGetters } from 'vuex'
import { parseTime } from '@/utils'
import {
  getOnlineDurationExcel,
  getRangeOnlineDurationExcel,
  getDepartmentOnlineDurationExcel,
  getDepartmentRangeOnlineDurationExcel
} from '../api'

export default {
  name: 'OnlineDurationDialog',
  data () {
    return {
      dateRange: []
    }
  },
  computed: {
    ...mapGetters(['tenant']),
    pickerOptions () {
      return {
        disabledDate: this.isDisableDate
      }
    }
  },
  methods: {
    show () {
      this.dateRange = [parseTime(new Date() - 3600000 * 24 * 6, '{y}-{m}-{d}'), parseTime(new Date(), '{y}-{m}-{d}')]
      this.$refs.dialog.show()
    },
    onGroupChanged (group) {
      this.$group = group
    },
    isDisableDate (date) {
      return date > Date.now()
    },
    onConfirm (done) {
      const groupPath = this.$group.path
      if (this.dateRange) {
        const time = this.dateRange[0] === this.dateRange[1] ? this.dateRange[0] : `${this.dateRange[0]}~${this.dateRange[1]}`
        if (this.tenant === groupPath) {
          getRangeOnlineDurationExcel({
            sumDateFrom: this.dateRange[0],
            sumDateTo: this.dateRange[1]
          }, time).then(done)
        } else {
          getDepartmentRangeOnlineDurationExcel({
            department: this.$group.path,
            sumDateFrom: this.dateRange[0],
            sumDateTo: this.dateRange[1]
          }, `${this.$group.name}_${time}`).then(done)
        }
      } else if (this.tenant === groupPath) {
        getOnlineDurationExcel().then(done)
      } else {
        getDepartmentOnlineDurationExcel(this.$group.path, this.$group.name).then(done)
      }
    }
  }
}
</script>
