<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-date-picker
        v-if="isPasture"
        ref="inputDatetime"
        v-model="table.getdataListParm.parammaps.inputDatetime"
        class="inputDatetime"
        type="datetimerange"
        style="width: 250px;top:-3px;"
        format="yyyy-MM-dd"
        value-format="yyyy-MM-dd"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        :clearable="false"
      />
      <tree-select
        v-if="isType"
        class="typeSelect"
        :height="150"
        :width="250"
        size="small"
        clearable
        :data="parentClass"
        :disabled="disabled"
        :placeholder="placeholder"
        style="display:inline-block;"
        :default-props="defaultProps"
        :node-key="nodeKey"
        :checked-keys="defaultCheckedKeys"
        @popoverHide="popoverHide"
      />
      <el-select v-if="isType2" v-model="eqName" style="width: 140px;" placeholder="设备名称" class="filter-item">
        <el-option v-for="item in eqNameList" :key="item.id" :label="item.name" :value="item.name" />
      </el-select>
      <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" style="position:absolute ;right:10px" @click="handleDownload">导出</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>
    <el-table
      :key="table.tableKey"
      v-loading="table.listLoading"
      element-loading-text="给我一点时间"
      :data="table.list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      :row-style="rowStyle"
      :cell-style="tableCellStyle"
      class="elTable"
      @sort-change="tableSort1"
    >
      <el-table-column label="序号" align="center" type="index" width="50px">
        <template slot-scope="scope">
          <span>{{ scope.$index + (table.pageNum-1) * table.pageSize + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="isPasture" :key="1" label="牧场" min-width="140px" align="center">
        <template slot-scope="{row}">
          <a @click="tableCellClick(row)">{{ row.name }}</a>
        </template>
      </el-table-column>

      <el-table-column v-if="isType" :key="2" label="设备分类" min-width="140px" align="center">
        <template slot-scope="{row}">
          <a @click="tableCellClick2(row)">{{ row.typename }}</a>
        </template>
      </el-table-column>
      <el-table-column v-if="isType2" :key="3" label="设备名称" min-width="140px" align="center">
        <template slot-scope="{row}">
          <a @click="tableCellClick3(row)">{{ row.eqName }}</a>
        </template>
      </el-table-column>
      <el-table-column v-if="isType2" :key="4" label="设备编号" min-width="140px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.eqCode }}</span>
        </template>
      </el-table-column>
      <el-table-column :key="5" label="保养计划数" min-width="100px" align="center" sortable prop="totaluk" />
      <el-table-column :key="6" label="完成数" min-width="100px" align="center" sortable prop="doneuk" />
      <el-table-column :key="7" label="保养完成率" :sortable="true" :sort-method="(a,b) => sortMethod(a ,b , 'donerateuk')" min-width="90px" align="center" prop="donerateuk" />
      <el-table-column :key="8" label="报修数量" min-width="100px" align="center" sortable prop="totalmt" />
      <el-table-column :key="9" label="完成数" min-width="100px" align="center" sortable prop="donemt" />
      <el-table-column label="维修完成率" :sortable="true" :sort-method="(a,b) => sortMethod(a ,b , 'doneratemt')" min-width="90px" align="center" prop="doneratemt" />
    </el-table>
    <pagination v-show="table.total>0" :total="table.total" :page.sync="table.getdataListParm.offset" :limit.sync="table.getdataListParm.pagecount" @pagination="getList" />
  </div>

</template>

<script>
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { GetDataByName, 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: 'CompletionRateMaintenance',
  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,
      isTitle2: false,
      isPasture: true,
      isType: false,
      isType2: false,
      pastureName: '',
      eqName: '',
      eqNameList: [],
      table: {
        tableKey: 0,
        list: [],
        total: 0,
        listLoading: true,
        getdataListParm: {
          name: 'UkdoneRatePasture',
          page: 1,
          offset: 1,
          pagecount: 10,
          returntype: 'Map',
          parammaps: {
            startTime: '',
            stopTime: '',
            inputDatetime: []
          }
        }
      },
      disabled: false,
      placeholder: '请选择设备类别',
      nodeKey: 'id',
      defaultCheckedKeys: [],
      parentClass: [],
      defaultProps: {
        children: 'children',
        label: 'typeName'
      },
      getRecuListParm: {
        name: 'getAssetTypeList',
        idname: 'id',
        params: [-1]
      },
      dataform: {
        eqClassId: '',
        typeCode: ''
      },
      types: [{ id: 0, name: '设备类别1' }, { id: 1, name: '设备类别2' }],
      downLoadParm: {},
      downLoadList: [],
      isPercentage: false,
      percentage: 1
    }
  },

  created() {
    this.getTimeFn()
    this.getDownClassList()
  },

  methods: {
    sortMethod(a, b, c) {
      var str = 0
      var str2 = 0
      str2 = parseFloat(a[c].substring(0, a[c].length - 1))
      str = parseFloat(b[c].substring(0, b[c].length - 1))
      return str2 - str
    },
    tableSort1(column) {
      sortChange(column, this.table.list)
    },
    getTimeFn() {
      const that = this
      const start = new Date()
      const end = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      that.table.getdataListParm.parammaps.inputDatetime[0] = parseTime(start, '{y}-{m}-{d}')
      that.table.getdataListParm.parammaps.inputDatetime[1] = parseTime(end, '{y}-{m}-{d}')
      that.table.getdataListParm.parammaps.startTime = that.table.getdataListParm.parammaps.inputDatetime[0]
      that.table.getdataListParm.parammaps.stopTime = that.table.getdataListParm.parammaps.inputDatetime[1]
      that.getList()
    },
    getList() {
      this.table.listLoading = true
      if (Cookies.get('pastureid') == 18) {
        this.table.getdataListParm.parammaps.pastureId = ''
      } else {
        this.table.getdataListParm.parammaps.pastureId = Cookies.get('pastureid')
      }
      GetDataByName(this.table.getdataListParm).then(response => {
        console.log('table数据', response.data.list)
        this.table.list = response.data.list
        this.table.pageNum = response.data.pageNum
        this.table.pageSize = response.data.pageSize
        this.table.total = response.data.total
        setTimeout(() => {
          this.table.listLoading = false
        }, 100)
      })
    },
    form_search() {
      this.table.listLoading = true
      this.table.getdataListParm.offset = 1
      this.table.getdataListParm.parammaps.startTime = this.table.getdataListParm.parammaps.inputDatetime[0]
      this.table.getdataListParm.parammaps.stopTime = this.table.getdataListParm.parammaps.inputDatetime[1]
      if (this.isPasture == false) {
        this.table.getdataListParm.name = 'UkdoneRateEqclass'
        console.log(this.dataform.eqClassId)
        if (this.dataform.eqClassId == null) {
          this.table.getdataListParm.parammaps.typecode = ''
        } else {
          this.table.getdataListParm.parammaps.typecode = this.dataform.typeCode
        }
      } else {
        this.table.getdataListParm.parammaps.typecode = ''
        this.table.getdataListParm.name = 'UkdoneRatePasture'
      }
      this.getList()
    },
    tableCellStyle({ row, column, rowIndex, columnIndex }) {
      if (row.name !== '现代牧业' && row.typename == null && columnIndex === 1) {
        return {
          textDecoration: 'underline'
        }
      }
      if (this.isType == true || this.isType2 == true) {
        if (row.typename !== null && columnIndex == 1) {
          return {
            textDecoration: 'underline'
          }
        }
      }
      return {
        textDecoration: 'none'
      }
    },
    tableCellClick(row) {
      if (row.name !== '现代牧业') {
        this.table.getdataListParm.name = 'UkdoneRateEqclass'
        this.pastureName = row.name
        this.table.getdataListParm.parammaps.pastureid = row.id
        this.getList()
        this.isPasture = false
        this.isType = true
        this.isType2 = false
        this.isTitle = true
        this.isTitle2 = false
      }
      // else {
      //   this.getList()
      //   this.isTitle = false
      //   this.isTitle2 = false
      //   this.isType2 = false
      // }
    },
    tableCellClick2(row) {
      this.table.getdataListParm.offset = 1
      this.table.getdataListParm.name = 'UkdoneRateEq'
      // this.pastureName = row.name
      this.typename = row.typename
      this.table.getdataListParm.parammaps.startTime = this.table.getdataListParm.parammaps.inputDatetime[0]
      this.table.getdataListParm.parammaps.stopTime = this.table.getdataListParm.parammaps.inputDatetime[1]
      this.table.getdataListParm.parammaps.pastureId = row.pastureId
      this.table.getdataListParm.parammaps.eqClassId = row.id
      this.getList()
      this.isPasture = false
      this.isType = false
      this.isType2 = true
      this.isTitle = false
      this.isTitle2 = true
    },
    tableCellClick3(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: '请联系管理员开通相关牧场数据权限' })
        }
      }
    },
    // goBack() {
    //   this.isPasture = true
    //   this.isType = false
    //   this.isTitle = false
    //   this.table.getdataListParm.name = 'UkdoneRatePasture'
    //   this.table.getdataListParm.parammaps.typecode = ''
    //   this.table.getdataListParm.parammaps.eqClassId = ''
    //   this.dataform.eqClassId = ''
    //   this.dataform.typeCode = ''
    //   this.getList()
    // },
    goFirst() {
      this.table.getdataListParm.offset = 1
      this.table.getdataListParm.name = 'UkdoneRatePasture'
      this.table.getdataListParm.parammaps.typecode = ''
      this.table.getdataListParm.parammaps.eqClassId = ''
      this.dataform.eqClassId = ''
      this.dataform.typeCode = ''
      this.getList()
      this.isType = false
      this.isType2 = false
      this.isTitle = false
      this.isTitle2 = false
      this.isPasture = true
    },
    goSecond() {
      this.isType = true
      this.isType2 = false
      this.isTitle = true
      this.isTitle2 = false
      this.table.getdataListParm.name = 'UkdoneRateEqclass'
      this.table.getdataListParm.parammaps.pastureid = this.table.getdataListParm.parammaps.pastureid
      this.getList()
    },
    getDownClassList() {
      getRecuData(this.getRecuListParm).then(response => {
        this.parentClass = response.data
      })
    },
    popoverHide(checkedIds, checkedData) {
      console.log(checkedIds, checkedData)

      if (checkedData == null) {
        this.dataform.eqClassId = checkedIds
        this.dataform.typeCode = ''
      } else {
        if (checkedData.children !== undefined) {
          this.defaultCheckedKeys = []
          this.$message({ type: 'warning', message: '请选择具体设备类型' })
        } else {
          this.dataform.eqClassId = checkedIds
          this.dataform.typeCode = checkedData.typeCode
        }
      }
      // this.table.getdataListParm.parammaps.typecode = checkedData.typeCode
    },
    handleDownload() {
      if (this.isTitle == true) {
        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.name = 'UkdoneRateEqclass'
        this.downLoadParm.getdataListParm.pagecount = 0
        this.downLoadParm.getdataListParm.parammaps = this.table.getdataListParm.parammaps
        GetDataByName(this.downLoadParm.getdataListParm).then(response => {
          if (response.data.list !== '') {
            this.percentage = 99
            setTimeout(() => {
              this.isPercentage = false
            }, 2000)
          }
          this.$nextTick(() => {
            this.downLoadParm.list = response.data.list
            var excelDatas = [
              {
                tHeader: ['设备分类', '保养计划数', '完成数', '保养完成率', '报修数量', '完成数', '维修完成率'],
                filterVal: ['typename', 'totaluk', 'doneuk', 'donerateuk', 'totalmt', 'donemt', 'doneratemt'],
                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.name = 'UkdoneRatePasture'
        this.downLoadParm.getdataListParm.pagecount = 0
        this.downLoadParm.getdataListParm.parammaps = this.table.getdataListParm.parammaps
        GetDataByName(this.downLoadParm.getdataListParm).then(response => {
          if (response.data.list !== '') {
            this.percentage = 99
            setTimeout(() => {
              this.isPercentage = false
            }, 2000)
          }
          this.$nextTick(() => {
            this.downLoadParm.list = response.data.list
            var excelDatas = [
              {
                tHeader: ['牧场', '保养计划数', '完成数', '保养完成率', '报修数量', '完成数', '维修完成率'],
                filterVal: ['name', 'totaluk', 'doneuk', 'donerateuk', 'totalmt', 'donemt', 'doneratemt'],
                tableDatas: this.downLoadParm.list,
                sheetName: '设备'
              }
            ]
            json2excel(excelDatas, '维修保养完成率报表-牧场', true, 'xlsx')
          })
        })
      }
    }

  }
}
</script>
