<template>
  <div class="app-container">
    <div v-if="isPercentage" class="percentage" style="width: 210px;height: 90px;background: #fff;position: fixed;bottom: 0;left: 0;z-index: 9999999999999;">
      <h4 style="padding-left: 10px;line-height: 0;">导出进度：</h4>
      <el-progress style="padding-left: 10px;" :text-inside="true" :stroke-width="26" :percentage="percentage" />
    </div>
    <div class="filter-container">
      <el-select  v-if="isPasture || isType3" v-model="tableObj.getdataListParm.parammaps.pastureName" placeholder="牧场" style="width: 140px;" class="filter-item" >
        <el-option v-for="item in pastureList" :key="item.id" :label="item.name" :value="item.name" />
      </el-select>
      <el-select  v-if="isPasture || isType" v-model="tableObj.getdataListParm.parammaps.eqClassId" placeholder="设备类别" style="width: 140px;" class="filter-item" clearable>
        <el-option v-for="item in eqClassList" :key="item.id" :label="item.remark" :value="item.id" />
      </el-select>
      <el-select  v-if=" isType3" v-model="tableObj.getdataListParm.parammaps.eqClassId" placeholder="设备类别" style="width: 140px;" class="filter-item" clearable>
        <el-option v-for="item in eqClassList3" :key="item.id" :label="item.remark" :value="item.id" />
      </el-select>
      <el-date-picker v-if="isPasture" ref="inputDatetime" v-model="tableObj.getdataListParm.parammaps.inputDatetime" class="inputDatetime" type="datetimerange" style="width: 280px;top:-3px;" format="yyyy-MM-dd" value-format="yyyy-MM-dd" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" :clearable="false" />
      <el-input  v-if="isType2" v-model="tableObj.getdataListParm.parammaps.eqName" placeholder="设备名称" style="width: 200px;" class="filter-item" />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="form_search">搜索</el-button>
      <el-button class="filter-item" type="success" icon="el-icon-upload2" @click="form_export">导出</el-button>
    </div>
    <div v-if="isTitle" style="line-height:50px;height:50px"><b @click="goFirst">所有牧场</b>&gt;<span>{{ this.pastureName }}</span></div>
    <div v-if="isTitle2" style="line-height:50px;height:50px"><b @click="goFirst">所有牧场</b>&gt;<span @click="goSecond">{{ this.pastureName }}</span>&gt;<span>{{ this.typename }}</span></div>
    <div v-if="isTitle3" style="line-height:50px;height:50px"><b @click="goFirst">所有资产</b>&gt;<span>{{ this.eqClassName }}</span></div>
    <el-table
      :key="tableObj.tableKey"
      v-loading="tableObj.listLoading"
      element-loading-text="给我一点时间"
      :data="tableObj.list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      :row-style="rowStyle"
      :cell-style="tableCellStyle"
      class="elTable"
      @sort-change="tableSort1"
      :max-height="myHeight"
    >
      <el-table-column label="序号" align="center" type="index" width="50px">
        <template slot-scope="scope">
          <span>{{ scope.$index + (pageNum-1) * pageSize + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="isPasture" :key="1" label="牧场" min-width="140px" sortable align="center">
        <template slot-scope="{row}">
          <a @click="table_click1(row)">{{ row.pastureName }}</a>
        </template>
      </el-table-column>
      <el-table-column  v-if="isPasture" :key="5" label="设备二级分类名称" sortable min-width="140px" align="center">
        <template slot-scope="{row}">
          <a @click="table_click4(row)" style="text-decoration: underline;">{{ row.eqClassName }}</a>
        </template>
      </el-table-column>
      <el-table-column  v-if="isType" :key="5" label="设备三级分类名称"  sortable min-width="140px" align="center">
        <template slot-scope="{row}">
          <a @click="table_click2(row)">{{ row.eqClassName }}</a>
        </template>
      </el-table-column>
      <el-table-column  v-if="isType2" label="设备名称" sortable min-width="140px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.eqName }}</span>
        </template>
      </el-table-column>
      <el-table-column  v-if="isType2" label="设备内部编号" sortable min-width="140px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.eqCode }}</span>
        </template>
      </el-table-column>

      <el-table-column  v-if="isType3" :key="5" label="牧场"  sortable min-width="140px" align="center" prop="pastureName" />
      <el-table-column  v-if="isType3" :key="5" label="设备三级分类名称"  sortable min-width="140px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.eqClassName }}</span>
        </template>
      </el-table-column>

      <el-table-column   :key="6" label="维修次数" sortable min-width="140px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.count }}</span>
        </template>
      </el-table-column>
      <el-table-column   :key="7" label="平均维修时间（MTTR）" sortable min-width="140px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.mttr }}</span>
        </template>
      </el-table-column>
      <el-table-column   :key="8" label="无故障时间（MTTF）" sortable min-width="140px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.mttf }}</span>
        </template>
      </el-table-column>
      <el-table-column   :key="9" label="平均故障间隔时间（MTBF）" sortable min-width="140px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.mtbf }}</span>
        </template>
      </el-table-column>


    </el-table>
    <pagination v-show="tableObj.total>0" :total="tableObj.total" :page.sync="tableObj.getdataListParm.parammaps.offset" :limit.sync="tableObj.getdataListParm.parammaps.pagecount" @pagination="get_table_data" />
  </div>

</template>

<script>
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import {  GetDataByName, GetDataByNames, GetMaintain, PostDataByName, checkButtons, ExecDataByConfig, GetAccount, getRecuData } from '@/api/common'

import { parseTime, json2excel, sortChange } from '@/utils/index.js'
import TreeSelect from '@/components/TreeSelect'
import Cookies from 'js-cookie'
export default {
  name: 'MaintenanceFault',
  components: { Pagination, TreeSelect },
  directives: { waves },
  data() {
    return {
      rowStyle: { maxHeight: 50 + 'px', height: 45 + 'px' },
      cellStyle: { padding: 0 + 'px' },
      pickerOptions1: {
        disabledDate(time) {
          return time.getTime() > new Date().getTime() - 24 * 60 * 60 * 1000
        }
      },
      isTitle: false,
      isTitle3:false,
      isTitle2: false,
      isPasture: true,
      isType: false,
      isType2: false,
      isType3:false,
      pastureName: '',
      eqName: '',
      eqClassName:'',
      eqNameList: [],
      pastureList: [],
      eqClassList: [],
      eqClassList2: [],
      eqClassList3: [],
      // tableObj: {
      //   tableKey: 0,
      //   list: [],
      //   total: 0,
      //   listLoading: true,
      //   getdataListParm: {
      //     name: 'pasture',
      //     page: 1,
      //     offset: 1,
      //     pagecount: 10,
      //     returntype: 'Map',
      //     parammaps: {
      //       eqClassId: '',  startTime: '',pastureName: '', pastureId:"",
      //       endTime: '',level: 1,
      //       inputDatetime: []
      //     }
      //   }
      // },
      pageNum: 0,
      pageSize: 0,
      tableObj: {
        tableKey: 0,
        list: [],
        total: 0,
        listLoading: true,
        getdataListParm: {
          name: 'pasture',
          returntype: 'Map',
          parammaps: {
            eqClassId: '',  startTime: '',pastureName: '', pastureId:"",
            endTime: '',level: 1,page: 1,  offset: 1, pagecount: 10,eqName:"",
            inputDatetime: []
          }
        }
      },


      disabled: false,
      placeholder: '请选择设备类别',
      nodeKey: 'id',

      parentClass: [],

      getRecuListParm: {
        name: 'getAssetTypeList',
        idname: 'id',
        params: [-1]
      },
      dataform: {
        eqClassId: '',
        typeCode: ''
      },

      downLoadParm: {},
      downLoadList: [],
      isPercentage: false,
      percentage: 1,
      myHeight:document.documentElement.clientHeight - 85- 150
    }
  },

  created() {
    this.getTimeFn()

    this.get_select_list()
  },

  methods: {

    get_select_list() {
      var send_data =  [

        { name: 'findAllPasture', offset: 0, pagecount: 0, returntype: 'Map', parammaps: { 'id': Cookies.get('pastureid') }},
        { name: 'getEqClassBengbu', offset: 0, pagecount: 0, returntype: 'Map', parammaps: { 'section': '2' }}


      ]



      GetDataByNames(send_data).then(response => {

        this.pastureList = response.data.findAllPasture.list
        this.eqClassList = response.data.getEqClassBengbu.list

      })

      GetDataByName( { name: 'getEqClassBengbu', offset: 0, pagecount: 0, returntype: 'Map', parammaps: { 'section': '2' }}).then(response => {

        this.eqClassList2 = response.data.list

      })
      GetDataByName( { name: 'getEqClassBengbu', offset: 0, pagecount: 0, returntype: 'Map', parammaps: { 'section': '3' }}).then(response => {

        this.eqClassList3 = response.data.list

      })
    },

    tableSort1(column) {
      sortChange(column, this.tableObj.list)
    },
    getTimeFn() {
      const that = this
      const start = new Date()
      const end = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      that.tableObj.getdataListParm.parammaps.inputDatetime[0] = parseTime(start, '{y}-{m}-{d}')
      that.tableObj.getdataListParm.parammaps.inputDatetime[1] = parseTime(end, '{y}-{m}-{d}')
      that.tableObj.getdataListParm.parammaps.startTime = that.tableObj.getdataListParm.parammaps.inputDatetime[0]
      that.tableObj.getdataListParm.parammaps.endTime = that.tableObj.getdataListParm.parammaps.inputDatetime[1]
      that.get_table_data()
    },
    get_table_data() {
      this.tableObj.listLoading = true
      if (Cookies.get('pastureid') == 18) {
        this.tableObj.getdataListParm.parammaps.pastureId = ''
      } else {
        this.tableObj.getdataListParm.parammaps.pastureId = Cookies.get('pastureid')
      }
      GetMaintain(this.tableObj.getdataListParm.parammaps).then(response => {
        console.log('table数据', response.data)
        this.tableObj.list = response.data
        this.pageNum = response.pageNum
        this.pageSize = response.pageSize
        this.tableObj.total = response.total
        setTimeout(() => {
          this.tableObj.listLoading = false
        }, 100)
      })
    },
    form_search() {
      this.tableObj.listLoading = true
      this.tableObj.getdataListParm.offset = 1
      this.tableObj.getdataListParm.parammaps.startTime = this.tableObj.getdataListParm.parammaps.inputDatetime[0]
      this.tableObj.getdataListParm.parammaps.endTime = this.tableObj.getdataListParm.parammaps.inputDatetime[1]
      if (this.isPasture == false) {

        // console.log(this.dataform.eqClassId)
        // if (this.dataform.eqClassId == null) {
        //   this.tableObj.getdataListParm.parammaps.typecode = ''
        // } else {
        //   this.tableObj.getdataListParm.parammaps.typecode = this.dataform.typeCode
        // }
      } else {
        // this.tableObj.getdataListParm.parammaps.typecode = ''

      }
      this.get_table_data()
    },
    tableCellStyle({ row, column, rowIndex, columnIndex }) {
      if (row.name !== '现代牧业' && row.typename == null && columnIndex === 1 && this.isPasture == true) {
        return {
          textDecoration: 'underline'
        }
      }
      if (this.isType == true  ) {
        if (row.typename !== null && columnIndex == 1) {
          return {
            textDecoration: 'underline'
          }
        }
      }

      if (this.isType2 == true  ) {
        return {
          textDecoration: 'none'
        }
      }
      return {
        textDecoration: 'none'
      }
    },
    table_click1(row) {
      if (row.name !== '现代牧业') {
        this.pastureName = row.pastureName
        this.tableObj.getdataListParm.parammaps.offset = 1
        this.tableObj.getdataListParm.parammaps.pastureId = row.pastureId
        this.tableObj.getdataListParm.parammaps.pastureName = row.pastureName
        this.tableObj.getdataListParm.parammaps.level = "2"
        this.tableObj.getdataListParm.parammaps.eqClassId = ""
        this.get_table_data()
        this.isPasture = false
        this.isType = true
        this.isType2 = false
        this.isTitle = true
        this.isTitle2 = false
        this.isType3 = false
      }
      this.eqClassList =  this.eqClassList3
    },
    table_click2(row) {
      this.tableObj.getdataListParm.parammaps.offset = 1
      this.typename = row.eqClassName
      this.tableObj.getdataListParm.parammaps.pastureId = row.pastureId
      this.tableObj.getdataListParm.parammaps.pastureName = row.pastureName
      this.tableObj.getdataListParm.parammaps.level = "3"
      this.tableObj.getdataListParm.parammaps.eqClassId = row.eqClassId
      this.tableObj.getdataListParm.parammaps.eqName = ""
      this.get_table_data()
      this.isPasture = false
      this.isType = false
      this.isType2 = true
      this.isTitle = false
      this.isTitle2 = true
    },
    table_click3(row) {
      if (Cookies.get('pasturename') == '现代牧业') {
        this.$router.push({ path: '/maintenance/MaintenancePlan', query: { myPath: 'CompletionRateMaintenance', eqCode: row.eqCode, pastureName: this.pastureName }})
      } else {
        if (this.pastureName == Cookies.get('pasturename')) {
          this.$router.push({ path: '/maintenance/MaintenancePlan', query: { myPath: 'CompletionRateMaintenance', eqCode: row.eqCode, pastureName: this.pastureName }})
        } else {
          this.$message({ type: 'error', message: '请联系管理员开通相关牧场数据权限' })
        }
      }
    },
    goFirst() {
      console.log("goFirst")
      this.tableObj.getdataListParm.offset = 1
      this.tableObj.getdataListParm.parammaps.eqClassPIdStr = ''
      this.tableObj.getdataListParm.parammaps.level = "1"
      this.tableObj.getdataListParm.parammaps.eqName = ''
      this.tableObj.getdataListParm.parammaps.eqClassId = ''
      this.tableObj.getdataListParm.parammaps.pastureId = ''
      this.tableObj.getdataListParm.parammaps.pastureName = ''
      this.eqClassList =  this.eqClassList2
      this.get_table_data()
      this.isType = false
      this.isType2 = false
      this.isTitle = false
      this.isTitle2 = false
      this.isTitle3 = false
      this.isPasture = true
      this.isType3 = false
      this.isTitle3 = false
      GetDataByName( { name: 'getEqClassBengbu', offset: 0, pagecount: 0, returntype: 'Map', parammaps: {
        'section': '3','pid':'' }}).then(response => {
      
        this.eqClassList3 = response.data.list
      
      })
    },
    goSecond() {
      console.log("goSecond")
      this.isType = true
      this.isType2 = false
      this.isTitle = true
      this.isTitle2 = false
      this.tableObj.getdataListParm.offset = 1
      this.tableObj.getdataListParm.parammaps.level = "2"
      this.tableObj.getdataListParm.parammaps.eqName = ''
      this.tableObj.getdataListParm.parammaps.eqClassId = ''
      this.tableObj.getdataListParm.parammaps.pastureId = ''
      this.tableObj.getdataListParm.parammaps.pastureName = ''

      this.eqClassList =  this.eqClassList3
      // this.tableObj.getdataListParm.parammaps.pastureid = this.tableObj.getdataListParm.parammaps.pastureid
      this.get_table_data()
    },


    form_export() {

      if (Cookies.get('pastureid') == 18) {
        this.tableObj.getdataListParm.parammaps.pastureId = ''
      } else {
        this.tableObj.getdataListParm.parammaps.pastureId = Cookies.get('pastureid')
      }

      if (this.isPasture) {

        console.log('设备导出')
        this.$alert('维修故障统计正在导出中，请勿刷新或离开本页面，若导出时间过长，建议缩小导出数据范围重新导出', {})
        this.isPercentage = true
        this.percentage = 1
        var timer = setInterval(() => {
          this.percentage += 5
          if (this.percentage > 95) {
            this.percentage = 99
            clearInterval(timer)
          }
          this.percentage = this.percentage
        }, 1000)
        this.downLoadParm.getdataListParm = {}

        this.downLoadParm.getdataListParm.pagecount = 0
        this.downLoadParm.getdataListParm.parammaps = this.tableObj.getdataListParm.parammaps


      //   this.tableObj.listLoading = true
      // this.tableObj.getdataListParm.offset = 1
      // this.tableObj.getdataListParm.parammaps.startTime = this.tableObj.getdataListParm.parammaps.inputDatetime[0]
      // this.tableObj.getdataListParm.parammaps.endTime = this.tableObj.getdataListParm.parammaps.inputDatetime[1]

      this.downLoadParm.getdataListParm.parammaps.pagecount = ""
      GetMaintain(this.downLoadParm.getdataListParm.parammaps ).then(response => {
          if (response.data !== '') {
            this.percentage = 99
            setTimeout(() => {
              this.isPercentage = false
            }, 2000)
          }
          this.$nextTick(() => {
            this.downLoadParm.list = response.data
            var excelDatas = [
              {
                tHeader: ['牧场', '设备二级分类名称', '维修次数', '平均维修时间（MTTR）', '无故障时间（MTTF）', '平均故障间隔时间（MTBF）'],
                filterVal: ['pastureName', 'eqClassName', 'count', 'mttr', 'mttf', 'mtbf' ],
                tableDatas: this.downLoadParm.list,
                sheetName: '设备'
              }
            ]
            json2excel(excelDatas, '维修故障统计', true, 'xlsx')
          })
        })
      } else if(this.isType){


        console.log('设备导出')
        this.$alert('维修故障统计正在导出中，请勿刷新或离开本页面，若导出时间过长，建议缩小导出数据范围重新导出', {})
        this.isPercentage = true
        this.percentage = 1
        var timer = setInterval(() => {
          this.percentage += 5
          if (this.percentage > 95) {
            this.percentage = 99
            clearInterval(timer)
          }
          this.percentage = this.percentage
        }, 1000)
        this.downLoadParm.getdataListParm = {}

        this.downLoadParm.getdataListParm.pagecount = 0
        this.downLoadParm.getdataListParm.parammaps = this.tableObj.getdataListParm.parammaps

        this.downLoadParm.getdataListParm.parammaps.pagecount = ""

      GetMaintain(this.downLoadParm.getdataListParm.parammaps ).then(response => {
          if (response.data !== '') {
            this.percentage = 99
            setTimeout(() => {
              this.isPercentage = false
            }, 2000)
          }
          this.$nextTick(() => {
            this.downLoadParm.list = response.data
            var excelDatas = [
              {
                tHeader: [ '设备三级分类名称', '维修次数', '平均维修时间（MTTR）', '无故障时间（MTTF）', '平均故障间隔时间（MTBF）'],
                filterVal: [ 'eqClassName', 'count', 'mttr', 'mttf', 'mtbf' ],
                tableDatas: this.downLoadParm.list,
                sheetName: '设备'
              }
            ]
            json2excel(excelDatas, '维修故障统计', true, 'xlsx')
          })
        })

      } else {
        console.log('设备导出')
        this.$alert('维修故障统计正在导出中，请勿刷新或离开本页面，若导出时间过长，建议缩小导出数据范围重新导出', {})
        this.isPercentage = true
        this.percentage = 1
        var timer = setInterval(() => {
          this.percentage += 5
          if (this.percentage > 95) {
            this.percentage = 99
            clearInterval(timer)
          }
          this.percentage = this.percentage
        }, 1000)
        this.downLoadParm.getdataListParm = {}

        this.downLoadParm.getdataListParm.pagecount = 0
        this.downLoadParm.getdataListParm.parammaps = this.tableObj.getdataListParm.parammaps


        this.downLoadParm.getdataListParm.parammaps.pagecount = ""
      GetMaintain(this.downLoadParm.getdataListParm.parammaps ).then(response => {
          if (response.data !== '') {
            this.percentage = 99
            setTimeout(() => {
              this.isPercentage = false
            }, 2000)
          }
          this.$nextTick(() => {
            this.downLoadParm.list = response.data
            var excelDatas = [
              {
                tHeader: [   '设备名称','设备内部编号','维修次数', '平均维修时间（MTTR）', '无故障时间（MTTF）', '平均故障间隔时间（MTBF）'],
                filterVal: [ '维修次数','维修次数',  'count', 'mttr', 'mttf', 'mtbf' ],
                tableDatas: this.downLoadParm.list,
                sheetName: '设备'
              }
            ]
            json2excel(excelDatas, '维修故障统计', true, 'xlsx')
          })
        })
      }
    },
    table_click4(row){
      this.isTitle3 = true
      this.isType3 = true
      this.isTitle2 = false
      this.isPasture = false
      this.isType = false
      this.isType2 = false
      this.eqClassName = row.eqClassName
      this.tableObj.getdataListParm.parammaps.offset = 1
      this.tableObj.getdataListParm.parammaps.level = "2"
      this.tableObj.getdataListParm.parammaps.eqClassPIdStr = row.eqId
      this.tableObj.getdataListParm.parammaps.eqClassId = ''
      this.get_table_data()
      GetDataByName( { name: 'getEqClassBengbu', offset: 0, pagecount: 0, returntype: 'Map', parammaps: {
        'section': '3','pid':row.eqId }}).then(response => {

        this.eqClassList3 = response.data.list

      })
    }

  }
}
</script>
