<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-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
              type="text"
              size="mini"
              icon="el-icon-chat-dot-round"
              title="使用详情"
              @click="showRecords(row)">使用详情
            </el-button>
          </template>
        </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"
              size="mini"
              icon="el-icon-error"
              title="手动停止"
              type="text"
              @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>

    <el-dialog :title="title" :visible.sync="showDetails" :close-on-click-modal="false" width="1000px" height="600px">
      <div class="dark-el-input dark-el-button">
        <vxe-table
          ref="xTable"
          align="center"
          class="mytable-style"
          auto-resize
          border
          resizable
          export-config
          highlight-current-row
          show-overflow
          max-height="700"
          :data="tableDataDetails.slice((currentPage-1)*pageSize,currentPage*pageSize)">
          <vxe-table-column field="stationCode" title="场站名称" :formatter="codeChangeName"></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="forecastModel" title="预测模型"></vxe-table-column>
          <vxe-table-column field="useNum" title="使用次数"></vxe-table-column>
          <vxe-table-column field="updateTime" :formatter="formatDateTime" title="上一次使用时间"></vxe-table-column>
        </vxe-table>
        <vxe-pager
          background
          :loading="loading"
          :current-page.sync="currentPage"
          :page-size.sync="pageSize"
          :total="totalDetails"
          @page-change="handlePageChangeDetails"
          :layouts="['PrevJump', 'PrevPage', 'JumpNumber', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total']">
        </vxe-pager>
      </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,
      showDetails: false,
      total: 0,
      totalDetails: 0,
      pageSize: 10,
      currentPage: 1,
      stationList: [],
      stationCode: '',
      stationName: undefined,
      tableData: [],
      tableDataDetails: [],
      loading: false,
      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.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 = "新增检修计划";
    },
    // 提交按钮
    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.form)) {
            this.$message.warning('该时间段内已有检修计划！')
            return
          }
          // 新增操作
          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) => {
          })
        }
      });
    },
    handlePageChange({currentPage, pageSize}) {
      this.currentPage = currentPage
      this.pageSize = pageSize
      this.queryByStationCode();
    },
    handlePageChangeDetails({currentPage, pageSize}) {
      this.currentPage = currentPage
      if (this.pageSize != pageSize) {
        this.changePageSize(pageSize)
      }
      this.pageSize = pageSize
    },
    //日期转换器
    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, 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])
      }

      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++) {
        if (row.cellValue == codeList[i].value) {
          return codeList[i].label
        }
      }
    },
    showRecords(row) {
      this.showDetails = true
      this.title = '使用记录详情'
      this.loading = true
      const param = {
        "stationCode": this.stationCode,
        "startTime": Date.parse(row.startTime),
        "endTime": Date.parse(row.endTime)
      }
      this.$axios.get('/overhaulPlanRecords/findByStationCodeAndTimeBetween', {params: param}).then(response => {
        this.tableDataDetails = response.data
        this.totalDetails  = response.data.length()
        this.loading = false
      })
    }
  }
}
</script>
