<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select v-model="getdataListParm.parammaps.pastureName" placeholder="牧场" class="filter-item" style="width: 120px;" @change="changePastureName">
        <el-option v-for="item in findAllPasture" :key="item.id" :label="item.name" :value="item.name" />
      </el-select>
      <el-date-picker class="filter-item" v-model="getdataListParm.month" type="month" placeholder="选择日期" format="yyyy-MM" value-format="yyyy-MM" :clearable="false" @blur="blurMonth" />
      <el-input v-model="getdataListParm.parammaps.eqName" placeholder="设备名称" style="width: 200px;" class="filter-item" />
      <el-input v-model="getdataListParm.parammaps.eqCode" placeholder="设备内部编号" style="width: 140px;" class="filter-item" />
      <tree-select
        class="typeSelect"
        :height="150"
        :width="250"
        size="small"
        clearable
        :data="parentType"
        :disabled="disabled"
        :placeholder="placeholder"
        style="display:inline-block;"
        :default-props="defaultProps"
        :node-key="nodeKey"
        :checked-keys="defaultCheckedKeys"
        @popoverHide="popoverHide"
      />
      <el-select v-model="getdataListParm.parammaps.departmentId" clearable placeholder="部门" class="filter-item" style="width: 120px;">
        <el-option v-for="item in findAllDepart" :key="item.id" :label="item.name" :value="item.id" />
      </el-select>
      <el-select v-model="getdataListParm.parammaps.statue" placeholder="设备状态" class="filter-item" style="width: 120px;">
        <el-option v-for="item in equipmentStatusList" :key="item.id" :label="item.name" :value="item.id" />
      </el-select>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="form_search">搜索</el-button>
    </div>
    <div class="month" style="height: 50px;">
      <el-button v-if="isMaintenancePlanCopy" type="primary" icon="el-icon-copy-document" @click="handleCopy">复制</el-button>
      <el-button v-if="isMaintenancePlanClear" type="danger" icon="el-icon-delete" @click="handleDelate">清空</el-button>
      <el-button class="filter-item" type="success" icon="el-icon-download"  @click="handleDownload">导出</el-button>
      <el-upload style="display: inline-block;" :headers="headers" :data="uploadData" :action="uploadExcelUrl" :show-file-list="false" :before-upload="beforeImportExcel" :on-success="handleImportExcelSuccess">
        <el-button v-if="isMaintenancePlanUpload" v-waves class="filter-item" type="warning" icon="el-icon-download">导入</el-button>
      </el-upload>
      <el-button v-waves class="filter-item" type="info" icon="el-icon-download" @click="handleDownloadTemp">模板</el-button>
    </div>
    <el-table
      slot="reference"
      border
      :data="list"
      header-align="center"
      :row-style="rowStyle"
      :cell-style="tableCellClassName"
      @cell-click="handleCellClick"
      :max-height="myHeight"
    >
      <template v-for="(item,index) in tablelist">
        <el-table-column :key="index" show-overflow-tooltip :prop="item.column_name" :label="item.label" :width="item.width" />
      </template>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="getdataListParm.offset" :limit.sync="getdataListParm.pagecount" @pagination="get_table_data" />
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false" width="50%">
      <div class="content-add">
        <el-form
          ref="createTemp"
          :rules="rules"
          :model="createTemp"
          label-position="right"
          label-width="95px"
          style="width:90%;margin:0 auto"
        >
          <el-row>
            <el-col :span="20">
              <el-form-item label="保养名称:" prop="upkeepTemplateId">
                <el-select v-model="createTemp.upkeepTemplateId" filterable placeholder="请选择" @change="changeUpkeep">
                  <el-option
                    v-for="item in upkeepTemps"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="20">
              <el-form-item label="保养人:" prop="upkeepEmpId">
                <el-select v-model="createTemp.upkeepEmpId" filterable placeholder="请选择">
                  <el-option
                    v-for="item in findAllEmploye"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer" style="bottom:10px">
          <el-button type="primary" :disabled="isokDisable" @click="dialogStatus==='create'?add_dialog_save():edit_dialog_save()">保存并关闭</el-button>
          <el-button @click="dialogFormVisible = false;">关闭</el-button>
        </div>
      </div>
    </el-dialog>
    <!-- 修改计划/删除计划/提前保养 -->
    <el-dialog :title="textMap[dialogStatusBtn]" :visible.sync="dialogFormVisibleBtn" :close-on-click-modal="false" width="450px;" style="width:45%;margin:0 auto">
      <div class="content-btn">
        <el-button class="filter-item" type="primary" @click="handleRevisionPlan">修改计划</el-button>
        <el-button class="filter-item" type="danger" @click="handleDeletionPlan">删除计划</el-button>
        <el-button class="filter-item" type="warning" @click="handleAdvanceMaintenance">提前保养</el-button>
      </div>
    </el-dialog>
    <!-- 复制 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisibleCopy" :close-on-click-modal="false" width="50%" style="width:90%;margin:0 auto">
      <div class="app-copy">
        <el-form ref="copyTemp" :rules="rules" :model="copyTemp" label-position="right" label-width="110px" style="width: 90%; margin: 0 auto;">
          <el-row>
            <el-col :span="12" label="月份：">
              <el-form-item>
                <el-select v-model="month" placeholder="月份" multiple style="width:100%">
                  <el-option v-for="item in months" :key="item.id" :label="item.name" :value="item.name" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer" style="right:30px;position:absolute;bottom:30px">
          <el-button type="primary" @click="dialogStatus==='copy'?createCopyData():createCopyData()">确认</el-button>
          <el-button @click="dialogFormVisibleCopy = false">关闭</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 引入
import { GetDataByName, GetDataByNames, transData, GetUpkeepPlan, PostDataByName, failproccess, ExecDataByConfig, checkButtons,GetAccount } from '@/api/common'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination'
import { parseTime, json2excel } from '@/utils/index.js'
import { MessageBox } from 'element-ui'
import TreeSelect from '@/components/TreeSelect'
import Cookies from 'js-cookie'
import { getToken } from '@/utils/auth'
export default {
  name: 'MaintenancePlan',
  components: { Pagination, TreeSelect },
  directives: { waves },
  data() {
    return {
      // ----------------------------------------------------
      myHeight:document.documentElement.clientHeight - 85- 250,
      equipmentStatusList: [{ id: 1, name: '正常设备' }, { id: 2, name: '非正常设备' }, { id: '', name: '全部' }],
      visible: false,
      findAllPasture: [],
      findAllDepart: [],
      requestParams: [
        { name: 'findAllPasture', offset: 0, pagecount: 0, returntype: 'Map', parammaps: { 'id': Cookies.get('pastureid') }},
        { name: 'findAllEmploye', offset: 0, pagecount: 0, parammaps: { 'pastureId': Cookies.get('pastureid') }}
      ],
      getDepartParam: {
        name: 'findAllDepart', offset: 0, pagecount: 0, parammaps: { 'pastureId': Cookies.get('pastureid') }
      },
      disabled: false,
      parentType: [],
      placeholder: '设备类别',
      getParmType: {
        name: 'geteqclasslist'
      },
      defaultProps: {
        children: 'children',
        label: 'typeName'
      },
      nodeKey: 'id',
      defaultCheckedKeys: [],
      dataform: {
        id: '',
        name: '',
        selectType: [],
        sort: '',
        enable: '',
        typeCode: ''
      },
      UpdateDataRelationParam: {
        name: '',
        dataname: '',
        datavalue: '',
        valuename: '',
        values: ''
      },
      rowStyle: { maxHeight: 30 + 'px', height: 25 + 'px' },
      total: 0,
      tableKey: 0,
      listLoading: true,
      list: [],
      listTest: {},
      updateValue: {},
      tablelist: [],
      getdataListParm: {
        name: 'geteqList',
        page: 1,
        offset: 1,
        pagecount: 10,
        returntype: 'Map',
        parammaps: {
          pastureName: Cookies.get('pasturename'),
          eqCode: '',
          eqName: '',
          typeCode: '',
          partName: '',
          statue: 1
        },
        month: parseTime(new Date(), '{y}-{m}')
      },
      getdataListParmSH: {
        name: 'geteqList',
        page: 0,
        offset: 0,
        pagecount: 0,
        returntype: 'Map',
        parammaps: {
          pastureName: Cookies.get('pasturename'),
          eqCode: '',
          eqName: '',
          typeCode: '',
          partName: '',
          statue: 1
        },
        month: parseTime(new Date(), '{y}-{m}')
      },
      dialogStatus: '',
      dialogFormVisible: false,
      dialogStatusBtn: '',
      dialogFormVisibleBtn: false,
      isokDisable: false,
      rules: {
        upkeepTemplateId: [{ required: true, message: '必填', trigger: 'blur' }],
        upkeepEmpId: [{ required: true, message: '必填', trigger: 'blur' }]
      },
      textMap: {
        create: '添加保养计划',
        update: '修改保养计划',
        copy: '复制'
      },
      listAdd: [],
      createTemp: {
        upkeepTemplateId: '',
        upkeepEmpId: ''
      },
      postDataPramas: {},
      requestParam: {},
      getParmUpemplateByeq: {
        name: 'getUpemplateByeq',
        parammaps: {}
      },
      getParmUpdatePlan: {
        name: 'getseviceplanbyid',
        parammaps: {}
      },
      upkeepTemps: [],
      findAllEmploye: [],
      dialogFormVisibleCopy: false,
      months: [],
      copyTemp: {},
      month: [],
      downLoadParm: {},
      downLoadList: [],
      buttons: [],
      isMaintenancePlanCopy: [], isMaintenancePlanUpload: [], isMaintenancePlanClear: [], isMaintenancePlanAdd: [], isMaintenancePlanUpdate: []
    }
  },
  computed: {
    // 设置请求头
    headers() {
      return {
        // 设置token
        // eslint-disable-next-line no-undef
        token: getToken()
      }
    },
    uploadData() {
      return {
        name: 'uploadSevicplan',
        importParams: '月份,部门名称,编码,资产名称,牧场,保养人,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31',
        sheetname: 'SheetJS'
      }
    },
    // 设置上传地址
    uploadExcelUrl() {
      // process.env.VUE_APP_BASE_API是服务器的路径，也是axios的基本路径
      return process.env.VUE_APP_BASE_API + 'authdata/ImportExcel'
    }
  },
  created() {
    if (this.$route.query.myPath !== undefined && this.$route.query.myPath == 'CompletionRateMaintenance') {
      if (this.$route.query.pastureName !== undefined && this.$route.query.eqCode !== undefined) {
        this.getdataListParm.parammaps.pastureName = this.$route.query.pastureName
        this.getdataListParm.parammaps.eqCode = this.$route.query.eqCode
        this.$forceUpdate()
      } else {
        this.getdataListParm.parammaps.pastureName = Cookies.get('pasturename')
        this.getdataListParm.parammaps.eqCode = ''
      }
      this.get_table_data()
    } else {
      if (this.$route.query.pastureName !== undefined && this.$route.query.eqCode !== undefined) {
        this.getdataListParm.parammaps.pastureName = this.$route.query.pastureName
        this.getdataListParm.parammaps.eqCode = this.$route.query.eqCode
      } else {
        this.getdataListParm.parammaps.pastureName = Cookies.get('pasturename')
        this.getdataListParm.parammaps.eqCode = ''
      }
      this.get_table_data()
    }
    this.getTypeList()
    this.get_select_list()
    this.getMonths()
    const that = this
    GetDataByName({ 'name': 'getUserPCButtons', 'parammaps': { 'jwt_username': Cookies.get('name') }}).then(response => {
      that.buttons = response.data.list
      that.get_auto_buttons()
    })
    // 新增
  },
  methods: {
    get_auto_buttons() {
      // 复制
      const MaintenancePlanCopy = 'maintenance:maintenancePlan:copy'
      const isMaintenancePlanCopy = checkButtons(this.$store.state.user.buttons, MaintenancePlanCopy)
      this.isMaintenancePlanCopy = isMaintenancePlanCopy
      // 导入
      const MaintenancePlanUpload = 'maintenance:maintenancePlan:upload'
      const isMaintenancePlanUpload = checkButtons(this.$store.state.user.buttons, MaintenancePlanUpload)
      this.isMaintenancePlanUpload = isMaintenancePlanUpload
      // 清空
      const MaintenancePlanClear = 'maintenance:maintenancePlan:clear'
      const isMaintenancePlanClear = checkButtons(this.$store.state.user.buttons, MaintenancePlanClear)
      this.isMaintenancePlanClear = isMaintenancePlanClear
      // 新增
      const MaintenancePlanAdd = 'maintenance:maintenancePlan:add'
      const isMaintenancePlanAdd = checkButtons(this.$store.state.user.buttons, MaintenancePlanAdd)
      this.isMaintenancePlanAdd = isMaintenancePlanAdd
      // 编辑
      const MaintenancePlanUpdate = 'maintenance:maintenancePlan:update'
      const isMaintenancePlanUpdate = checkButtons(this.$store.state.user.buttons, MaintenancePlanUpdate)
      this.isMaintenancePlanUpdate = isMaintenancePlanUpdate
    },
    popoverHide(checkedIds, checkedData) {
      console.log('选中值', checkedIds, checkedData)
      if (checkedData == null) {
        this.dataform.eqClassId = checkedIds
        this.dataform.typeCode = ''
      } else {
        this.dataform.eqClassId = checkedIds
        this.dataform.typeCode = checkedData.typeCode
      }
    },
    getTypeList() {
      GetDataByName(this.getParmType).then(response => {
        if (response.data.list !== null) {
          this.parentType = transData(response.data.list, 'id', 'pid', 'children')
        }
      })
    },
    get_select_list() {
      GetDataByNames(this.requestParams).then(response => {
        this.findAllPasture = response.data.findAllPasture.list
        this.findAllEmploye = response.data.findAllEmploye.list
        this.getDepartDownList()
      })
    },
    getDepartDownList() {
      GetDataByName(this.getDepartParam).then(response => {
        this.findAllDepart = response.data.list
      })
    },
    changePastureName(item) {
      this.getDepartParam.parammaps.pastureId = this.findAllPasture.find(obj => obj.name == item).id
      this.getdataListParm.parammaps.departmentId = ''
      this.getDepartDownList()
    },
    get_table_data() {
      this.listLoading = true
      // this.getdataListParm.month = parseTime(new Date(), '{y}-{m}') // 更改为请求的月份
      // this.getdataListParm.month = '2020-03' // 更改为请求的月份
      GetUpkeepPlan(this.getdataListParm).then(response => {
        console.log('table数据', response.data.list)
        this.list = response.data.list
        this.pageNum = response.data.pageNum
        this.pageSize = response.data.pageSize
        if (response.data.total) {
          this.total = response.data.total
        }
        var temp = this.getdataListParm.month.split('-')
        var year = temp[0]
        var month = temp[1]
        var d = new Date(year, month, 0)
        var table = [{ 'label': '序号', 'column_name': 'i' }, { 'label': '牧场', 'column_name': 'pastureName' }, { 'label': '部门', 'column_name': 'deptName' }, { 'label': '设备名称', 'column_name': 'eqName' }, { 'label': '设备内部编号', 'column_name': 'eqCode' }, { 'label': '品牌', 'column_name': 'brand' }]
        for (let index = 1; index <= d.getDate(); index++) {
          // eslint-disable-next-line no-undef
          index = JSON.stringify(index)
          var m = { 'label': index, 'column_name': 'm' + index, 'width': '40' }
          table.push(m)
        }
        var operation = { 'label': '操作', 'column_name': 'operation', 'width': '100' }
        table.push(operation)
        this.tablelist = table
        for (var i = 0; i < this.list.length; i++) {
          this.list[i].i = i + 1
          if (this.isMaintenancePlanClear !== false) {
            this.list[i].operation = <el-button type='danger' size='mini' style='width:60px;' ref='clear' id='clear' class-name='small-padding fixed-width' fixed='right'>清空</el-button>
          }
          // this.list[i].operation = '操作'
          for (const key in this.list[i]) {
            // console.log(key + '---' + this.list[i][key])
            // this.list[i][key] = (this.list[i][key]).split('#')[0]
            var reg = /^(?![^a-zA-Z]+$)(?!\D+$)/
            // console.log(reg.test(key))
            // console.log((this.list[i][key]))
            if (reg.test(key)) {
              // console.log(reg.test(key))
              var a = JSON.stringify(i)
              if (this.list[i][key] !== undefined) {
                if ((this.list[i][key]).split('#')[0] == undefined) {
                  this.listTest[key + a] = this.list[i][key]
                  this.list[i][key] = ''
                } else {
                  this.listTest[key + a] = this.list[i][key]
                  this.list[i][key] = (this.list[i][key]).split('#')[0]
                }
              }
            }
          }
        }
        console.log('table数据', this.list)
        console.log('表头数据', this.tablelist)
        this.$forceUpdate()
        setTimeout(() => {
          this.listLoading = false
        }, 100)
      })
    },
    blurMonth() {
      this.listLoading = true
      if (this.dataform.eqClassId == null) {
        this.getdataListParm.parammaps.typeCode = ''
      } else {
        this.getdataListParm.parammaps.typeCode = this.dataform.typeCode
      }
      this.get_table_data()
    },
    form_search() {
      this.listLoading = true
      if (this.dataform.eqClassId == null) {
        this.getdataListParm.parammaps.typeCode = ''
      } else {
        this.getdataListParm.parammaps.typeCode = this.dataform.typeCode
      }
      this.getdataListParm.offset = 1
      this.get_table_data()
    },
    tableCellClassName({ row, column, rowIndex, columnIndex }) {
      row.index = rowIndex
      column.index = columnIndex
      var rowStr = JSON.stringify(rowIndex)

      // console.log(this.listTest)


      console.log(row, column, rowIndex, columnIndex )
      var test = this.listTest[this.tablelist[column.index].column_name + rowStr]

      if (test !== undefined) {
        if (test.split('#')[2] !== undefined) {
          var colorTest = test.split('#')[2] // 0,1,2
          var colorTest2 = test.split('#')[4] // 0,1,2

          if(rowIndex == 1){

            if(this.tablelist[column.index].column_name == 'm31'){
              console.log('test',test)
             console.log('rowIndex',rowIndex,'colorTest',  colorTest )
             console.log('rowIndex',rowIndex,'colorTest2',  colorTest2 )
            }

          }


          let cellStyle
          if (parseFloat(colorTest2) !== 0) {
            cellStyle = 'background: #E6A23C;color:#fff;width:48px'
          } else {
            switch (colorTest) {
              case '0':
                cellStyle = 'background: #4169E1;color:#fff;width:48px'
                break
              case '1':
                cellStyle = 'background: #00FF00;color:#fff'
                break
              case '2':
                cellStyle = 'background: red;color:#fff'
                break
              default:
                cellStyle = 'background: #4169E1;color:#fff'
            }
          }
          if (columnIndex >= 6 && row[this.tablelist[column.index].column_name] == test.split('#')[0]) {
            return cellStyle
          }
        } else {
          const cellStyle = 'background: #4169E1;color:#fff'
          if (columnIndex >= 6 && row[this.tablelist[column.index].column_name] == test.split('#')[0]) {
            return cellStyle
          }
        }
      }
    },
    resetCreateTemp() {
      this.createTemp.upkeepTemplateId = ''
      this.listAdd = []
    },
    handleCellClick(row, column, rowIndex, columnIndex) {
      // console.log(this.getdataListParm.month)
      // console.log(parseTime(new Date(), '{y}-{m}-{d}'))
      var day
      if (this.tablelist[column.index].label < 10) {
        day = '0' + this.tablelist[column.index].label
      } else {
        day = this.tablelist[column.index].label
      }
      if (this.getdataListParm.month + '-' + day > parseTime(new Date(), '{y}-{m}-{d}')) {
        this.getParmUpemplateByeq.parammaps.assetCode = row.assetCode
        this.getUpemplateByeq()
        // console.log('row', row)
        // console.log('table数据', this.list)
        // console.log('行索引', rowIndex)
        // console.log('lie索引', columnIndex)
        // console.log('引', column.index)
        if (column.index > 5) {
          // console.log('row--行', row)
          // console.log('--列索引', column.index)
          // console.log('--行索引', row.index)
          console.log('--表头', this.tablelist[column.index])
          console.log('row[this.tablelist[column.index].column_name]', row[this.tablelist[column.index].column_name])
          // console.log('row[this.tablelist[column.index].column_name].elm', row[this.tablelist[column.index].column_name].elm)
          if (column.index >= 6 && row[this.tablelist[column.index].column_name] !== undefined) {
            console.log(row[this.tablelist[column.index].column_name].elm)
            if (row[this.tablelist[column.index].column_name].elm == undefined) {
              // console.log(row[this.tablelist[column.index].column_name])
              // console.log(row[this.tablelist[column.index].column_name])
              var rowStr = JSON.stringify(row.index)
              // console.log(this.tablelist[column.index].column_name + rowStr)
              // 要分割值
              this.updateValue = this.listTest[this.tablelist[column.index].column_name + rowStr]
              console.log('要分割值', this.updateValue)
              console.log('--年月', this.getdataListParm.month)
              console.log(this.updateValue.split('#')[4])
              if (this.updateValue.split('#')[4] == 0) {
                console.log(this.isMaintenancePlanAdd, this.isMaintenancePlanUpdate)
                if (this.isMaintenancePlanUpdate == true) {
                  this.dialogFormVisibleBtn = true
                }
              }
              this.createTemp.pastureId = row.pastureId
              this.createTemp.deptId = row.deptId
              this.createTemp.eqName = row.eqName
              this.createTemp.eqCode = row.eqCode
              this.createTemp.eqId = row.id
              this.createTemp.eqClassId = row.eqClassId
              this.createTemp.bigupkeeptemplateId = row.upkeepTemplateId
              this.createTemp.month = this.getdataListParm.month
              this.createTemp.upkeepType = row.upkeepType
              this.createTemp.upkeepCycel = row.upkeepCycel
              this.createTemp.upkeepName = row.upkeepName
              this.createTemp.id = this.updateValue.split('#')[1]
              this.createTemp.upkeepEmpId = row.upkeepEmpId
              this.createTemp.day = this.tablelist[column.index].label
              console.log('---------------------', row)
            } else {
              MessageBox.confirm('是否清空本设备本月保养计划？', {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                this.requestParam.name = 'ClearoneSevicplan'
                this.requestParam.parammaps = {}
                this.requestParam.parammaps.id = row.id
                this.requestParam.parammaps.monthIN = this.getdataListParm.month
                PostDataByName(this.requestParam).then(() => {
                  this.get_table_data()
                  this.dialogFormVisible = false
                  this.$notify({ title: '成功', message: '清空成功', type: 'success', duration: 2000 })
                })
              }).catch(() => {
                this.$message({ type: 'info', message: '已取消清空' })
              })
            }
          } else {
            console.log('--年月', this.getdataListParm.month)
            console.log('--日', this.tablelist[column.index].label)
            this.resetCreateTemp()
            this.createTemp.pastureId = row.pastureId
            this.createTemp.deptId = row.deptId
            this.createTemp.eqName = row.eqName
            this.createTemp.eqCode = row.eqCode
            this.createTemp.eqId = row.id
            this.createTemp.eqClassId = row.eqClassId
            this.createTemp.month = this.getdataListParm.month
            this.createTemp.day = this.tablelist[column.index].label
            this.dialogStatus = 'create'
            console.log(this.isMaintenancePlanAdd, this.isMaintenancePlanUpdate)
            if (this.isMaintenancePlanAdd == true) {
              this.dialogFormVisible = true
            }
          }
        }
      } else {
        console.log('点击后期跳转', row, column, rowIndex, columnIndex)
        var str = 'm' + column.label
        console.log(str, 'str')
        console.log(row.str, 'row.str')
        console.log(row['m' + column.label], '====')
        if (row['m' + column.label] !== undefined && row['m' + column.label] !== '') {
          var time = this.getdataListParm.month + '-' + day
          if (Cookies.get('pasturename') == '现代牧业') {
            this.$router.push({ path: '/maintenance/maintain', query: { myPath: 'MaintenancePlan', eqCode: row.eqCode, time: time }})
          } else {
            if (row.pastureName == Cookies.get('pasturename')) {
              this.$router.push({ path: '/maintenance/maintain', query: { myPath: 'MaintenancePlan', eqCode: row.eqCode, time: time }})
            } else {
              this.$message({ type: 'error', message: '请联系管理员开通相关牧场数据权限' })
            }
          }
        }
      }
    },
    getUpemplateByeq() {
      GetDataByName(this.getParmUpemplateByeq).then(response => {
        if (response.data.list !== null) {
          this.upkeepTemps = response.data.list
          for (var i = 0; i < this.upkeepTemps.length; i++) {
            this.upkeepTemps[i].name = this.upkeepTemps[i].upkeepName + '|' + this.upkeepTemps[i].upkeepType + '|' + this.upkeepTemps[i].upkeepLevel
          }
        }
      })
    },
    changeUpkeep(item) {
      console.log('保养名称', item)
      console.log(this.upkeepTemps.find(obj => obj.id === item))
      this.createTemp.upkeepTemplateId = item
      this.createTemp.upkeepType = this.upkeepTemps.find(obj => obj.id === item).upkeepType
      this.createTemp.upkeepCycel = this.upkeepTemps.find(obj => obj.id === item).upkeepCycel
      this.createTemp.upkeepName = this.upkeepTemps.find(obj => obj.id === item).upkeepName
    },
    add_dialog_save() {
      this.isokDisable = true
      setTimeout(() => {
        this.isokDisable = false
      }, 1000)
      for (var i = parseInt(this.createTemp.day); i < this.tablelist.length - 5; i += this.createTemp.upkeepCycel) {
        // this.listAdd.push()
        var listObj = {}
        listObj.pastureId = this.createTemp.pastureId
        listObj.deptId = this.createTemp.deptId
        listObj.eqName = this.createTemp.eqName
        listObj.eqCode = this.createTemp.eqCode
        listObj.eqId = this.createTemp.eqId
        listObj.eqClassId = this.createTemp.eqClassId
        listObj.upkeepPerson = this.createTemp.upkeepEmpId
        listObj.bigupkeeptemplateId = this.createTemp.upkeepTemplateId
        var b = i
        if (b < 10) {
          listObj.plantime = this.createTemp.month + '-' + '0' + b
        } else {
          listObj.plantime = this.createTemp.month + '-' + b
        }
        this.listAdd.push(listObj)
      }
      console.log('this.listAdd', this.listAdd)
      this.$refs['createTemp'].validate(valid => {
        this.postDataPramas.common = { 'returnmap': '0' }
        this.postDataPramas.data = []
        this.postDataPramas.data[0] = { 'name': 'insertseviceplan', 'type': 'e', 'parammaps': {
          pastureId: this.createTemp.pastureId,
          deptId: this.createTemp.deptId,
          eqName: this.createTemp.eqName,
          eqCode: this.createTemp.eqCode,
          eqId: this.createTemp.eqId,
          eqClassId: this.createTemp.eqClassId,
          upkeepTemplateId: this.createTemp.upkeepTemplateId,
          upkeepType: this.createTemp.upkeepType,
          upkeepCycel: this.createTemp.upkeepCycel,
          upkeepName: this.createTemp.upkeepName,
          month: this.createTemp.month,
          day: this.createTemp.day,
          upkeepEmpId: this.createTemp.upkeepEmpId
        }}
        // eslint-disable-next-line no-irregular-whitespace
        this.postDataPramas.data[1] = { 'name': 'insertSpotList', 'resultmaps': { 'list': this.listAdd }}
        this.postDataPramas.data[1].children = []
        this.postDataPramas.data[1].children[0] = { 'name': 'insertBigupKeep', 'type': 'e', 'parammaps': {
          seviceplanId: '@insertseviceplan.LastInsertId',
          pastureId: '@insertSpotList.pastureId',
          deptId: '@insertSpotList.deptId',
          eqName: '@insertSpotList.eqName',
          eqCode: '@insertSpotList.eqCode',
          eqId: '@insertSpotList.eqId',
          eqClassId: '@insertSpotList.eqClassId',
          bigupkeeptemplateId: '@insertSpotList.bigupkeeptemplateId',
          plantime: '@insertSpotList.plantime',
          upkeepPerson: '@insertSpotList.upkeepPerson'
        }}
        ExecDataByConfig(this.postDataPramas).then(response => {
          console.log('新增保存发送参数', this.postDataPramas)
          if (response.msg === 'fail') {
            this.$notify({
              title: '保存失败',
              message: response.data,
              type: 'warning',
              duration: 2000
            })
          } else {
            this.dialogFormVisible = false
            this.getdataListParm.parammaps.inputDatetime = ''
            this.get_table_data()
            this.$notify({
              title: '',
              message: '保存成功',
              type: 'success',
              duration: 2000
            })
          }
        })
      })
    },
    handleRevisionPlan() {
      console.log('点击了修改计划', this.updateValue)
      console.log('年月', this.getdataListParm.month)
      this.dialogFormVisibleBtn = false
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.getUpdatePlan()
    },
    getUpdatePlan() {
      this.getParmUpdatePlan.parammaps.id = (this.updateValue).split('#')[1]
      GetDataByName(this.getParmUpdatePlan).then(response => {
        if (response.data.list !== null) {
          console.log(response.data.list[0])
          this.createTemp.id = response.data.list[0].id
          this.createTemp.upkeepCycel = response.data.list[0].upkeepCycel
          this.createTemp.upkeepEmpId = response.data.list[0].upkeepEmpId
          this.createTemp.upkeepName = response.data.list[0].upkeepName
          this.createTemp.upkeepTemplateId = response.data.list[0].upkeepTemplateId
          this.createTemp.upkeepType = response.data.list[0].upkeepType
        }
      })
    },
    edit_dialog_save() {
      this.isokDisable = true
      setTimeout(() => {
        this.isokDisable = false
      }, 1000)
      // for (var i = parseInt(this.createTemp.upkeepCycel); i < this.tablelist.length - 5; i += this.createTemp.upkeepCycel) {
      //   // this.listAdd.push()
      //   var listObj = {}
      //   listObj.pastureId = this.createTemp.pastureId
      //   listObj.deptId = this.createTemp.deptId
      //   listObj.eqName = this.createTemp.eqName
      //   listObj.eqCode = this.createTemp.eqCode
      //   listObj.eqId = this.createTemp.eqId
      //   listObj.eqClassId = this.createTemp.eqClassId
      //   listObj.upkeepPerson = this.createTemp.upkeepEmpId
      //   listObj.bigupkeeptemplateId = this.createTemp.upkeepTemplateId
      //   var b = i
      //   if (b < 10) {
      //     listObj.plantime = this.createTemp.month + '-' + '0' + b
      //   } else {
      //     listObj.plantime = this.createTemp.month + '-' + b
      //   }
      //   this.listAdd.push(listObj)
      // }
      console.log('this.listAdd', this.listAdd)
      this.$refs['createTemp'].validate(valid => {
        this.postDataPramas.common = { 'returnmap': '0' }
        this.postDataPramas.data = []
        this.postDataPramas.data[0] = { 'name': 'updateseviceplanId', 'type': 'e', 'parammaps': {
          id: (this.updateValue).split('#')[3]
        }}
        this.postDataPramas.data[1] = { 'name': 'insertseviceplan', 'type': 'e', 'parammaps': {
          pastureId: this.createTemp.pastureId,
          deptId: this.createTemp.deptId,
          eqName: this.createTemp.eqName,
          eqCode: this.createTemp.eqCode,
          eqId: this.createTemp.eqId,
          eqClassId: this.createTemp.eqClassId,
          upkeepTemplateId: this.createTemp.upkeepTemplateId,
          upkeepType: this.createTemp.upkeepType,
          upkeepCycel: this.createTemp.upkeepCycel,
          upkeepName: this.createTemp.upkeepName,
          month: this.createTemp.month,
          day: this.createTemp.day,
          upkeepEmpId: this.createTemp.upkeepEmpId
        }}
        this.postDataPramas.data[2] = { 'name': 'updateBigUpkeep', 'type': 'e', 'parammaps': {
          id: (this.updateValue).split('#')[3],
          bigupkeeptemplateId: this.createTemp.upkeepTemplateId,
          seviceplanId:	'@insertseviceplan.LastInsertId',
          upkeepPerson:	this.createTemp.upkeepEmpId
        }}
        ExecDataByConfig(this.postDataPramas).then(response => {
          console.log('新增保存发送参数', this.postDataPramas)
          if (response.msg === 'fail') {
            this.$notify({
              title: '保存失败',
              message: response.data,
              type: 'warning',
              duration: 2000
            })
          } else {
            this.dialogFormVisible = false
            this.getdataListParm.parammaps.inputDatetime = ''
            this.get_table_data()
            this.$notify({
              title: '',
              message: '保存成功',
              type: 'success',
              duration: 2000
            })
          }
        })
      })
    },
    handleDeletionPlan() {
      console.log('点击了删除计划')
      this.dialogFormVisibleBtn = false
      MessageBox.confirm('是否删除本天保养计划？', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.requestParam.name = 'deleteBigUpkeep'
        this.requestParam.parammaps = {}
        console.log('要分割值', this.updateValue)
        this.requestParam.parammaps.id = (this.updateValue).split('#')[3]
        PostDataByName(this.requestParam).then(() => {
          this.get_table_data()
          this.dialogFormVisible = false
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 提前保养
    handleAdvanceMaintenance() {
      console.log('点击了提前保养', this.updateValue)
      MessageBox.confirm('是否确认提前一天保养本设备？', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.isokDisable = true
        setTimeout(() => {
          this.isokDisable = false
        }, 1000)
        this.postDataPramas.common = { 'returnmap': '0' }
        this.postDataPramas.data = []
        this.postDataPramas.data[0] = { 'name': 'advanceBigupkeep', 'type': 'e', 'parammaps': {
          id: this.updateValue.split('#')[3]
        }}
        this.postDataPramas.data[1] = { 'name': 'updateadvanceupkeep', 'type': 'e', 'parammaps': {
          id: this.updateValue.split('#')[3],
          advanceId: '@advanceBigupkeep.LastInsertId'
        }}
        this.postDataPramas.data[2] = { 'name': 'advanceBupUt', 'type': 'e', 'parammaps': {
          bigupkeeptemplateId: this.updateValue.split('#')[1],
          id: '@advanceBigupkeep.LastInsertId'
        }}
        ExecDataByConfig(this.postDataPramas).then(response => {
          console.log('提前保养发送参数', this.postDataPramas)
          if (response.msg === 'fail') {
            // key 'pastureId'
            var pmonth = new RegExp("key 'pastureId'")
            if (pmonth.test(response.data)) {
              this.$notify({
                title: '',
                message: '前一天已有保养计划，不可重复添加',
                type: 'warning',
                duration: 2000
              })
            } else {
              this.$notify({
                title: '保存失败',
                message: '参数错误',
                type: 'warning',
                duration: 2000
              })
            }
          } else {
            this.dialogFormVisibleBtn = false
            this.getdataListParm.parammaps.inputDatetime = ''
            this.get_table_data()
            this.$notify({
              title: '',
              message: '保存成功',
              type: 'success',
              duration: 2000
            })
          }
        })
      })
    },
    getMonths() {
      var data = new Date()
      data.setMonth(data.getMonth(), 1) // 获取到当前月份,设置月份
      for (var i = 0; i < 12; i++) {
        data.setMonth(data.getMonth() + 1) // 每次循环一次 月份值减1
        var m = data.getMonth() + 1
        m = m < 10 ? '0' + m : m
        var monthObj = {}
        monthObj.id = i
        monthObj.name = data.getFullYear() + '-' + m

        this.months.push(monthObj)
      }
      console.log(this.months, '---------------')
    },
    handleCopy() {
      this.dialogStatus = 'copy'
      this.dialogFormVisibleCopy = true
    },
    createCopyData() {
      console.log(this.month)
      if (this.month.length === 0) {
        this.$message({
          message: '请选择设备',
          type: 'warning',
          duration: 2000
        })
      } else {
        var selectMonth = []
        for (var i = 0; i < this.month.length; i++) {
          var checkedIdsObj = {}
          checkedIdsObj['NewmonthIN'] = this.month[i]
          selectMonth.push(checkedIdsObj)
        }
        console.log('处理选中值', selectMonth)
        this.dialogStatusCopy = 'copy'
        this.dialogFormVisibleCopy = true
        this.postDataPramas.common = { 'returnmap': '0' }
        this.postDataPramas.data = []
        this.postDataPramas.data[0] = { 'name': 'insertSpotList', 'resultmaps': { 'list': selectMonth }}
        this.postDataPramas.data[0].children = []
        this.postDataPramas.data[0].children[0] = { 'name': 'CopySevicplan', 'type': 'e', 'parammaps': {
          pastureName: this.getdataListParm.parammaps.pastureName,
          eqName: this.getdataListParm.parammaps.eqName,
          eqCode: this.getdataListParm.parammaps.eqCode,
          typeCode: this.getdataListParm.parammaps.typeCode,
          departmentId: this.getdataListParm.parammaps.departmentId,
          monthIN: this.getdataListParm.month,
          NewmonthIN: '@insertSpotList.NewmonthIN'
        }}
        ExecDataByConfig(this.postDataPramas).then(response => {
          console.log('复制保存发送参数', this.postDataPramas)
          if (response.msg !== 'fail') {
            this.dialogFormVisibleCopy = false
            this.$notify({
              title: '成功',
              message: '复制成功',
              type: 'success',
              duration: 2000
            })
          } else {
            failproccess(response, this.$notify)
          }
        })
      }
    },
    handleDelate() {
      MessageBox.confirm('是否清空本月保养计划？', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.requestParam.name = 'ClearSevicplan'
        this.requestParam.parammaps = {}
        this.requestParam.parammaps.pastureName = this.getdataListParm.parammaps.pastureName
        this.requestParam.parammaps.eqName = this.getdataListParm.parammaps.eqName
        this.requestParam.parammaps.eqCode = this.getdataListParm.parammaps.eqCode
        this.requestParam.parammaps.typeCode = this.getdataListParm.parammaps.typeCode
        this.requestParam.parammaps.departmentId = this.getdataListParm.parammaps.departmentId
        this.requestParam.parammaps.monthIN = this.getdataListParm.month
        PostDataByName(this.requestParam).then(() => {
          this.get_table_data()
          this.dialogFormVisible = false
          this.$notify({
            title: '成功',
            message: '清空成功',
            type: 'success',
            duration: 2000
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消清空'
        })
      })
    },
    beforeImportExcel(file) {
      const isLt2M = file.size / 1024 / 1024 < 10
      if (!isLt2M) {
        this.$message.error('上传文件大小不能超过 10MB!')
      }
      return isLt2M
    },
    handleImportExcelSuccess(res, file) {
      if (res.msg === 'ok') {
        this.$message({
          title: '成功',
          message: '导入成功:' + res.data.success + '条!',
          type: 'success',
          duration: 2000
        })
        if (res.data.err_count > 0) {
          this.$notify({
            title: '失败',
            message: '导入失败:' + res.data.err_count + '条!',
            type: 'danger',
            duration: 2000
          })
           import('@/vendor/Export2Excel').then(excel => {
             const list1 = res.data.result
             const tHeader = [
               '月份', '部门名称', '编码', '资产名称', '牧场', '保养人', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', 'error_msg'
             ]
             const filterVal = [
               '月份', '部门名称', '编码', '资产名称', '牧场', '保养人', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', 'error_msg'
             ]
             const data1 = this.formatJson(filterVal, list1)
             excel.export_json_to_excel({
               header: tHeader,
               data: data1,
               filename: '保养计划',
               autoWidth: true,
               bookType: 'xlsx'
             })
           })
        }
      } else {
        this.$notify({
          title: '失败',
          message: '上传失败',
          type: 'danger',
          duration: 2000
        })
      }
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v =>
        filterVal.map(j => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        })
      )
    },
    handleDownloadTemp() {
      this.downLoadParm = {}
      this.downLoadParm.name = 'getUpkeepeqlist'
      this.downLoadParm.month = this.getdataListParm.month
      this.downLoadParm.parammaps = this.getdataListParm.parammaps
      GetDataByName(this.downLoadParm).then(response => {
        if (response.data.list !== null) {
          this.downloadList = response.data.list
        } else {
          this.downloadList = []
        }
        var temp = this.downLoadParm.month.split('-')
        var year = temp[0]
        var month = temp[1]
        var d = new Date(year, month, 0)
        var tHeader = ['月份', '部门名称', '编码', '资产名称', '牧场', '保养人']
        for (let index = 1; index <= d.getDate(); index++) {
          // eslint-disable-next-line no-undef
          index = JSON.stringify(index)
          var m = { 'label': index, 'column_name': 'm' + index, 'width': '40' }
          // table.push(m)
          tHeader.push(index)
        }
        console.log(tHeader, '====')

        // return
        const elecExcelDatas = [
          {
            tHeader: tHeader,
            filterVal: ['i', 'name', 'deptName', 'eqName', 'eqCode', 'brandname'],
            // tableDatas: this.downloadList,
            tableDatas: [],
            sheetName: 'SheetJS'
          }
        ]
        json2excel(elecExcelDatas, '保养计划模板', true, 'xlsx')
      })
    },

    handleDownload() {
      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.getdataListParmSH.month = this.getdataListParm.month
      this.getdataListParmSH.parammaps = this.getdataListParm.parammaps
      GetUpkeepPlan(this.getdataListParmSH).then(response => {
        this.downLoadList = response.data.list
        if (response.data.list !== '') {
          this.percentage = 99
          setTimeout(() => {
            this.isPercentage = false
          }, 2000)
        }
        console.log('ssssss',this.downLoadList)

        var temp = this.getdataListParmSH.month.split('-')
        var year = temp[0]
        var month = temp[1]
        var d = new Date(year, month, 0)
        var tHeader = ['月份', '部门名称', '编码', '资产名称', '牧场', '保养人','1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31']
        this.downLoadList.forEach(row => {
          row.m1 = (typeof row.m1 ===  'undefined') ? '' : row.m1.substr(0,1)
          row.m2 = (typeof row.m2 ===  'undefined') ? '' : row.m2.substr(0,1)
          row.m3 = (typeof row.m3 ===  'undefined') ? '' : row.m3.substr(0,1)
          row.m4 = (typeof row.m4 ===  'undefined') ? '' : row.m4.substr(0,1)
          row.m5 = (typeof row.m5 ===  'undefined') ? '' : row.m5.substr(0,1)
          row.m6 = (typeof row.m6 ===  'undefined') ? '' : row.m6.substr(0,1)
          row.m7 = (typeof row.m7 ===  'undefined') ? '' : row.m7.substr(0,1)
          row.m8 = (typeof row.m8 ===  'undefined') ? '' : row.m8.substr(0,1)
          row.m9 = (typeof row.m9 ===  'undefined') ? '' : row.m9.substr(0,1)
          row.m10 = (typeof row.m10 ===  'undefined') ? '' : row.m10.substr(0,1)
          row.m11 = (typeof row.m11 ===  'undefined') ? '' : row.m11.substr(0,1)
          row.m12 = (typeof row.m12 ===  'undefined') ? '' : row.m12.substr(0,1)
          row.m13 = (typeof row.m13 ===  'undefined') ? '' : row.m13.substr(0,1)
          row.m14 = (typeof row.m14 ===  'undefined') ? '' : row.m14.substr(0,1)
          row.m15 = (typeof row.m15 ===  'undefined') ? '' : row.m15.substr(0,1)
          row.m16 = (typeof row.m16 ===  'undefined') ? '' : row.m16.substr(0,1)
          row.m17 = (typeof row.m17 ===  'undefined') ? '' : row.m17.substr(0,1)
          row.m18 = (typeof row.m18 ===  'undefined') ? '' : row.m18.substr(0,1)
          row.m19 = (typeof row.m19 ===  'undefined') ? '' : row.m19.substr(0,1)
          row.m20 = (typeof row.m20 ===  'undefined') ? '' : row.m20.substr(0,1)
          row.m21 = (typeof row.m21 ===  'undefined') ? '' : row.m21.substr(0,1)
          row.m22 = (typeof row.m22 ===  'undefined') ? '' : row.m22.substr(0,1)
          row.m23 = (typeof row.m23 ===  'undefined') ? '' : row.m23.substr(0,1)
          row.m24 = (typeof row.m24 ===  'undefined') ? '' : row.m24.substr(0,1)
          row.m25 = (typeof row.m25 ===  'undefined') ? '' : row.m25.substr(0,1)
          row.m26 = (typeof row.m26 ===  'undefined') ? '' : row.m26.substr(0,1)
          row.m27 = (typeof row.m27 ===  'undefined') ? '' : row.m27.substr(0,1)
          row.m28 = (typeof row.m28 ===  'undefined') ? '' : row.m28.substr(0,1)
          row.m29 = (typeof row.m29 ===  'undefined') ? '' : row.m29.substr(0,1)
          row.m30 = (typeof row.m30 ===  'undefined') ? '' : row.m30.substr(0,1)
          row.m31 = (typeof row.m31 ===  'undefined') ? '' : row.m31.substr(0,1)
        });
        const elecExcelDatas = [
          {
            tHeader: tHeader,
            filterVal: ['month','deptName','eqCode','eqName','pastureName','employeName','m1','m2','m3','m4','m5','m6','m7','m8','m9','m10','m11','m12','m13','m14','m15','m16','m17','m18','m19','m20','m21','m22','m23','m24','m25','m26','m27','m28','m29','m30','m31'],
            tableDatas: this.downLoadList,
            sheetName: 'SheetJS'
          }
        ]
        json2excel(elecExcelDatas, '保养计划', true, 'xlsx')
      })
    },

  }
}
</script>
<style lang="scss">
.el-input--small .el-input__inner{
  height: 38px !important;
}
</style>
