<template>
  <div class="app-container">
    <el-form :inline="true" size="small" class="dark-el-input dark-el-button">
      <el-form-item label="场站名称">
        <el-select v-model="stationCode" placeholder="请选择" style="width: 255px" popper-class="cpp-popper">
          <el-option
            v-for="item in stationList"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="使用状态">
        <el-select v-model="overhualStatus" placeholder="请选择" style="width: 255px" popper-class="cpp-popper"
                   clearable>
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="mini" style="margin-left: 5px" icon="el-icon-search"
                   @click="queryByStationCode">查询
        </el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增
        </el-button>
      </el-col>
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="success"-->
      <!--          plain-->
      <!--          icon="el-icon-edit"-->
      <!--          size="mini"-->
      <!--          @click="handleUpdate"-->
      <!--        >修改-->
      <!--        </el-button>-->
      <!--      </el-col>-->
    </el-row>

    <div style="padding-top: 10px">
      <vxe-table
        ref="xTable"
        align="center"
        class="mytable-style"
        auto-resize
        border
        resizable
        export-config
        highlight-current-row
        show-overflow
        max-height="700"
        :data="tableData">
        <vxe-table-column field="stationCode" title="场站名称" :formatter="codeChangeName"></vxe-table-column>
        <vxe-table-column field="name" title="检修名称"></vxe-table-column>
        <vxe-table-column field="description" title="描述"></vxe-table-column>
        <vxe-table-column field="startTime" :formatter="formatDateTime" title="开始时间"></vxe-table-column>
        <vxe-table-column field="endTime" :formatter="formatDateTime" title="结束时间"></vxe-table-column>
        <vxe-table-column field="overhaulCapacity" title="检修容量（MW）"></vxe-table-column>
        <vxe-table-column field="maintenanceQuantity" title="检修台数"></vxe-table-column>
        <vxe-table-column field="status" title="状态" :formatter="statusFormatter"></vxe-table-column>
        <vxe-table-column field="isUse" title="是否使用" :formatter="useFormatter"></vxe-table-column>
        <vxe-table-column field="mcTime" title="手动停止时间" :formatter="formatDateTime"></vxe-table-column>
        <vxe-table-column field="" title="操作">
          <template v-slot="{ row }">
            <el-button
              v-if="row.status === 1"
              style="padding: 3px 4px 3px 4px;margin: 2px; color: red; background-color: whitesmoke;"
              size="mini"
              icon="el-icon-error"
              title="手动停止"
              @click="stopOverhaulPlan(row)">废弃
            </el-button>
          </template>
        </vxe-table-column>
      </vxe-table>
      <vxe-pager
        background
        :loading="loading"
        :current-page.sync="currentPage"
        :page-size.sync="pageSize"
        :total="total"
        @page-change="handlePageChange"
        :layouts="['PrevJump', 'PrevPage', 'JumpNumber', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total']">
      </vxe-pager>
    </div>

    <el-dialog :title="title" :visible.sync="open" :close-on-click-modal="false" width="850px" height="600px">
      <div class="dark-el-input dark-el-button">
        <el-form ref="form" :model="form" :rules="rules" width="830px" label-width="150px">
          <el-row class="mb4">
            <el-col :span="12">
              <el-form-item label="场站名称">
                <el-select v-model="form.stationCode" placeholder="请选择" style="width: 255px"
                           popper-class="cpp-popper">
                  <el-option
                    v-for="item in stationList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="检修名称" prop="name">
                <el-input style="width: 100%" v-model="form.name" maxlength="50"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row class="dark-el-input dark-el-button ">
            <el-col :span="12">
              <el-form-item label="开始时间" prop="startTime">
                <el-date-picker
                  popper-class="cpp-popper"
                  v-model="form.startTime"
                  :clearable="false"
                  type="datetime"
                  value-format="timestamp"
                  placeholder="选择开始日期"
                  style="width: 255px">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="结束时间" prop="startTime">
                <el-date-picker
                  popper-class="cpp-popper"
                  v-model="form.endTime"
                  :clearable="false"
                  type="datetime"
                  value-format="timestamp"
                  placeholder="选择结束日期"
                  style="width: 255px">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row class="mb4">
            <el-col :span="12">
              <el-form-item label="描述" prop="name">
                <el-input style="width: 100%" v-model="form.description" maxlength="50"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="检修容量（MW）" prop="overhaulCapacity">
                <el-input style="width: 100%" v-model="form.overhaulCapacity" maxlength="50"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row class="mb4">
            <el-col :span="12">
              <el-form-item label="检修台数" prop="maintenanceQuantity">
                <el-input style="width: 100%" v-model="form.maintenanceQuantity" maxlength="50"/>
              </el-form-item>
            </el-col>
            <!--            <el-col :span="12">-->
            <!--              <el-form-item label="状态" prop="status">-->
            <!--                <el-input style="width: 100%" v-model="form.status === 1 ? '使用中' : '已废弃'" maxlength="50"-->
            <!--                          :disabled="true"/>-->
            <!--              </el-form-item>-->
            <!--            </el-col>-->
          </el-row>
          <!--          <el-row class="mb4">-->
          <!--            <el-col :span="12">-->
          <!--              <el-form-item label="是否使用" prop="isUse">-->
          <!--                <el-input style="width: 100%" v-model="form.isUse === false ? '否' : '是'" maxlength="50"-->
          <!--                          :disabled="true"/>-->
          <!--              </el-form-item>-->
          <!--            </el-col>-->
          <!--            <el-col :span="12">-->
          <!--              <el-form-item label="手动停止时间">-->
          <!--                <el-input style="width: 100%" v-model="form.mcTime" maxlength="50" :disabled="true"/>-->
          <!--              </el-form-item>-->
          <!--            </el-col>-->
          <!--          </el-row>-->
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="commitChannel">确 定</el-button>
          <el-button @click="cancelChannel">取 消</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>


<script>
import form from "vxe-table/packages/form";

export default {
  name: 'overhaulPlan',
  data() {
    return {
      options: [{
        value: 1,
        label: '使用中'
      }, {
        value: 2,
        label: '已废弃'
      }],
      overhualStatus: null,
      form: {
        stationCode: '',
        name: '',
        startTime: '',
        endTime: '',
        overhaulCapacity: '',
        maintenanceQuantity: '',
        status: 1,
        isUse: false,
        mcTime: '',
      },
      title: "",
      // 是否显示弹出层
      open: false,
      edit: false,
      total: 0,
      sortOrder: 'asc',
      pageSize: 10,
      currentPage: 1,
      stationList: [],
      stationCode: '',
      stationName: undefined,
      searchForm: {},
      tableData: [],
      loading: false,
      modId: '',
      checkSign: '',
      capacity: null,
      // 表单校验
      rules: {
        name: [
          {required: true, message: "检修计划名称不能为空！", trigger: "blur"}
        ],
        description: [
          {required: true, message: "描述不能为空！", trigger: "blur"}
        ],
        maintenanceQuantity: [
          {required: true, message: "检修台数不能为空！", trigger: "blur"},
          {pattern: /^[0-9]*[1-9][0-9]*$/, message: '只能输入正整数数字'}
        ],
        overhaulCapacity: [
          {required: true, message: "检修容量不能为空！", trigger: "blur"},
          {pattern: /^\d+(\.\d{2})?$/, message: '只能输入正数数字或带两位小数的数字'}
        ],
        startTime: [
          {required: true, message: '开始时间不能为空！'}
        ],
      },
    }
  },
  created() {
    this.getStationCode()
  },
  mounted() {

  },
  computed: {},
  methods: {
    // 表单重置
    reset() {
      this.edit = false;
      this.form = {
        stationCode: '',
        name: '',
        startTime: '',
        endTime: '',
        overhaulCapacity: '',
        maintenanceQuantity: '',
        status: 1,
        isUse: false,
        mcTime: '',
      },
        this.resetForm("form");
    },
    // 取消按钮
    cancelChannel() {
      this.open = false;
      this.reset();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增检修计划";
      this.edit = false;
    },
    /** 修改按钮操作 */
    handleUpdate() {
      this.title = "修改检修计划";
      this.reset();
      const _selectData = this.$refs.xTable.getRadioRecord(true)
      if (_selectData == null) {
        this.$message({
          type: 'warning',
          message: '请选择记录!'
        });
        return
      }
      this.open = true;
      this.edit = true;
      this.form = JSON.parse(JSON.stringify(_selectData))
    },
    // 提交按钮
    async commitChannel() {
      var checkData=[]
      const param = {
        "stationCode": this.form.stationCode
      }
      await this.$axios.get('/electricfield/findCapacityByStationCode', {params: param}).then(response => {
        this.capacity = response.data.capacity
      })
      await this.$axios.get('overhaulplan/stationCode/noPage', {params: param}).then(response => {
        checkData = response.data
      })
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.startTime > this.form.endTime) {
            this.$message.warning('开始时间不能大于结束时间！')
            return
          }
          if (this.form.startTime == null || this.form.endTime == null) {
            this.$message.warning('开始时间或者结束时间不能为空！')
            return
          }
          if (Number(this.form.overhaulCapacity) > this.capacity) {
            this.$message.warning('检修容量不能超过装机容量！')
            return
          }
          var timeStartEnd = [this.form.startTime, this.form.endTime]
          if (this.checkDate(timeStartEnd, checkData, this.edit, this.form)) {
            this.$message.warning('该时间段内已有检修计划！')
            return
          }
          // if (this.form.id != undefined) {
          //   // 更新操作
          //   this.$axios.post('/overhaulplan/updateById', this.form).then((res) => {
          //     this.$message.success('修改成功')
          //     this.open = false;
          //     this.overhualStatus = null
          //     this.queryByStationCode()
          //   }).catch((error) => {
          //   })
          // } else {
            // 新增操作
            this.$axios.post('/overhaulplan/save', this.form).then((res) => {
              if (res == undefined) {
                this.$message.success('新增失败')
              } else {
                this.$message.success('新增成功')
                this.overhualStatus = null
                this.queryByStationCode()
                this.open = false;
              }
            }).catch((error) => {
            })
          }
        // }
      });
    },
    // /** 删除按钮操作 */
    // handleDelete() {
    //   const _selectData = this.$refs.xTable.getRadioRecord(true)
    //   if (_selectData == null) {
    //     this.$message({
    //       type: 'warning',
    //       message: '请选择记录!'
    //     });
    //     return
    //   }
    //
    //   this.$confirm('是否确认删除?', '提示', {
    //     confirmButtonText: '确定',
    //     cancelButtonText: '取消',
    //     type: 'warning'
    //   }).then(() => {
    //     this.doDelete(_selectData)
    //   }).catch(() => {
    //   });
    // },
    /**
     * 删除提交
     */
    // doDelete(row) {
    //   this.$axios.post('/overhaulplan/remove', row).then((res) => {
    //     this.$message.success('删除成功！')
    //     this.dataQuery()
    //   }).catch((error) => {
    //   })
    //   this.loading = false
    // },
    handlePageChange({currentPage, pageSize}) {
      this.currentPage = currentPage
      this.pageSize = pageSize
      this.queryByStationCode();
    },
    // dataQuery() {
    //   this.loading = true
    //   const param = {
    //     "currentPage": this.currentPage,
    //     "pageSize": this.pageSize,
    //   }
    //   this.$axios.get('/overhaulplan/getList', {params: param}).then(response => {
    //     this.tableData = response.data.records
    //     this.total = response.data.total
    //     this.loading = false
    //   }).catch(() => {
    //     this.loading = false
    //   })
    // },

    //日期转换器
    formatDateTime(cellValue) {
      if (cellValue.cellValue == null) {
        return ''
      }
      const date = new Date(cellValue.cellValue)
      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
    },
    // 状态转换
    statusFormatter(cellValue) {
      return cellValue.cellValue === 1 ? '使用中' : '已废弃'
    },
    useFormatter(cellValue) {
      return cellValue.cellValue === 0 ? '否' : '是'
    },
    getStationCode() {
      this.$axios({url: '/electricfield/all', method: 'get'}).then(response => {
        this.stationList = response.data
        if (this.stationList.length > 0) {
          this.stationCode = this.stationList[0].value
          this.queryByStationCode()
        } else {
          this.queryByStationCode()
        }
      })
    },
    queryByStationCode() {
      this.loading = true
      const param = {
        "currentPage": this.currentPage,
        "pageSize": this.pageSize,
        "stationCode": this.stationCode,
        "status": this.overhualStatus
      }
      this.$axios.get('/overhaulplan/stationCode', {params: param}).then(response => {
        this.tableData = response.data.records
        this.total = response.data.total
        this.loading = false
      })
    },
    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] >= new Date(v2[i].startTime).getTime() && v1[0] <= new Date(v2[i].endTime).getTime()) {
            result = true
            break
          }
          if (v1[1] >= new Date(v2[i].startTime).getTime() && v1[1] <= new Date(v2[i].endTime).getTime()) {
            result = true
            break
          }
          if (v1[0] <= new Date(v2[i].startTime).getTime() && v1[1] >= new Date(v2[i].endTime).getTime()) {
            result = true
            break
          }
          if (v1[0] >= new Date(v2[i].startTime).getTime() && v1[1] <= new Date(v2[i].endTime).getTime()) {
            result = true
            break
          }
        }
      }
      return result
    },
    stopOverhaulPlan(row) {
      this.$axios.post("/overhaulplan/updateStatus", row).then(response => {
        this.$message.success('检修计划停用成功！')
        this.queryByStationCode();
      })
    },
    codeChangeName(row) {
      var codeList = this.stationList
      for (let i = 0; i < codeList.length; i++) {
        console.log("a" + row.cellValue)
        console.log("b" + codeList[i].value)
        if (row.cellValue == codeList[i].value) {
          return codeList[i].label
        }
      }
    }
  }
}
</script>
