<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div>
        <el-date-picker v-model="searchParam._month" type="month" clearable size="small" style="width: 200px;" class="filter-item" placeholder="选择月" />
        <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="primary" icon="el-icon-plus" @click="doAdd()">新增</el-button>
        <el-upload
          class="filter-item"
          action="/api/leader-scheduling/import"
          multiple
          :data="{mineType:selectedMine.mineType,mineId:selectedMine.id}"
          :headers="httpHeaders"
          :before-upload="beforeImport"
          :on-success="importSuccess"
          :on-error="importError"
          :show-file-list="false"
        >
          <el-button :loading="dialog3Saving" size="mini" type="success" icon="el-icon-upload2">导入</el-button>
        </el-upload>
      </div>
    </div>
    <!--弹出框1-->
    <el-dialog append-to-body :close-on-click-modal="true" :visible.sync="dialog1Show" :title="'新增'" width="960px">
      <el-form ref="dialog1Form" :model="dialog1Data" :rules="dialog1Rules" size="mini" label-width="180px" style="margin-right: 80px;">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="带班日期：" prop="schedulingDateFrom">
              <el-date-picker v-model="dialog1Data.schedulingDateFrom" value-format="yyyy-MM-dd" style="width: 100%;" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="至（含）：" prop="schedulingDateTo">
              <el-date-picker v-model="dialog1Data.schedulingDateTo" value-format="yyyy-MM-dd" style="width: 100%;" />
            </el-form-item>
          </el-col>
          <el-col :span="20">
            <el-form-item label="班次：" prop="leaderClassesId">
              <el-select v-model="dialog1Data.leaderClassesId" filterable remote placeholder="请输入姓名搜索" clearable :remote-method="dialog1LeaderClassesSearch" style="width: 100%;">
                <el-option v-for="item in dialog1Data._leaderClassesSelections" :key="item.id" :label="item.name" :value="item.id">
                  <span style="float: left">{{ item.name }}</span>
                  <span style="float: right; color: #8492a6; font-size: 12px">{{ item.beginTime + '~' + item.endTime }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="20">
            <el-form-item label="带班领导：" prop="staffId">
              <el-select v-model="dialog1Data.staffId" filterable remote placeholder="请输入姓名搜索" clearable :remote-method="dialog1StaffSearch" style="width: 100%;">
                <el-option v-for="item in dialog1Data._staffSelections" :key="item.id" :label="item.name" :value="item.id">
                  <span style="float: left; margin-right: 10px;">{{ item.name }}</span>
                  <span style="float: right; color: #8492a6; font-size: 12px">{{ stringMosaic(item.idcard,6) }}</span>
                  <span style="float: right; color: #8492a6; font-size: 12px">{{ item.departmentName?item.departmentName+'，':'' }}</span>
                  <span style="float: right; color: #8492a6; font-size: 12px">{{ item.jobName?item.jobName+'，':'' }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="20">
            <el-form-item label="备注：" prop="note">
              <el-input v-model="dialog1Data.note" maxlength="100" show-word-limit />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div 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="'申请变更带班领导'" width="640px">
      <el-form ref="dialog2Form" :model="dialog2Data" size="mini" label-width="180px" style="margin-right: 80px;">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="带班日期：" prop="schedulingDate">
              <span>{{ dialog2Data.schedulingDate }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="班次：" prop="leaderClassesId">
              <span>{{ dialog2Data.leaderClassesName }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="撤销：" prop="noStaff">
              <el-checkbox v-model="dialog2Data.noStaff">申请撤销此次带班</el-checkbox>
            </el-form-item>
          </el-col>
          <el-col v-if="!dialog2Data.noStaff" :span="24">
            <el-form-item label="变更带班领导：" prop="staffId">
              <el-select v-model="dialog2Data.staffId" filterable remote placeholder="请输入姓名搜索" clearable :remote-method="dialog2StaffSearch" style="width: 100%;">
                <el-option v-for="item in dialog2Data._staffSelections" :key="item.id" :label="item.name" :value="item.id">
                  <span style="float: left; margin-right: 10px;">{{ item.name }}</span>
                  <span style="float: right; color: #8492a6; font-size: 12px">{{ stringMosaic(item.idcard,6) }}</span>
                  <span style="float: right; color: #8492a6; font-size: 12px">{{ item.departmentName?item.departmentName+'，':'' }}</span>
                  <span style="float: right; color: #8492a6; font-size: 12px">{{ item.jobName?item.jobName+'，':'' }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注：" prop="note">
              <el-input v-model="dialog2Data.note" maxlength="100" show-word-limit />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <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>
        <span>共计成功导入：</span>
        <span style="font-weight: bold;">{{ dialog3Data.successCount + dialog3Data.failCount }}</span>
        <span>条，请核对总数。</span>
      </div>
      <div>
        <span>其中，成功：</span>
        <span style="color: #67C23A;">{{ dialog3Data.successCount }}</span>
        <span>条；失败：</span>
        <span style="color: #F56C6C;">{{ dialog3Data.failCount }}</span>
        <span>条。</span>
      </div>
      <br>
      <div v-if="dialog3Data.failCount">
        <div><span>失败信息：</span></div>
        <br>
        <div v-for="failReason in dialog3Data.failReasonList" :key="failReason.index">
          <span>第{{ failReason.index }}条数据</span>
          <span v-if="failReason.row" style="font-size: 10px;color: #909399;">第{{ failReason.row }}行</span>
          <span v-if="failReason.col" style="font-size: 10px;color: #909399;">第{{ failReason.col }}列</span>
          <span v-if="failReason.data" style="margin-left: 10px; color: #F56C6C;">{{ failReason.data }}</span>
          <span style="margin-left: 10px;">{{ failReason.reason }}</span>
        </div>
      </div>
    </el-dialog>
    <!--日历-->
    <el-calendar id="calendar" v-model="calendarDate" :loading="true">
      <template slot="dateCell" slot-scope="{date, data}">
        <div v-if="date.getMonth() == calendarDate.getMonth()" style="background-color:#8492a6;color:#FFFFFF;text-align:center;padding:3px;border-radius:4px;">{{ (date.getMonth()+1)+'-'+date.getDate() }}</div>
        <div v-else style="border:#d2d5dd 1px solid;color:#d2d5dd;text-align:center;padding:3px;border-radius:4px;">{{ (date.getMonth()+1)+'-'+date.getDate() }}</div>
        <div v-if="date.getMonth() == calendarDate.getMonth()">
          <div v-if="calendarData[data.day]">
            <div v-for="(item,index) in calendarData[data.day]" :key="index">
              <el-tooltip :disabled="item.changing?false:true" effect="dark" :content="item.changingToStaffName?'变更成'+item.changingToStaffName+'审核中':'取消排班审核中'" placement="left">
                <div class="calendar-scheduling" :class="item.changing?'calendar-scheduling-error':''" @click.stop="doChange(item.id)">
                  {{ item.leaderClassesName }}：{{ item.staffName }}
                </div>
              </el-tooltip>
            </div>
          </div>
        </div>
      </template>
    </el-calendar>
  </div>
</template>

<script>
import leaderSchedulingApi from '@/api/kd/leaderScheduling'
import leaderClassesApi from '@/api/kd/leaderClasses'
import staffApi from '@/api/kd/staff'
import { getToken } from '@/utils/auth'
import { mapGetters } from 'vuex'
import { getMonthFrist, getMonthLast, parseTime } from '@/utils/index'
const searchParam = { // 搜索条件，不分页
  _month: new Date()
}
export default {
  name: 'ELeaderScheduling', // 本页面名
  components: {},
  data() {
    return {
      selectedMine: {},
      httpHeaders: {
        'Authorization': getToken()
      },
      searching: false,
      searchingMask: null,
      searchParam: {},
      searchResult: {
        results: [] // 搜索结果
      },
      calendarDate: new Date(),
      dialog1Show: false,
      dialog1Saving: false,
      dialog1Data: {},
      dialog1Rules: {
        schedulingDateFrom: [{ required: true, message: '请填写' }],
        schedulingDateTo: [{ required: true, message: '请填写' }],
        leaderClassesId: [{ required: true, message: '请选择' }],
        staffId: [{ required: true, message: '请选择' }]
      },
      dialog2Show: false,
      dialog2Saving: false,
      dialog2Data: {},
      dialog3Show: false,
      dialog3Data: {},
      dialog3Saving: false
    }
  },
  computed: {
    ...mapGetters([
      'user'
    ]),
    calendarData() {
      const array = this.searchResult.results
      // 按开始时间排序
      const timeMap = {} // {开始时间:[{排班信息}]} 防止班次开始时间重复，使用数组，支持同时间多班次
      let timeList = [] // [开始时间]
      array.forEach(x => {
        if (!timeMap[x.beginDateTime]) {
          timeMap[x.beginDateTime] = []
        }
        timeMap[x.beginDateTime].push(x)
        timeList.push(x.beginDateTime)
      })
      timeList = timeList.sort()
      // list转map，方便按日展示
      const result = {}
      timeList.forEach(t => {
        timeMap[t].forEach(x => {
          if (!result[x.schedulingDate]) {
            result[x.schedulingDate] = []
          }
          result[x.schedulingDate].push(x)
        })
      })
      return result
    }
  },
  watch: {
    calendarDate(newValue, oldValue) {
      if (newValue.getMonth() !== oldValue.getMonth() || newValue.getFullYear() !== oldValue.getFullYear()) {
        this.searchParam._month = newValue
        this.searchSubmit()
      }
    },
    searching(newValue, oldValue) {
      if (newValue && !oldValue) {
        this.searchingMask = this.$loading({
          target: '#calendar',
          lock: true,
          text: '加载中',
          spinner: 'el-icon-loading'
        })
      } else if (this.searchingMask) {
        this.searchingMask.close()
        this.searchingMask = null
      }
    }
  },
  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() {
      if (!this.searchParam._month) {
        this.$message.error('请选择查询月份')
        return
      }
      this.searching = true
      let calendarDate = this.searchParam._month // 查询成功后将要赋值给日历，先缓存下来，防止查询过程中this.data发生改变
      if (typeof calendarDate === 'string') {
        calendarDate = new Date(calendarDate)
      }
      this.searchParam.mineType = this.selectedMine.mineType
      this.searchParam.mineId = this.selectedMine.id
      this.searchParam.schedulingDateFrom = parseTime(getMonthFrist(calendarDate), '{y}-{m}-{d}')
      this.searchParam.schedulingDateTo = parseTime(getMonthLast(calendarDate), '{y}-{m}-{d}')
      leaderSchedulingApi.getAll(this.searchParam).then(response => {
        this.searching = false
        this.searchResult = response
        this.calendarDate = calendarDate
      }).catch(() => {
        this.searching = false
      })
    },
    dialog1Submit() {
      this.$refs['dialog1Form'].validate(valid => {
        if (!valid) {
          return
        } else {
          this.dialog1Saving = true
          if (this.dialog1Data.schedulingDateFrom > this.dialog1Data.schedulingDateTo) {
            this.$message.error('结束日期不可小于开始日期')
            this.dialog1Saving = false
            return
          }
          this.dialog1Data.mineType = this.selectedMine.mineType
          this.dialog1Data.mineId = this.selectedMine.id
          leaderSchedulingApi.addMoreDate(this.dialog1Data).then(() => {
            this.dialog1Show = false
            this.$message.success('保存成功')
            setTimeout(() => { // 立即清除会导致输入框Validate一闪变红
              this.dialog1Data = {}
              this.dialog1Saving = false
            }, 500)
            this.searchSubmit()
          }).catch(() => {
            this.dialog1Saving = false
          })
        }
      })
    },
    doAdd() {
      this.dialog1Data = {}
      this.dialog1Show = true
      this.$nextTick(() => {
        this.$refs['dialog1Form'].clearValidate()
      })
    },
    dialog1StaffSearch(queryString) {
      staffApi.getPage({
        nameLike: queryString,
        mineType: this.selectedMine.mineType,
        mineId: this.selectedMine.id
      }).then(response => {
        this.$delete(this.dialog1Data, '_staffSelections') // 解决$set不更新DOM
        this.$set(this.dialog1Data, '_staffSelections', response.results)
      }).catch(() => {
        this.$message.error('出错啦，请重试')
      })
    },
    stringMosaic(str, showLastNumber) {
      if (str) {
        return '**' + str.substring(str.length - showLastNumber)
      }
      return ''
    },
    dialog1LeaderClassesSearch(queryString) {
      leaderClassesApi.getPage({
        nameLike: queryString,
        mineType: this.selectedMine.mineType,
        mineId: this.selectedMine.id
      }).then(response => {
        this.$delete(this.dialog1Data, '_leaderClassesSelections') // 解决$set不更新DOM
        this.$set(this.dialog1Data, '_leaderClassesSelections', response.results)
      }).catch(() => {
        this.$message.error('出错啦，请重试')
      })
    },
    doChange(id) {
      leaderSchedulingApi.getById(id).then(response => {
        if (response && response.id) {
          this.dialog2Data = response
          this.$set(this.dialog2Data, 'noStaff', false)
          this.$set(this.dialog2Data, '_staffSelections', [{ id: response.staffId, name: response.staffName }])
          this.dialog2Show = true
        } else {
          this.$message('查询排班信息失败，无法进行变更')
          this.searchSubmit()
        }
      }).catch(() => {
        this.searchSubmit()
      })
    },
    dialog2Submit() {
      if (!this.dialog2Data.noStaff && !this.dialog2Data.staffId) {
        this.$message.error('请选择变更后的值班领导')
        return
      }
      const param = {
        mineType: this.selectedMine.mineType,
        mineId: this.selectedMine.id,
        schedulingId: this.dialog2Data.id,
        staffId: this.dialog2Data.noStaff ? null : this.dialog2Data.staffId,
        note: this.dialog2Data.note
      }
      leaderSchedulingApi.applyChange(param).then(() => {
        this.$message.success('变更申请已提交')
        this.dialog2Saving = false
        this.dialog2Show = false
        this.searchSubmit()
      }).catch(() => {
        this.dialog2Saving = false
      })
    },
    dialog2StaffSearch(queryString) {
      staffApi.getPage({
        nameLike: queryString,
        mineType: this.selectedMine.mineType,
        mineId: this.selectedMine.id
      }).then(response => {
        this.$delete(this.dialog2Data, '_staffSelections') // 解决$set不更新DOM
        this.$set(this.dialog2Data, '_staffSelections', response.results)
      }).catch(() => {
        this.$message.error('出错啦，请重试')
      })
    },
    dialog2LeaderClassesSearch(queryString) {
      leaderClassesApi.getPage({
        nameLike: queryString,
        mineType: this.selectedMine.mineType,
        mineId: this.selectedMine.id
      }).then(response => {
        this.$delete(this.dialog2Data, '_leaderClassesSelections') // 解决$set不更新DOM
        this.$set(this.dialog2Data, '_leaderClassesSelections', response.results)
      }).catch(() => {
        this.$message.error('出错啦，请重试')
      })
    },
    beforeImport() {
      this.dialog3Saving = true
    },
    importSuccess(response, file, fileList) {
      this.dialog3Data = response
      this.dialog3Show = true
      this.searchSubmit()
      this.dialog3Saving = false
    },
    importError(error) {
      this.$message.error('导入失败')
      console.error('导入失败', error)
      this.dialog3Saving = false
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .calendar-scheduling{
    color: #444444;
    border:#d2d5dd 1px solid;
    padding:6px;
    padding-top:8px;
    border-radius:4px;
    margin-top:4px;
    font-size:small;
    cursor:pointer;
  }
  .calendar-scheduling:hover{
    background-color: #eeeeee;
  }
  .calendar-scheduling-error{
    border:#f8dcdc 1px solid;
    background-color: #fbeeed;
  }
  .calendar-scheduling-error:hover{
    background-color: #fbeeed;
  }
  ::v-deep .el-calendar-day{
    min-height: 110px;
    height: inherit !important;
    position: relative;
    z-index: inherit;
  }
  ::v-deep .el-calendar-table .el-calendar-day:hover {
    background-color: rgba($color: #000000, $alpha: 0.0) !important;
    cursor: auto;
  }
  ::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>
