<template>
  <d2-container>
    <template slot="header"
              style="padding: 5px;">
      <el-form :model="dutyDetail"
               label-width="100px">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="标题"
                          label-width="120px">
              {{dutyDetail.Title}}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="学年"
                          label-width="120px">
              {{dutyDetail.Year}}年
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="学期"
                          label-width="120px">
              {{this.termName}}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="值班人员"
                          size="mini"
                          label-width="120px">
              <el-tag @click="personClick(item.ItemValue)"
                      v-for="item in PeopleList"
                      :key="item.ItemValue"
                      :label="item.ItemValue">{{item.ItemName}}</el-tag>
            </el-form-item>

          </el-col>
          <el-col :span="8">
            <el-form-item label="地点"
                          size="mini"
                          label-width="120px">
              <el-checkbox-group v-model="selectLocal">
                <el-checkbox v-for="item in LocalList"
                             :label="item.ItemValue"
                             :key="item.ItemValue">{{item.ItemName}}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="值班时间"
                          size="mini"
                          label-width="120px">
              <el-checkbox-group v-model="selectTime">
                <el-checkbox v-for="item in TimeList"
                             :label="item.ItemValue"
                             :key="item.ItemValue">{{item.ItemName}}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-button size="mini"
                   @click="addList()"
                   type="success"
                   style="margin-right:6px">生成表格</el-button>
        <el-button size="mini"
                   type="primary"
                   style="margin-left:10px"
                   @click="addDuytDetail()">保存</el-button>
        <el-button size="mini"
                   style="margin-right:6px"
                   @click="closeWindow()">关闭</el-button>
      </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">
      <el-table-column label="操作"
                       width="180px"
                       align="center"
                       fixed='right'>
        <template slot-scope="scope">
          <el-button size="mini"
                     type="danger"
                     title="删除"
                     @click="deleteRow(scope.row.Id)"
                     style="margin-left:5px;"
                     icon="el-icon-delete"
                     circle></el-button>
        </template>
      </el-table-column>
      <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>
  </d2-container>
</template>
<script>
// 总列数
const columnNum = 9
// 固定列数
const fixRowHeadNum = 2
// todo 欠优化 列属性对应
const columnProperty = [
  'Local',
  'Time',
  'Monday',
  'Tuesday',
  'Wednesday',
  'Thursday',
  'Friday',
  'Saturday',
  'Sunday'
]
import DutyApi from '@/api/duty'
import itemDetailApi from '@/api/sysadmin/itemdetail'
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: []
    }
  },
  created () {
    this.init()
  },
  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: {
    // 获取值班子表表格
    getDetailData () {
      let _this = this
      DutyApi.getDetailByDutyId({
        DutyId: _this.dutyDetail.Id
      }).then(res => {
        if (res.length > 0) {
          _this.list = res
        }

      })
    },
    // 新增表格
    addList () {
      if (this.selectLocal == 0 && this.selectTime.length == 0) {
        return
      }
      this.list = []
      this.selectcell = new Map()
      let _this = this
      this.selectLocal.forEach(function (value, key) {
        _this.selectTime.forEach(function (valuee, keyy) {
          _this.list.push({
            DutyId: _this.dutyDetail.Id,
            Local: value,
            Time: valuee,
            Monday: 0,
            Tuesday: 0,
            Wednesday: 0,
            Thursday: 0,
            Friday: 0,
            Saturday: 0,
            Sunday: 0
          })
        })
      })
    },
    // 保存值班子表信息
    addDuytDetail () {
      let _this = this
      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 () {
      let val = this.selectcell
      if (val) {
        val.forEach((val, index) => {
          this.list.forEach((v, i) => {
            if (val.index === v.index) {
              this.list.splice(i, 1)
            }
          })
        })
      }

    },
    // 获取字典表地点
    getLocal () {
      let _this = this
      itemDetailApi.getItemDetailByItemCode({ ItemCode: 'Local' })
        .then(res => {
          _this.LocalList = res
        })
        .catch(err => {
          console.error(err)
        })
    },
    // 获取字典表值班人员
    getPeople () {
      let _this = this
      itemDetailApi.getItemDetailByItemCode({ ItemCode: 'People' })
        .then(res => {
          _this.PeopleList = res
        })
        .catch(err => {
          console.error(err)
        })
    },
    // 获取字典表课程时间段
    getDutyTime () {
      let _this = this
      itemDetailApi.getItemDetailByItemCode({ ItemCode: 'DutyTime' })
        .then(res => {
          _this.TimeList = res
        })
        .catch(err => {
          console.error(err)
        })
    },
    // 获取本年年份
    init () {
      var myDate = new Date()
      var year = myDate.getFullYear()// 获取当前年
      this.initSelectYear(year)
    },
    // 循环遍历年份
    initSelectYear (year) {
      this.years = []
      for (let i = 0; i < 5; i++) {
        this.years.push({ value: (year - i), label: (year - i) + '年' })
      }
    },
    // 单元格、行选中
    cellclick (row, column, cell, event) {
      // 第3列开始可以选中
      // 单击单元格选中
      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 > 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 termName = ''
      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].ItemValue == cellValue) {
          return this.PeopleList[i].ItemName
        }
      }
      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
        }
      }
    },
    // 关闭当前页
    closeWindow () {
      window.location.href = "./#/duty";
    }
  }
}
</script>
<style>
.selectedCell {
  background-color: green !important;
  color: white;
}
</style>
