<template>
  <div class="key-dm-stats-wrapper">
    <Tabs v-model="activeTab" @on-click="handleTabChange" class="tabsCls">
      <TabPane label="办公用品使用统计" name="usage">
        <div class="search-div">
          <Row type="flex" :gutter="16" align="middle">
            <Col :span="20">
              <span>开始：</span>
              <DatePicker v-model="usageStart" type="date" style="min-width:110px;margin-right:20px" />
              <span>结束：</span>
              <DatePicker v-model="usageEnd" type="date" style="min-width:110px;margin-right:20px" />
              <span>物料：</span>
              <Input v-model="usageMaterial" placeholder="物料名称或编码" style="width: 150px" />
            </Col>
            <Col :span="4" class="text-right">
              <Button type="primary" class="mr10" @click="loadUsage">统计</Button>
              <Button @click="resetUsage">重置</Button>
            </Col>
          </Row>
        </div>
        <Table :data="tables.usage" :loading="loading.usage" :columns="usageColumns" border>
          <template slot="action" slot-scope="{ row }">
            <Button size="small" @click="openUsageDetail(row)">详细</Button>
          </template>
        </Table>
      </TabPane>

      <TabPane label="工作量统计" name="workload">
        <div class="search-div">
          <Row type="flex" :gutter="16" align="middle">
            <Col :span="18">
              <span>开始：</span>
              <DatePicker v-model="workStart" type="date" style="min-width:110px;margin-right:20px" />
              <span>结束：</span>
              <DatePicker v-model="workEnd" type="date" style="min-width:110px;margin-right:20px" />
            </Col>
            <Col :span="6" class="text-right">
              <Button type="primary" class="mr10" @click="loadWorkload">统计</Button>
              <Button @click="resetWorkload">重置</Button>
            </Col>
          </Row>
        </div>
        <Table :data="tables.workload" :loading="loading.workload" :columns="workloadColumns" border>
          <template slot="action" slot-scope="{ row }">
            <Button size="small" class="mr10" @click="openWorkloadDetail(row,'leave')">请假明细</Button>
            <Button size="small" @click="openWorkloadDetail(row,'inventory')">申领明细</Button>
          </template>
        </Table>
      </TabPane>
    </Tabs>

    <!-- 使用明细弹窗 -->
    <Modal v-model="detailModal.visible" title="明细" width="800">
      <Table :data="detailModal.rows" :columns="detailModal.columns" size="small" border />
      <div slot="footer"><Button type="primary" @click="detailModal.visible=false">关闭</Button></div>
    </Modal>
  </div>
</template>

<script>
import { getUsageStats, getUsageDetails, getWorkloadStats, getWorkloadDetails } from '@/api/key-dm'
import { normalizeVisitTimeValue } from '@/view/key-person/key_dm_conf/dates.js'

export default {
  name: 'key-dm-stats-index',
  data () {
    return {
      activeTab: 'usage',
      usageStart: new Date(new Date().getFullYear(), new Date().getMonth(), 1),
      usageEnd: new Date(),
      usageMaterial: '',
      workStart: new Date(new Date().getFullYear(), new Date().getMonth(), 1),
      workEnd: new Date(),
      tables: { usage: [], workload: [] },
      loading: { usage: false, workload: false },
      usageColumns: [
        { type: 'index', title: '序号', width: 60, align: 'center' },
        { title: '部门', key: 'department_name', align: 'center' },
        { title: '物料', key: 'material_name', align: 'center' },
        { title: '领用数量', key: 'total_quantity', align: 'center' },
        { title: '操作', slot: 'action', width: 100, align: 'center' }
      ],
      workloadColumns: [
        { type: 'index', title: '序号', width: 60, align: 'center' },
        { title: '人员', key: 'user_name', align: 'center' },
        { title: '请假申请次数', key: 'leave_applications', align: 'center' },
        { title: '请假审批次数', key: 'leave_approvals', align: 'center' },
        { title: '用品申领次数', key: 'borrow_applications', align: 'center' },
        { title: '入库次数', key: 'inbound_count', align: 'center' },
        { title: '请假时长(天)', key: 'leave_duration', align: 'center' },
        { title: '操作', slot: 'action', width: 200, align: 'center' }
      ],
      detailModal: {
        visible: false,
        rows: [],
        columns: []
      }
    }
  },
  created () {
    this.loadUsage()
  },
  methods: {
    handleTabChange (name) {
      this.activeTab = name
      if (name === 'usage') {
        this.loadUsage()
      } else {
        this.loadWorkload()
      }
    },
    loadUsage () {
      this.loading.usage = true
      const st = this.usageStart ? normalizeVisitTimeValue(this.usageStart) : null
      const et = this.usageEnd ? normalizeVisitTimeValue(this.usageEnd) : null
      const params = { start: st, end: et, material: this.usageMaterial }
      getUsageStats(params).then(ret => {
        if (ret.data && ret.data.errcode === 0) this.tables.usage = ret.data.data || []
        else this.$Notice.error({ title: '查询失败', desc: ret.data && ret.data.errmsg })
      }).finally(() => { this.loading.usage = false })
    },
    resetUsage () { this.usageStart = null; this.usageEnd = null; this.usageMaterial = ''; this.tables.usage = [] },
    openUsageDetail (row) {
      this.detailModal.columns = [
        { title: '部门', key: 'department_name', align: 'center' },
        { title: '人员', key: 'user_name', align: 'center' },
        { title: '物料', key: 'material_name', align: 'center' },
        { title: '申请数量', key: 'apply_quantity', align: 'center' },
        { title: '已归还数量', key: 'returned_quantity', align: 'center' }
      ]
      this.detailModal.visible = true
      const st = this.usageStart ? normalizeVisitTimeValue(this.usageStart) : null
      const et = this.usageEnd ? normalizeVisitTimeValue(this.usageEnd) : null
      getUsageDetails({ start: st, end: et, material: row.material_id, department: row.department_id }).then(ret => {
        if (ret.data && ret.data.errcode === 0) this.detailModal.rows = ret.data.data || []
        else this.$Notice.error({ title: '查询失败', desc: ret.data && ret.data.errmsg })
      })
    },
    loadWorkload () {
      this.loading.workload = true
      const st = this.workStart ? normalizeVisitTimeValue(this.workStart) : null
      const et = this.workEnd ? normalizeVisitTimeValue(this.workEnd) : null
      const params = { start: st, end: et }
      getWorkloadStats(params).then(ret => {
        if (ret.data && ret.data.errcode === 0) this.tables.workload = ret.data.data || []
        else this.$Notice.error({ title: '查询失败', desc: ret.data && ret.data.errmsg })
      }).finally(() => { this.loading.workload = false })
    },
    resetWorkload () { this.workStart = null; this.workEnd = null; this.tables.workload = [] },
    openWorkloadDetail (row, type) {
      const st = this.workStart ? normalizeVisitTimeValue(this.workStart) : null
      const et = this.workEnd ? normalizeVisitTimeValue(this.workEnd) : null
      if (type === 'leave') {
        this.detailModal.columns = [
          { title: '人员', key: 'user_name', align: 'center' },
          { title: '开始', key: 'start_time', align: 'center', render: (h, params) => {
            const time = params.row.start_time
            if (time) {
              const date = new Date(time)
              const year = date.getFullYear()
              const month = String(date.getMonth() + 1).padStart(2, '0')
              const day = String(date.getDate()).padStart(2, '0')
              const hours = String(date.getHours()).padStart(2, '0')
              const minutes = String(date.getMinutes()).padStart(2, '0')
              const seconds = String(date.getSeconds()).padStart(2, '0')
              return h('span', `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`)
            }
            return h('span', '-')
          }},
          { title: '结束', key: 'end_time', align: 'center', render: (h, params) => {
            const time = params.row.end_time
            if (time) {
              const date = new Date(time)
              const year = date.getFullYear()
              const month = String(date.getMonth() + 1).padStart(2, '0')
              const day = String(date.getDate()).padStart(2, '0')
              const hours = String(date.getHours()).padStart(2, '0')
              const minutes = String(date.getMinutes()).padStart(2, '0')
              const seconds = String(date.getSeconds()).padStart(2, '0')
              return h('span', `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`)
            }
            return h('span', '-')
          }},
          { title: '时长', key: 'duration', align: 'center' },
          { title: '状态', key: 'status', align: 'center', render: (h, params) => {
            const status = params.row.status
            let statusText = ''
            switch (status) {
              case 0: statusText = '未提交'; break
              case 1: statusText = '审核中'; break
              case 9: statusText = '审核通过'; break
              case -1: statusText = '驳回'; break
              default: statusText = status
            }
            return h('span', statusText)
          }}
        ]
        getWorkloadDetails({ user_id: row.user_id, start: st, end: et, type: 'leave' }).then(ret => {
          if (ret.data && ret.data.errcode === 0) { this.detailModal.rows = ret.data.data || []; this.detailModal.visible = true } else this.$Notice.error({ title: '查询失败', desc: ret.data && ret.data.errmsg })
        })
      } else {
        this.detailModal.columns = [
          { title: '申请时间', key: 'submit_time', align: 'center', render: (h, params) => {
            const time = params.row.submit_time
            if (time) {
              const date = new Date(time)
              const year = date.getFullYear()
              const month = String(date.getMonth() + 1).padStart(2, '0')
              const day = String(date.getDate()).padStart(2, '0')
              const hours = String(date.getHours()).padStart(2, '0')
              const minutes = String(date.getMinutes()).padStart(2, '0')
              const seconds = String(date.getSeconds()).padStart(2, '0')
              return h('span', `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`)
            }
            return h('span', '-')
          }},
          { title: '物料', key: 'material_name', align: 'center' },
          { title: '申请数量', key: 'apply_quantity', align: 'center' },
          { title: '归还数量', key: 'returned_quantity', align: 'center' },
          { title: '状态', key: 'approval_status', align: 'center', render: (h, params) => {
            const status = params.row.approval_status
            let statusText = ''
            switch (status) {
              case 0: statusText = '待提交'; break
              case 1: statusText = '审核中'; break
              case 9: statusText = '审核通过'; break
              case -1: statusText = '驳回'; break
              default: statusText = status
            }
            return h('span', statusText)
          }}

        ]
        getWorkloadDetails({ user_id: row.user_id, start: st, end: et, type: 'inventory' }).then(ret => {
          if (ret.data && ret.data.errcode === 0) { this.detailModal.rows = ret.data.data || []; this.detailModal.visible = true } else this.$Notice.error({ title: '查询失败', desc: ret.data && ret.data.errmsg })
        })
      }
    }
  }
}
</script>

<style scoped>
.key-dm-stats-wrapper { padding: 10px; min-height: 380px;}
.tabsCls { min-height: 380px;}
.search-div { border: 1px solid #dce1e7; padding: 12px; margin-bottom: 12px; background-color: #f8fbff; }
.mr10 { margin-right: 10px; }
.text-right { text-align: right; }
.page_style { margin-top: 12px; text-align: right; }
.mt8 { margin-top: 8px; }
.mr5 {
  margin-right: 5px;
}
.mr10 {
  margin-right: 10px;
}
.ml5 {
  margin-left: 5px;
}
</style>
