<template>
  <div class="page-header-index-wide">
    <a-card :bordered="false">
      <a-tabs v-model="activeTab" @change="handleTabChange">
        <a-tab-pane tab="按维修人统计" key="user"></a-tab-pane>
        <a-tab-pane tab="按设备统计" key="sb"></a-tab-pane>
      </a-tabs>

      <div class="table-page-search-wrapper" @keyup.enter="handleSearch">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="8" :sm="24" v-if="activeTab === 'user'">
              <a-form-item label="维修人">
                <a-input v-model="queryParam.repairUserName" placeholder="请输入维修人姓名" allow-clear/>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24" v-else>
              <a-form-item label="设备">
                <a-input v-model="queryParam.keyword" placeholder="请输入设备名称/编号" allow-clear/>
              </a-form-item>
            </a-col>
            <a-col :md="10" :sm="24">
              <a-form-item label="维修开始时间">
                <a-range-picker
                  v-model="dateRange"
                  format="YYYY-MM-DD"
                  style="width: 100%"
                  :placeholder="['开始日期', '结束日期']"/>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <span class="table-page-search-submitButtons">
                <a-button type="primary" @click="handleSearch">查询</a-button>
                <a-button style="margin-left: 8px" @click="resetSearchForm">重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <div class="table-operator">
        <a-button type="primary" icon="download" @click="doExport">导出</a-button>
      </div>

      <s-table
        ref="table"
        size="default"
        :rowKey="rowKey"
        :columns="columns"
        :data="loadData"
        showPagination="auto"
      >
        <span slot="action" slot-scope="record">
          <template>
            <a @click="handleDetail(record)">查看明细</a>
            <a-divider type="vertical"/>
            <a @click="doExportDetail(record)">导出明细</a>
          </template>
        </span>
      </s-table>
    </a-card>

    <detail-modal ref="detailModal"/>
  </div>
</template>

<script>
import { STable } from '@/components'
import DetailModal from './modules/DetailModal'
import {
  getWorkHourByUser,
  getWorkHourBySb,
  exportWorkHourUser,
  exportWorkHourSb,
  exportWorkHourDetail
} from '@/api/report/application-form'

export default {
  name: 'RepairWorkHourReport',
  components: {
    STable,
    DetailModal
  },
  data () {
    return {
      // 当前统计维度：user-按维修人，sb-按设备
      activeTab: 'user',
      // 查询参数
      queryParam: {
        repairUserName: null,
        keyword: null
      },
      // 维修开始时间范围
      dateRange: [],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        const query = this.buildQuery()
        parameter = {
          ...parameter,
          ...query
        }
        const fetchFn = this.activeTab === 'user' ? getWorkHourByUser : getWorkHourBySb
        return fetchFn(parameter)
          .then(res => {
            return res.data
          })
      }
    }
  },
  computed: {
    rowKey () {
      return this.activeTab === 'user' ? 'repairUserId' : 'sbId'
    },
    columns () {
      const indexColumn = {
        title: '序号',
        checked: true,
        dataIndex: 'index',
        width: '70px',
        customRender: (text, record, index) => {
          const pagination = this.$refs.table && this.$refs.table.localPagination
          if (pagination) {
            return `${(pagination.current - 1) * pagination.pageSize + index + 1}`
          }
          return `${index + 1}`
        }
      }
      const hourRender = (text) => {
        return this.BaseTool.Object.isBlank(text) ? '0.00' : Number(text).toFixed(2)
      }
      const commonColumns = [
        {
          title: '维修次数',
          checked: true,
          dataIndex: 'num'
        },
        {
          title: '总维修工时(小时)',
          checked: true,
          dataIndex: 'totalRepairHours',
          customRender: hourRender
        },
        {
          title: '平均工时(小时)',
          checked: true,
          dataIndex: 'avgRepairHours',
          customRender: hourRender
        },
        {
          title: '总停机修复时长(小时)',
          checked: true,
          dataIndex: 'totalDealHours',
          customRender: hourRender
        },
        {
          title: '操作',
          checked: true,
          key: 'action',
          width: '180px',
          align: 'center',
          scopedSlots: { customRender: 'action' }
        }
      ]
      if (this.activeTab === 'user') {
        return [
          indexColumn,
          {
            title: '维修人',
            checked: true,
            dataIndex: 'repairUserName'
          },
          ...commonColumns
        ]
      }
      return [
        indexColumn,
        {
          title: '设备编号',
          checked: true,
          dataIndex: 'sbNo'
        },
        {
          title: '设备名称',
          checked: true,
          dataIndex: 'sbName'
        },
        ...commonColumns
      ]
    }
  },
  methods: {
    buildQuery () {
      const query = {}
      if (this.activeTab === 'user') {
        if (this.BaseTool.String.isNotBlank(this.queryParam.repairUserName)) {
          query.repairUserName = this.queryParam.repairUserName
        }
      } else {
        if (this.BaseTool.String.isNotBlank(this.queryParam.keyword)) {
          query.keyword = this.queryParam.keyword
        }
      }
      if (this.dateRange && this.dateRange.length === 2) {
        query.searchRepairStartTime = this.dateRange[0].format('YYYY-MM-DD') + ' 00:00:00'
        query.searchRepairEndTime = this.dateRange[1].format('YYYY-MM-DD') + ' 23:59:59'
      }
      return query
    },
    handleTabChange () {
      this.$nextTick(() => {
        this.$refs.table.refresh(true)
      })
    },
    handleSearch () {
      this.$refs.table.refresh(true)
    },
    resetSearchForm () {
      this.queryParam = {
        repairUserName: null,
        keyword: null
      }
      this.dateRange = []
      this.$refs.table.refresh(true)
    },
    doExport () {
      const parameter = this.buildQuery()
      const exportFn = this.activeTab === 'user' ? exportWorkHourUser : exportWorkHourSb
      exportFn(parameter).then(file => {
        this.BaseTool.UPLOAD.downLoadExportExcel(file)
      })
    },
    handleDetail (record) {
      const modal = this.$refs.detailModal
      modal.base({
        type: this.activeTab,
        record: record,
        searchRepairStartTime: this.buildQuery().searchRepairStartTime,
        searchRepairEndTime: this.buildQuery().searchRepairEndTime
      })
    },
    doExportDetail (record) {
      const parameter = this.buildDetailQuery(record)
      exportWorkHourDetail(parameter).then(file => {
        this.BaseTool.UPLOAD.downLoadExportExcel(file)
      })
    },
    buildDetailQuery (record) {
      const parameter = {}
      if (this.activeTab === 'user') {
        parameter.repairUserId = record.repairUserId
      } else {
        parameter.sbId = record.sbId
      }
      const timeQuery = this.buildQuery()
      if (timeQuery.searchRepairStartTime) {
        parameter.searchRepairStartTime = timeQuery.searchRepairStartTime
      }
      if (timeQuery.searchRepairEndTime) {
        parameter.searchRepairEndTime = timeQuery.searchRepairEndTime
      }
      return parameter
    }
  }
}
</script>

<style lang="less" scoped>
</style>
