<template>
  <d2-container>
    <template slot="header"
              style="padding: 5px;">
      <el-form :model="dutyDetail">
        <el-row>
          <el-col :span="10">
            <el-form-item label="标题"
                          label-width="120px">
              {{dutyDetail.Title}}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="10">
            <el-form-item label="学年"
                          label-width="120px">
              {{dutyDetail.Year}}年
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="10">
            <el-form-item label="学期"
                          label-width="120px">
              {{this.termName}}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-form-item label="地点"
                        size="mini"
                        label-width="120px">
            <el-checkbox-group v-model="selectLocal">
              <el-checkbox-button v-for="item in LocalList"
                                  :label="item.ItemValue"
                                  :key="item.ItemValue"
                                  style="float:left">{{item.ItemName}}</el-checkbox-button>
            </el-checkbox-group>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="值班时间"
                        size="mini"
                        label-width="120px">
            <el-checkbox-group v-model="selectTime">
              <el-checkbox-button v-for="item in TimeList"
                                  :label="item.ItemValue"
                                  :key="item.ItemValue"
                                  style="float:left">{{item.ItemName}}</el-checkbox-button>
            </el-checkbox-group>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="值班人员"
                        size="mini"
                        label-width="120px">
            <el-button @click="personClick(item.Id)"
                       v-for="item in PeopleList"
                       :key="item.Id"
                       :label="item.Id"
                       style="float:left">{{item.PersonnelName}}</el-button>
          </el-form-item>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="16">
            &nbsp;
          </el-col>
          <el-col :span="2">
            <el-button size="mini"
                       @click="addList()"
                       type="success">生成值班表</el-button>
          </el-col>
          <el-col :span="2">
            <el-button size="mini"
                       type="primary"
                       @click="addDuytDetail()">保存值班表</el-button>
          </el-col>
          <el-col :span="2">
            <el-button size="mini"
                       type="warning"
                       @click="exportExcel()">导出</el-button>
          </el-col>
          <el-col :span="1">
            <el-button size="mini"
                       type="danger"
                       Updated
                       upstream
                       @click="back()">关闭</el-button>
          </el-col>
        </el-row>
      </el-form>
    </template>
    <el-table :data="list"
              border
              fit
              tooltip-effect="dark"
              style="width: 100%"
              height="100%"
              @cell-click="cellclick"
              @header-click="headclick"
              :cell-class-name="cellBg"
              :key="refresh"
              id="out-table">
      <el-table-column fit
                       prop="Local"
                       min-width="160px"
                       label="地点"
                       align="center"
                       show-overflow-tooltip
                       :formatter="formatLocal"></el-table-column>
      <el-table-column prop="Time"
                       label="时间段"
                       align="center"
                       min-width="120px"
                       show-overflow-tooltip
                       :formatter="formatTime"></el-table-column>
      <el-table-column prop="Monday"
                       label="周一"
                       align="center"
                       min-width="120px"
                       show-overflow-tooltip
                       :formatter="formatPerson"></el-table-column>
      <el-table-column prop="Tuesday"
                       label="周二"
                       align="center"
                       min-width="120px"
                       show-overflow-tooltip
                       :formatter="formatPerson"></el-table-column>
      <el-table-column prop="Wednesday"
                       label="周三"
                       align="center"
                       min-width="120px"
                       show-overflow-tooltip
                       :formatter="formatPerson"></el-table-column>
      <el-table-column prop="Thursday"
                       label="周四"
                       align="center"
                       min-width="120px"
                       show-overflow-tooltip
                       :formatter="formatPerson"></el-table-column>
      <el-table-column prop="Friday"
                       label="周五"
                       align="center"
                       min-width="120px"
                       show-overflow-tooltip
                       :formatter="formatPerson"></el-table-column>
      <el-table-column prop="Saturday"
                       label="周六"
                       align="center"
                       min-width="120px"
                       show-overflow-tooltip
                       :formatter="formatPerson"></el-table-column>
      <el-table-column prop="Sunday"
                       label="周日"
                       align="center"
                       min-width="120px"
                       show-overflow-tooltip
                       :formatter="formatPerson"></el-table-column>
      <el-table-column label="操作"
                       width="80px"
                       align="center">
        <template slot-scope="scope">
          <el-button size="mini"
                     type="danger"
                     title="删除"
                     @click="deleteRow(scope.$index,list)"
                     style="margin-left:3px;"
                     icon="el-icon-delete"
                     circle></el-button>
        </template>
      </el-table-column>
    </el-table>
  </d2-container>
</template>
<script>
// 总列数
import { mapState, mapActions } from 'vuex'
import DutyApi from '@/api/duty'
import itemDetailApi from '@/api/sysadmin/itemdetail'
import PersonnelApi from '@/api/personnel'
import FileSaver from 'file-saver'
import XLSX from 'xlsx'
const columnNum = 9
// 固定列数
const fixRowHeadNum = 2
// todo 欠优化 列属性对应
const columnProperty = [
  'Local',
  'Time',
  'Monday',
  'Tuesday',
  'Wednesday',
  'Thursday',
  'Friday',
  'Saturday',
  'Sunday'
]
export default {
  name: 'dutyEdit',
  data () {
    return {

      LocalList: [],
      PeopleList: [],
      TimeList: [],
      termList: [],
      termName: '',
      selectLocal: [],
      selectTime: [],
      dutyDetail: {
        Id: -1,
        Year: -1,
        Term: -1
      },
      year: '',
      years: [],
      dialogvisible: false,
      // 刷新标志 刷新表格样式
      refresh: 123,
      // 已选列表
      selectcell: new Map(),
      // 数据列表
      list: []
    }
  },
  computed: {
    ...mapState('d2admin/page', [
      'opened',
      'current' // 用户获取当前页面的地址，用于关闭
    ])
  },

  mounted () {
    this.getLocal()
    this.getPeople()
    this.getDutyTime()
    let _this = this
    _this.dutyDetail = _this.$route.query.duty
    _this.termList = _this.$route.query.term
    this.getTerm()
    this.getDetailData()
  },
  methods: {
    // 导出excel
    exportExcel () {
      /* out-table关联导出的dom节点  */
      var wb = XLSX.utils.table_to_book(document.querySelector('#out-table'))
      /* get binary string as output */
      var wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' })
      try {
        FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), '值班表.xlsx')
      } catch (e) { if (typeof console !== 'undefined') console.log(e, wbout) }
      return wbout
    },
    // 初始化单选框
    selectCheckBox () {
      let selectLocal = new Map()
      let selectTime = new Map()

      for (var i = 0; i < this.list.length; i++) {
        if (selectLocal.get(this.list[i].Local + '') !== true) {
          this.selectLocal.push(this.list[i].Local + '')
        }
        if (selectTime.get(this.list[i].Time + '') !== true) {
          this.selectTime.push(this.list[i].Time + '')
        }
        selectLocal.set(this.list[i].Local + '', true)
        selectTime.set(this.list[i].Time + '', true)
      }
    },
    // 获取值班子表表格
    getDetailData () {
      let _this = this
      DutyApi.getDetailByDutyId({
        DutyId: _this.dutyDetail.Id
      }).then(res => {
        if (res.length > 0) {
          _this.list = res
          _this.selectCheckBox()
        }
      })
    },
    // 新增表格
    addList () {
      if (this.selectLocal == 0 && this.selectTime.length == 0) {
        return
      }
      //  清空已选择
      this.selectcell = new Map()
      let _this = this; let listMap = new Map(); let newList = []
      this.list.forEach(row => {
        listMap.set(row.Local + '_' + row.Time, row)
      })
      this.selectLocal.forEach(function (value, key) {
        _this.selectTime.forEach(function (valuee, keyy) {
          if (listMap.get(value + '_' + valuee)) {
            newList.push(listMap.get(value + '_' + valuee))
          } else {
            newList.push({
              DutyId: _this.dutyDetail.Id,
              Local: value,
              Time: valuee,
              Monday: 0,
              Tuesday: 0,
              Wednesday: 0,
              Thursday: 0,
              Friday: 0,
              Saturday: 0,
              Sunday: 0
            })
          }
        })
      })
      this.list = newList
    },
    // 保存值班子表信息
    addDuytDetail () {
      if (this.dutyDetail.Id) {
        DutyApi.Saves({ DataList: this.list, DutyId: this.dutyDetail.Id })
          .then(res => {

          })
          .catch(err => {
            // handle error
            console.error(err)
          })
      } else {
        console.log('error submit!!')
        return false
      }
    },
    // 删除一行
    deleteRow (index, rows) {
      rows.splice(index, 1)
    },
    // 获取字典表地点
    getLocal () {
      let _this = this
      itemDetailApi.getItemDetailByItemCode({ ItemCode: 'Local' })
        .then(res => {
          _this.LocalList = res
        })
        .catch(err => {
          console.error(err)
        })
    },
    // 多选框回显
    change (index, item) {

    },
    // 获取字典表值班人员
    getPeople () {
      let _this = this
      PersonnelApi.getAllPersonnel({ current: 1, size: 999 })
        .then(res => {
          _this.PeopleList = res.records
        })
        .catch(err => {
          console.error(err)
        })
    },
    // 获取字典表课程时间段
    getDutyTime () {
      let _this = this
      itemDetailApi.getItemDetailByItemCode({ ItemCode: 'DutyTime' })
        .then(res => {
          _this.TimeList = res
        })
        .catch(err => {
          console.error(err)
        })
    },

    // 单元格、行选中
    cellclick (row, column, cell, event) {
      // 第3列开始可以选中
      // 单击单元格选中
      // 取消操作行选中
      if (cell.cellIndex >= columnNum) {
        return
      }
      if (cell.cellIndex >= fixRowHeadNum) {
        if (this.selectcell.get(row.Local + '_' + row.Time + '_' + column.property)) {
          this.selectcell.set(row.Local + '_' + row.Time + '_' + column.property, false)
        } else {
          this.selectcell.set(row.Local + '_' + row.Time + '_' + column.property, this.list[row.index])
        }
      }
      // 第三列之前选中整行
      // 行选中
      var currentcolumnindex = column.index
      if (cell.cellIndex < fixRowHeadNum) {
        for (var i = cell.cellIndex; i < columnNum - 1; i++) {
          currentcolumnindex = currentcolumnindex + 1
          var nextSibling = cell.nextSibling
          cell = nextSibling
          if (i >= fixRowHeadNum - 1) {
            if (this.selectcell.get(row.Local + '_' + row.Time + '_' + columnProperty[currentcolumnindex])) {
              this.selectcell.set(row.Local + '_' + row.Time + '_' + columnProperty[currentcolumnindex], false)
            } else {
              this.selectcell.set(row.Local + '_' + row.Time + '_' + columnProperty[currentcolumnindex], this.list[row.index])
            }
          }
        }
      }
      this.refresh = Math.random()
    },
    // 列选中
    headclick (column, event) {
      // 判断是否为可选列
      // 取消操作列选中
      if (column.index >= columnNum) {
        return
      }
      if (column.index > fixRowHeadNum - 1) {
        for (var i = 0; i < this.list.length; i++) {
          if (this.selectcell.get(this.list[i].Local + '_' + this.list[i].Time + '_' + column.property)) {
            this.selectcell.set(this.list[i].Local + '_' + this.list[i].Time + '_' + column.property, false)
          } else {
            this.selectcell.set(this.list[i].Local + '_' + this.list[i].Time + '_' + column.property, this.list[i])
          }
        }
      }
      this.refresh = Math.random()
    },
    // 选择值班人员
    personClick (person) {
      this.selectcell.forEach(function (value, key) {
        if (value) {
          var property = key.split('_')
          value[property[2]] = person
        }
      })
      this.selectcell = new Map()
    },
    // 更新背景
    cellBg ({ row, column, rowIndex, columnIndex }) {
      row.index = rowIndex
      column.index = columnIndex
      let _this = this
      // 注意这里是解构
      // 利用单元格的 className 的回调方法，给行列索引赋值

      if (_this.selectcell.get(row.Local + '_' + row.Time + '_' + column.property)) {
        return 'selectedCell'
      }
    },
    // 匹配学期
    formatTerm (row, column) {
      for (var i = 0; i < this.termList.length; i++) {
        if (parseInt(this.termList[i].ItemValue) === parseInt(row.Term)) {
          return this.termList[i].ItemName
        }
      }
    },
    // 获取学期名称
    getTerm () {
      let _this = this
      _this.termList.forEach(function (value, key) {
        if (_this.dutyDetail.Term == value.ItemValue) {
          _this.termName = value.ItemName
        }
      })
    },
    formatPerson (row, column, cellValue, index) {
      let label = '休息'
      for (var i = 0; i < this.PeopleList.length; i++) {
        if (this.PeopleList[i].Id == cellValue) {
          return this.PeopleList[i].PersonnelName
        }
      }
      return label
    },
    formatLocal (row, column, cellValue, index) {
      for (var i = 0; i < this.LocalList.length; i++) {
        if (this.LocalList[i].ItemValue == cellValue) {
          return this.LocalList[i].ItemName
        }
      }
    },
    formatTime (row, column, cellValue, index) {
      for (var i = 0; i < this.TimeList.length; i++) {
        if (this.TimeList[i].ItemValue == cellValue) {
          return this.TimeList[i].ItemName
        }
      }
    },
    // 关闭页面
    ...mapActions('d2admin/page', [
      'close_return'
    ]),
    // 关闭
    back () {
      this.close_return({
        tagName: this.$route.fullPath,
        returnTagName: '/duty'
      })
    }
  }
}
</script>
<style>
.selectedCell {
  transition: background-color 2s;
  -webkit-transition: background-color 2s; /* Safari */
  background-color: green !important;
  color: white;
}
</style>
