<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div>
        <el-input v-model="searchParam.nameLike" clearable size="small" placeholder="班次名称" style="width: 200px;" class="filter-item" />
        <el-select v-model="searchParam.hasEnable" clearable size="small" placeholder="停用/启用" style="width: 200px;" class="filter-item">
          <el-option :key="1" label="停用" :value="false" />
          <el-option :key="2" label="启用" :value="true" />
        </el-select>
        <el-button class="filter-item" size="mini" type="success" icon="el-icon-search" @click="searchSubmit">搜索</el-button>
        <el-button class="filter-item" size="mini" type="warning" icon="el-icon-refresh-left" @click="searchParamReset">重置</el-button>
      </div>
      <el-button class="filter-item" size="mini" type="primary" icon="el-icon-plus" @click="doAdd()">新增</el-button>
    </div>
    <!--弹出框1-->
    <el-dialog append-to-body :close-on-click-modal="true" :visible.sync="dialog1Show" :title="editState==1?'新增':editState==2?'修改':'查看'" width="480px">
      <el-alert v-show="editState==2" title="注意：修改班次会连带修改已经排班的信息！" description="如果此排班信息已经正常使用过，建议设置为停用并创建新的。" type="warning" effect="dark" style="margin-bottom: 30px;" />
      <el-form ref="dialog1Form" :hide-required-asterisk="!dialog1Editing" :model="dialog1Data" :rules="dialog1Rules" size="mini" label-width="180px" style="margin-right: 80px;">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="班次名称：" prop="name">
              <span v-show="!dialog1Editing">{{ dialog1Data.name }}</span>
              <el-input v-show="dialog1Editing" v-model="dialog1Data.name" maxlength="100" show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="开始时间：" prop="beginTime">
              <span v-show="!dialog1Editing">{{ dialog1Data.beginTime }}</span>
              <el-time-picker v-show="dialog1Editing" v-model="dialog1Data.beginTime" value-format="HH:mm:ss" style="width: 100%;" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="结束时间：" prop="endTime">
              <span v-show="!dialog1Editing">{{ dialog1Data.endTime }}</span>
              <el-time-picker v-show="dialog1Editing" v-model="dialog1Data.endTime" value-format="HH:mm:ss" style="width: 100%;" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注：" prop="note">
              <span v-show="!dialog1Editing">{{ dialog1Data.note }}</span>
              <el-input v-show="dialog1Editing" v-model="dialog1Data.note" maxlength="100" show-word-limit />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div v-show="dialog1Editing" slot="footer" class="dialog-footer">
        <el-button type="text" @click="dialog1Show=false">取消</el-button>
        <el-button :loading="dialog1Saving" type="primary" @click="dialog1Submit">确认</el-button>
      </div>
    </el-dialog>
    <!--弹出框2-->
    <el-dialog append-to-body :close-on-click-modal="true" :visible.sync="dialog2Show" :title="'确认'+(dialog2Data.hasEnable?'启用':'停用')" width="580px">
      <div>
        <span>确认要{{ dialog2Data.hasEnable?'启用':'停用' }}班次：</span>
        <span style="font-weight: bold;">{{ dialog2Data.name }}</span><span>吗？</span>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="dialog2Show=false">取消</el-button>
        <el-button :loading="dialog2Saving" type="primary" @click="dialog2Submit">确认</el-button>
      </div>
    </el-dialog>
    <!--弹出框3-->
    <el-dialog append-to-body :close-on-click-modal="true" :visible.sync="dialog3Show" :title="'确认删除'" width="580px">
      <div>
        <el-alert title="注意：删除班次会连带影响已经排班的信息！" description="如果此排班信息已经使用过，建议设置为停用。" type="warning" effect="dark" style="margin-bottom: 30px;" />
      </div>
      <div>
        <span>确认要删除班次：</span>
        <span style="font-weight: bold;">{{ dialog3Data.name }}</span><span>吗？</span>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="dialog3Show=false">取消</el-button>
        <el-button :loading="dialog3Saving" type="primary" @click="dialog3Submit">确认</el-button>
      </div>
    </el-dialog>
    <!--表格-->
    <el-table ref="table" v-loading="searching" :data="tableData" row-key="id">
      <el-table-column :show-overflow-tooltip="true" prop="id" label="编号" width="100px" align="center" />
      <el-table-column :show-overflow-tooltip="true" prop="name" label="班次名称" align="center" />
      <el-table-column :show-overflow-tooltip="true" prop="beginTime" label="开始时间" align="center" />
      <el-table-column :show-overflow-tooltip="true" prop="endTime" label="结束时间" align="center" />
      <el-table-column :show-overflow-tooltip="true" prop="note" label="备注" align="center" />
      <el-table-column :show-overflow-tooltip="true" prop="hasEnable" label="是否启用" align="center">
        <template slot-scope="scope">
          {{ scope.row.hasEnable ? '是' : '否' }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="350px" align="center" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" round @click="doEdit(scope.row.id,false)">查看</el-button>
          <el-button size="mini" round @click="doEdit(scope.row.id,true)">修改</el-button>
          <el-button v-show="scope.row.hasEnable" size="mini" round @click="doEnable(scope.row.id, false)">停用</el-button>
          <el-button v-show="!scope.row.hasEnable" size="mini" round @click="doEnable(scope.row.id, true)">启用</el-button>
          <el-button size="mini" round @click="doDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :page-sizes="[10, 20, 50, 100]"
      :current-page.sync="searchParam.page"
      :page-size.sync="searchParam.count"
      :total="searchResult.total"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="searchSubmit"
      @current-change="searchSubmit"
    />
  </div>
</template>

<script>
import leaderClassesApi from '@/api/kd/leaderClasses'
import { mapGetters } from 'vuex'
const searchParam = { // 默认搜索条件
  hasEnable: true,
  page: 1,
  count: 10,
  searchCount: true
}
export default {
  name: 'ELeaderClasses', // 本页面名
  components: {},
  data() {
    return {
      selectedMine: {},
      searching: false,
      searchParam: {},
      searchResult: {
        total: 0,
        results: [] // 搜索结果
      },
      dialog1Show: false,
      dialog1Editing: false,
      dialog1Saving: false,
      dialog1Data: {},
      dialog1Rules: {
        name: [{ required: true, message: '请填写' }],
        beginTime: [{ required: true, message: '请填写' }],
        endTime: [{ required: true, message: '请填写' }]
      },
      editState: 0, // （刚打开窗口时）记录了上次窗口作用；（保存编辑时）记录了当前窗口作用； 0无 1新增 2修改 3查看
      addingData: {}, // 上次正在新增时的内容，下次打开dialog1窗口时记录下来
      dialog2Show: false,
      dialog2Saving: false,
      dialog2Data: {},
      dialog3Show: false,
      dialog3Saving: false,
      dialog3Data: {}
    }
  },
  computed: {
    ...mapGetters([
      'user'
    ]),
    tableData() {
      // 此处对返回值进行算法重组
      return this.searchResult.results
    }
  },
  mounted() {
    const selectedMineJson = window.localStorage.getItem('kd.selected.mine')
    let noMine = false
    if (!selectedMineJson) {
      noMine = true
    } else {
      const selectedMine = JSON.parse(selectedMineJson)
      if (!selectedMine || selectedMine.enterpriseId !== this.user.enterpriseId) {
        noMine = true
      } else {
        this.selectedMine = selectedMine
      }
    }
    // if (noMine) {
    //   this.$message.error('当前未选择矿山')
    //   this.$router.replace('/dashboard')
    // }
    this.searchParamReset()
    this.searchSubmit()
  },
  methods: {
    searchParamReset() {
      this.searchParam = JSON.parse(JSON.stringify(searchParam))
    },
    searchSubmit() {
      this.searching = true
      this.searchParam.mineType = this.selectedMine.mineType
      this.searchParam.mineId = this.selectedMine.id
      leaderClassesApi.getPage(this.searchParam).then(response => {
        this.searching = false
        this.searchResult = response
      }).catch(() => {
        this.searching = false
      })
    },
    dialog1Submit() {
      this.$refs['dialog1Form'].validate(valid => {
        if (!valid) {
          return
        } else {
          this.dialog1Saving = true
          if (this.dialog1Data.beginTime >= this.dialog1Data.endTime) {
            this.$message.error('结束时间不可小于开始时间')
            this.dialog1Saving = false
            return
          }
          if (this.editState === 1) { // 新增
            this.dialog1Data.mineType = this.selectedMine.mineType
            this.dialog1Data.mineId = this.selectedMine.id
            leaderClassesApi.add(this.dialog1Data).then(() => {
              this.dialog1Show = false
              this.$message.success('保存成功')
              setTimeout(() => { // 立即清除会导致输入框Validate一闪变红
                this.dialog1Data = {}
                this.dialog1Saving = false
              }, 500)
              this.searchSubmit()
            }).catch(() => {
              this.dialog1Saving = false
            })
          } else if (this.editState === 2) { // 修改
            leaderClassesApi.set(this.dialog1Data).then(() => {
              this.dialog1Show = false
              this.$message.success('修改成功')
              setTimeout(() => { // 立即清除会导致输入框Validate一闪变红
                this.dialog1Data = {}
                this.dialog1Saving = false
              }, 500)
              this.searchSubmit()
            }).catch(() => {
              this.dialog1Saving = false
            })
          } else {
            this.$message.error('出错啦，请重试')
            this.dialog1Saving = false
          }
        }
      })
    },
    beforeDialog1Open() { // 窗口打开前的统一操作
      if (this.editState === 1) {
        this.addingData = this.dialog1Data
      }
    },
    doAdd() {
      this.beforeDialog1Open()
      this.editState = 1
      this.dialog1Editing = true
      this.dialog1Data = this.addingData // 初始值：上次编辑的内容
      this.dialog1Show = true
      this.$nextTick(() => {
        this.$refs['dialog1Form'].clearValidate()
      })
    },
    doEdit(id, isEdit) {
      this.beforeDialog1Open()
      this.editState = isEdit ? 2 : 3
      leaderClassesApi.getById(id).then(response => {
        this.dialog1Data = response
        this.dialog1Editing = isEdit
        this.dialog1Show = true
        this.$nextTick(() => {
          this.$refs['dialog1Form'].clearValidate()
        })
      }).catch(() => {
        this.$message.error('出错啦，请重试')
        this.searchSubmit()
      })
    },
    dialog2Submit() {
      this.dialog2Saving = true
      leaderClassesApi.setEnable(this.dialog2Data).then(() => {
        this.dialog2Show = false
        this.$message.success('操作成功')
        this.dialog2Data = {}
        this.dialog2Saving = false
        this.searchSubmit()
      }).catch(() => {
        this.dialog2Saving = false
      })
    },
    doEnable(id, enable) {
      leaderClassesApi.getById(id).then(response => {
        response.hasEnable = enable
        this.dialog2Data = response
        this.dialog2Show = true
      }).catch(() => {
        this.searchSubmit()
      })
    },
    dialog3Submit() {
      this.dialog3Saving = true
      leaderClassesApi.del(this.dialog3Data).then(() => {
        this.dialog3Show = false
        this.$message.success('操作成功')
        this.dialog3Data = {}
        this.dialog3Saving = false
        this.searchSubmit()
      }).catch(() => {
        this.dialog3Saving = false
      })
    },
    doDelete(id) {
      leaderClassesApi.getById(id).then(response => {
        this.dialog3Data = response
        this.dialog3Show = true
      }).catch(() => {
        this.searchSubmit()
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  ::v-deep .el-input-number .el-input__inner {
    text-align: left;
  }
  ::v-deep .vue-treeselect__control,::v-deep .vue-treeselect__placeholder,::v-deep .vue-treeselect__single-value {
    height: 30px;
    line-height: 30px;
  }
</style>
