<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div>
        <el-select v-model="searchParam._mineIndex" placeholder="所属矿山" clearable size="small" class="filter-item" style="width: 200px;">
          <el-option v-for="mine in mineList" :key="mine.index" :label="mine.name" :value="mine.index" />
        </el-select>
        <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-tooltip class="item" effect="dark" content="按当前页面数据" placement="top">
          <el-button :loading="exporting" class="filter-item" size="mini" type="info" plain icon="el-icon-download" @click="exportSubmit">导出</el-button>
        </el-tooltip>
        <el-tooltip class="item" effect="dark" content="打印当前页面内容" placement="top">
          <el-button class="filter-item" size="mini" type="info" plain icon="el-icon-printer" @click="print">打印</el-button>
        </el-tooltip>
      </div>
    </div>
    <!--弹出框1-->
    <el-dialog append-to-body :close-on-click-modal="true" :visible.sync="dialog1Show" :title="'确认审核'" width="580px">
      <div v-if="dialog1Show">
        <span style="font-weight:bold;">{{ dialog1Data.schedulingDate }}</span>
        <span style="font-weight:bold;">{{ dialog1Data.leaderClassesName }}</span>
        <span>变更为</span>
        <span style="font-weight:bold;">{{ dialog1Data.changingToStaffName }}</span>
        <span>的变更申请吗？</span>
        <br>
        <br>
        <span>备注：{{ dialog1Data.changing.note }}</span>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="dialog1Show=false">取消</el-button>
        <el-button :loading="dialog1Saving" type="danger" @click="dialog1Submit(3)">拒绝</el-button>
        <el-button :loading="dialog1Saving" type="primary" @click="dialog1Submit(2)">通过</el-button>
      </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="item.changing?doAudit(item):''">
                  {{ item.leaderClassesName }}：{{ item.staffName }}
                </div>
              </el-tooltip>
            </div>
          </div>
        </div>
      </template>
    </el-calendar>
    <!--打印BOX-->
    <div class="print-box">
      <el-calendar v-model="calendarDate" :loading="true">
        <template slot="dateCell" slot-scope="{date, data}">
          <div>{{ (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">
                <div>
                  {{ item.leaderClassesName }}：{{ item.staffName }}
                </div>
              </div>
            </div>
          </div>
        </template>
      </el-calendar>
    </div>
  </div>
</template>

<script>
import leaderSchedulingApi from '@/api/kd/leaderScheduling'
import { mapGetters } from 'vuex'
import { getMonthFrist, getMonthLast, parseTime } from '@/utils/index'
import mineApi from '@/api/kd/mine'
import { downloadFile } from '@/utils'

const searchParam = { // 搜索条件，不分页
  _month: new Date()
}
export default {
  name: 'CLeaderScheduling', // 本页面名
  components: {},
  data() {
    return {
      mineList: [],
      searching: false,
      exporting: false,
      searchingMask: null,
      searchParam: {},
      searchResult: {
        results: [] // 搜索结果
      },
      calendarDate: new Date(),
      dialog1Show: false,
      dialog1Saving: false,
      dialog1Data: {}
    }
  },
  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() {
    this.searchParamReset()
    // 矿山选项卡
    mineApi.getEnableMine().then(response => {
      let i = 1
      response.results.forEach(x => { x.index = i++ })
      this.mineList = response.results
      if (this.mineList && this.mineList.length > 0) {
        this.$set(this.searchParam, '_mineIndex', 1)
        this.searchSubmit()
      }
    })
  },
  methods: {
    searchParamReset() {
      this.searchParam = JSON.parse(JSON.stringify(searchParam))
    },
    searchSubmit() {
      if (this.searchParam._mineIndex) {
        const mine = this.mineList[this.searchParam._mineIndex - 1]
        this.searchParam.mineType = mine.mineType
        this.searchParam.mineId = mine.id
      } else {
        this.$message.error('请选择要查询的矿山')
        return
      }
      if (!this.searchParam._month) {
        this.$message.error('请选择查询月份')
        return
      }
      let calendarDate = this.searchParam._month // 查询成功后将要赋值给日历，先缓存下来，防止查询过程中this.data发生改变
      if (typeof calendarDate === 'string') {
        calendarDate = new Date(calendarDate)
      }
      this.searching = true
      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
      })
    },
    exportSubmit() {
      if (this.searchParam._mineIndex) {
        const mine = this.mineList[this.searchParam._mineIndex - 1]
        this.searchParam.mineType = mine.mineType
        this.searchParam.mineId = mine.id
      } else {
        this.$message.error('请选择要查询的矿山')
        return
      }
      if (!this.searchParam._month) {
        this.$message.error('请选择查询月份')
        return
      }
      let calendarDate = this.searchParam._month
      if (typeof calendarDate === 'string') {
        calendarDate = new Date(calendarDate)
      }
      this.exporting = true
      this.searchParam.schedulingDateFrom = parseTime(getMonthFrist(calendarDate), '{y}-{m}-{d}')
      this.searchParam.schedulingDateTo = parseTime(getMonthLast(calendarDate), '{y}-{m}-{d}')
      leaderSchedulingApi.export(this.searchParam).then(response => {
        downloadFile(response, '带班领导排班', 'xlsx')
        this.exporting = false
      }).catch(() => {
        this.exporting = false
      })
    },
    doAudit(changeInfo) {
      this.dialog1Data = JSON.parse(JSON.stringify(changeInfo))
      this.dialog1Show = true
    },
    dialog1Submit(auditState) {
      this.dialog1Saving = true
      this.dialog1Data.changing.auditState = auditState
      leaderSchedulingApi.auditChange(this.dialog1Data.changing).then(() => {
        this.$message.success('审核完成')
        this.dialog1Show = false
        this.dialog1Saving = false
        this.searchSubmit()
      })
    },
    print() {
      window.print()
    }
  }
}
</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>
