<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>检修计划</span>
<!--        <el-button style="float: right;padding:3px 10px 3px 3px;" type="text" @click="qrShow">二维码扫描上传-->
<!--        </el-button>-->
        <el-button style="float: right;padding:3px 10px 3px 3px;" type="text" @click="exportDataEvent">导出数据
        </el-button>
      </div>
      <el-button type="primary" size="small" @click="insertEvent" style="round-clip: 10px"
                 :loading="btnLonding">新增
      </el-button>
      <div>
        <el-dialog
          :close-on-click-modal="false"
          :visible.sync="dialogVisible"
          title="请扫描以下二维码"
          style="padding: 0px;"
          label-width="1px"
          width="500px">
          <!--            <el-image-->
          <!--              src="http://www.baidu.com"-->
          <!--              fit="fill"-->
          <!--            />-->
          <div id="qrCode" ref="qrCodeDiv" name="qrCodeDiv" align="center"></div>

          <span
            slot="footer"
            class="dialog-footer">
            <el-button
              size="mini"
              @click="cancel">关 闭</el-button>
          </span>
        </el-dialog>
      </div>
      <div style="padding-top: 10px">
        <vxe-table
          highlight-hover-row
          :keep-source="true"
          align="center"
          :loading="loading"
          v-loading="false"
          ref="xTable"
          auto-resize
          highlight-current-row
          border
          resizable
          show-overflow
          :edit-rules="rules"
          :data="tableData"
          v-show="showTable"
          :edit-config="{trigger: 'manual', mode: 'row',autoClear: false,icon:'none'}"
        >
          <vxe-table-column title="检修计划信息">
            <vxe-table-column field="name" title="检修名称"
                              :edit-render="{name:'$input',attrs:{type:'text'}}"></vxe-table-column>
            <vxe-table-column field="describe" title="描述"
                              :edit-render="{name:'$input',attrs:{type:'text'}}"></vxe-table-column>
            <vxe-table-column width="14%" field="startTime" title="开始时间"
                              :edit-render="{name:'$input',attrs:{type:'text'}}">
              <template v-slot:edit="{ row }">
                <el-date-picker
                  style="width: 100%"
                  v-model="row.startTime"
                  type="datetime"
                  value-format="timestamp"
                  placeholder="选择开始时间"
                  :readonly=startTimeShow
                  :picker-options="pickerOptions1"/>
              </template>
              <template v-slot="{ row }">{{ timestampToTime(row.startTime) }}
              </template>
            </vxe-table-column>
            <vxe-table-column width="14%" field="endTime" title="结束时间"
                              :edit-render="{name:'$input',attrs:{type:'text'}}">
              <template v-slot:edit="{ row }">
                <el-date-picker
                  style="width: 100%"
                  v-model="row.endTime"
                  type="datetime"
                  value-format="timestamp"
                  placeholder="选择结束时间"
                  :picker-options="pickerOptions1"/>
              </template>
              <template v-slot="{ row }">{{
                  timestampToTime(row.endTime)
                }}
              </template>
            </vxe-table-column>
            <!--            <vxe-table-column width="15%" field="finalEntryTime" title="生效时间"-->
            <!--                              :edit-render="{}">-->
            <!--              <template v-slot="{ row }">{{ timestampToTime(row.finalEntryTime) }}</template>-->
            <!--            </vxe-table-column>-->
            <vxe-table-column field="overhaulCapactity" title="检修容量(Mw)"
                              :edit-render="{name:'$input',attrs:{type:'text'}}"></vxe-table-column>
            <vxe-table-column field="status" title="计划状态">
              <template v-slot="{ row }">{{ row.status == 2 ? '已停止' : '执行中' }}</template>
            </vxe-table-column>
            <vxe-table-column width="10%" field="createTime" title="创建时间">
              <template v-slot="{ row }">{{ timestampToTime1(row.createTime) }}</template>
            </vxe-table-column>
            <vxe-table-column width="10%" field="lastModifyTime" title="最后修改时间">
              <template v-slot="{ row }">{{ timestampToTime1(row.lastModifyTime) }}</template>
            </vxe-table-column>
            <vxe-table-column width="10%" field="mcTime" title="手动停止时间">
              <template v-slot="{ row }">{{ timestampToTime1(row.mcTime) }}</template>
            </vxe-table-column>
            <vxe-table-column fixed="right" width="150" title="操作">
              <template v-slot="{ row }">
                <template v-if="$refs.xTable.isActiveByRow(row)">
                  <el-button
                    style="padding: 3px 4px 3px 4px;margin: 2px"
                    size="mini"
                    icon="el-icon-edit"
                    :loading="saveLoding"
                    @click="saveCheck(row)">保存
                  </el-button>
                  <el-button
                    style="padding: 3px 4px 3px 4px;margin: 2px"
                    size="mini"
                    icon="el-icon-edit"
                    @click="cancelRowEvent(row)">取消
                  </el-button>
                </template>
                <template v-else>
                  <el-button
                    v-show="row.status==1"
                    style="padding: 3px 4px 3px 4px;margin: 2px"
                    size="mini"
                    icon="el-icon-edit"
                    @click="editRowEvent(row)"
                    :loading="btnLonding">编辑
                  </el-button>
                  <el-button
                    v-show="row.status==1&&row.finalEntryTime>now"
                    type="danger"
                    style="padding: 3px 4px 3px 4px;margin: 2px"
                    size="mini"
                    icon="el-icon-delete"
                    @click="removeEvent(row)"
                    :loading=btnLonding>删除
                  </el-button>
                  <el-button
                    v-show="row.finalEntryTime<now&&row.id!=undefined&&row.status==1"
                    type="success"
                    style="padding: 3px 4px 3px 4px;margin: 2px"
                    size="mini"
                    icon="el-icon-check"
                    :loading="saveLoding"
                    title="手动停止"
                    @click="fulSaveRowEvent(row)">停止
                  </el-button>
                </template>
              </template>
            </vxe-table-column>
          </vxe-table-column>
        </vxe-table>
        <vxe-pager
          perfect
          :current-page.sync="currentPage"
          :page-size.sync="pageSize"
          :total="total"
          :page-sizes=[10,50,100]
          :layouts="['PrevJump', 'PrevPage','JumpNumber', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total']"
          @page-change="handlePageChange"
          v-show="showTable"
        ><!--v-show="!btnLonding"-->
        </vxe-pager>
      </div>


    </el-card>
  </div>
</template>
<script>
import request from '@/utils/request'
import QRCode from 'qrcodejs2';
export default {
  data() {
    return {
      now: new Date().getTime(),
      checkSign: '',
      checkTableDate: [],
      holidayType: '',
      loading: false,
      dialogVisible: false,
      generateOverHaulPlanCodeContentData:'',
      saveLoding: false,
      showTable: true,
      btnLonding: false,
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      elCapacity: 0,
      startTimeShow:false,
      //表单验证规则
      rules: {
        name: [
          {required: true, message: ' 检修名称不能为空'},
          {min: 1, max: 9, message: '称长度在 1 到 9 个字符'}
        ],
        describe: [
          {required: true, message: '请填写检修计划描述，原因等'},
          {min: 1, max: 9, message: '名称长度在 1 到 9 个字符'}
        ],
        startTime: [
          {required: true, message: '开始时间不能为空'}
        ],
        overhaulCapactity: [
          { required: true, message: '不能为空' },
          { pattern: /^\d+(\.\d{2})?$/, message: '只能输入正数数字或带两位小数的数字' }
          // {message: '输入过长', max: 50}

        ]
      },
      //当前日期之前日期不可选
      pickerOptions1: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7;
          // return time.getTime() <= Date.now();
        }
      }
    }
  },
  created() {
    this.getEl()
  },
  methods: {
    getEl() {
      this.$axios.get("/electricField/").then(response => {
        this.elCapacity = response.data.backupF
        this.getAll()
      })
    },
    getAll() {
      this.now = (new Date()).getTime()
      this.loading = true
      this.saveLoding = false
      this.$axios.get("/overHaulPlanOne/" + this.currentPage + '/' + this.pageSize).then(response => {
        if (response.data.content == "") {
          this.showTable = false

        } else {
          this.showTable = true
        }
        this.tableData = response.data.content
        this.total = response.data.count

        if (response.data.totalElements != 0) {

          this.total = response.data.totalElements
        }
        this.loading = false

      })
      this.generateOverHaulPlanCodeContent()
    },
    //编辑框改变
    editRowEvent(row) {
      this.startTimeShow = false
      if(row.startTime < new Date().getTime()){
        this.startTimeShow = true
      }
      this.checkSign = true
      this.btnLonding = true
      this.$refs.xTable.setActiveRow(row)
    },
    checkDate(v1, v2, v3, v4) {
      let result = false
      const item = ''
      // 修改时所需便利集合
      const v5 = []
      // 所有假期存放集合

      // 在修改时，把当前在所有信息集合里要修改的信息去掉（如果不去掉会影响校验）
      for (let i = 0; i < v2.length; i++) {
        if (v2[i].id == v4.id||v2[i].status == 2) {
          continue
        }
        v5.push(v2[i])
      }
      // 编辑修改
      if (v3) {
        // 假期修改
        for (let i = 0; i < v5.length; i++) {
          if (v1[0] >= v5[i].startTime && v1[0] <= v5[i].endTime) {
            result = true
            break
          }
          if (v1[1] >= v5[i].startTime && v1[1] <= v5[i].endTime) {
            result = true
            break
          }
          if (v1[0] <= v5[i].startTime && v1[1] >= v5[i].endTime) {
            result = true
            break
          }
          if (v1[0] >= v5[i].startTime && v1[1] <= v5[i].endTime) {
            result = true
            break
          }
        }
      } else {
        for (let i = 0; i < v2.length; i++) {
          if (v1[0] >= v2[i].startTime && v1[0] <= v2[i].endTime) {
            result = true
            break
          }
          if (v1[1] >= v2[i].startTime && v1[1] <= v2[i].endTime) {
            result = true
            break
          }
          if (v1[0] <= v2[i].startTime && v1[1] >= v2[i].endTime) {
            result = true
            break
          }
          if (v1[0] >= v2[i].startTime && v1[1] <= v2[i].endTime) {
            result = true
            break
          }
        }
      }
      return result
    },
    //数据校验
    saveCheck(row) {

      this.$refs.xTable.validate(row, callback => {
        if(row.startTime<new Date().getTime()&&!this.startTimeShow){
          this.$XModal.message({status: 'error', message: '开始时间不能小于当前时间！'})
        }else if(row.overhaulCapactity>this.elCapacity){
          this.$XModal.message({status: 'error', message: '检修容量不能大于装机容量！'})
        } else if (row.startTime == null || row.endTime == null) {
          // callback(new Error('开始结束日期不能为空'))
          this.$XModal.message({status: 'error', message: '开始结束日期不能为空！'})
        } else {
          var timeStartEnd = [row.startTime,row.endTime]
          if (this.checkDate(timeStartEnd, this.tableData, this.checkSign, row)) {
            this.$XModal.message({status: 'error', message: '该时间段已有检修计划！'})
          } else {
            callback:this.saveRowEvent(row)
          }
        }
      })
    },
    //保存数据操作
    saveRowEvent(row) {
      this.saveLoding = true
      this.$refs.xTable.validate(valid => {
        if (valid) {
          if (row.id == undefined) {
            row.status = '1'
            this.$axios.post("/overHaulPlanOne/", row).then(response => {
              this.getAll()
              this.$XModal.message({status: 'warning', message: response.message})
              this.saveLoding = false
            })
          } else {
            this.$axios.put("/overHaulPlanOne/", row).then(response => {
              this.getAll()
              this.$XModal.message({status: 'warning', message: response.message})
              this.saveLoding = false

            })
          }
          this.btnLonding = false
        } else {
          this.$XModal.message({status: 'error', message: '校验不通过！'})
          this.saveLoding = false
        }

      })
    },
    //停止数据操作
    fulSaveRowEvent(row) {
      this.$XModal.confirm('您点击了手动停止，是否确认停止?').then(type => {
        this.saveLoding = true
        this.$refs.xTable.validate(valid => {
          if (valid) {
            row.status = '2'
            this.$axios.put("/overHaulPlanOne/", row).then(response => {
              this.getAll()
              this.$XModal.message({status: 'warning', message: response.message})
              this.saveLoding = false
            })
          } else {
            this.$XModal.message({status: 'error', message: '校验不通过！'})
            this.saveLoding = false
          }
          this.btnLonding = false
        })
      })
    },
    //取消编辑或添加操作
    cancelRowEvent(row) {
      this.saveLoding = false
      this.btnLonding = false
      const xTable = this.$refs.xTable
      if (row.id == undefined) {
        this.$refs.xTable.remove(row)
      } else {
        xTable.clearActived().then(() => {
          // 还原行数据
          xTable.revertData(row)
        })
      }
    },
    //删除数据
    removeEvent(row) {
      this.$XModal.confirm('您确定要删除该数据?').then(type => {
        if (type === 'confirm') {
          this.$axios.delete("/overHaulPlanOne/", {data: row}).then(response => {
            this.$XModal.message({status: 'warning', message: response.message})
            this.getAll()
          })
        }
      })
    },
    //时间戳日期转换器
    timestampToTime(time) {
      const date = new Date(time) // 时间戳为10位需*1000，时间戳为13位的话不需乘1000
      const Y = date.getFullYear() + '-'
      const M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
      const D = date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate()
      const h = " " + (date.getHours() < 10 ? '0' : '') + date.getHours() + ':'
      const m = (date.getMinutes() < 10 ? '0' : '') + date.getMinutes() + ':'
      const s = (date.getSeconds() < 10 ? '0' : '') + date.getSeconds()
      return Y + M + D + h + m + s
    },
    timestampToTime1(time) {
      if (time == undefined) {
        return '空'
      }
      const date = new Date(time) // 时间戳为10位需*1000，时间戳为13位的话不需乘1000
      const Y = date.getFullYear() + '-'
      const M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
      const D = date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate()
      const h = " " + (date.getHours() < 10 ? '0' : '') + date.getHours() + ':'
      const m = (date.getMinutes() < 10 ? '0' : '') + date.getMinutes() + ':'
      const s = (date.getSeconds() < 10 ? '0' : '') + date.getSeconds()
      return Y + M + D + h + m + s
    },
    //新增编辑框
    insertEvent() {
      this.startTimeShow = false
      this.showTable = true
      this.btnLonding = true
      this.checkSign = false
      this.timeStartEnd = []
      this.$refs.xTable.insert()
        .then(({row}) => this.$refs.xTable.setActiveRow(row))
    },
    //分页出发事件
    handlePageChange({currentPage, pageSize}) {
      this.currentPage = currentPage
      this.pageSize = pageSize
      this.getAll()
    },
    /*handleSizeChange(size) {
        this.pageSize = size
        this.getAll()
    },
    handleCurrentChange(currentPage) {
        this.currentPage = currentPage
        this.getAll()
    },*/
    //导出
    qrShow(){
      this.dialogVisible = true
      this.$nextTick(() => {
        var divs = document.getElementsByName('qrCodeDiv')
        for(var j = 0;j<divs.length;j++){
          divs[j].innerHTML = ""
        }
        new QRCode(this.$refs.qrCodeDiv, {
          text: this.generateOverHaulPlanCodeContentData[0],
          width: 300,
          height: 300,
          colorDark: "#333333", //二维码颜色
          colorLight: "#ffffff", //二维码背景色
          correctLevel: QRCode.CorrectLevel.L//容错率，L/M/H
        })
      })

    },
    generateOverHaulPlanCodeContent(){
      this.$axios.get("/overHaulPlanOne/generateOverHaulPlanCodeContent").then(response => {
        console.log(response.data)
        this.generateOverHaulPlanCodeContentData =  response.data
      })

    },
    cancel(){

      this.dialogVisible = false
    },
    exportDataEvent() {
      this.loading = true
      this.$axios.get('/overHaulPlanOne/').then(res => {
        const data = res.data

        for(let i = 0;i<data.length;i++){
          data[i].startTime = this.timestampToTime1(data[i].startTime)
          data[i].endTime = this.timestampToTime1(data[i].endTime)
          data[i].finalEntryTime = this.timestampToTime1(data[i].finalEntryTime)
          data[i].createTime = this.timestampToTime1(data[i].createTime)
          data[i].mcTime = this.timestampToTime1(data[i].mcTime)
        }

        this.$refs.xTable.exportData({
          filename: '检修计划信息',
          type: 'csv',
          isHeader: true,
          isFooter: true,
          data
        })
        this.loading = false
      }).catch(e => {
      })
    },
    //导入
    importDataEvent() {
      this.$refs.xTable.importData({types: ['csv']})
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  /*left: 0;*/
  /*width: 100%;*/
  /*min-height: 100%;*/
  /*height: auto;*/
  /*background-image: linear-gradient(25deg, #05362d, #145d44, #24875d, #35b477)*/

}

.pagination {
  margin: 20px 0;
  text-align: right;
}
</style>
