<template>
  <el-dialog title="新增值班表"
             :visible.sync="dialogvisible"
             width="80%"
             :before-close="handleCloseAdd">
    <el-form size="mini"
             :model="testlistform"
             :rules="rulestestlistform"
             label-width="100px"
             ref="testlistform">
      <el-row :gutter="20"
              class="donorsaddformcss">
        <el-col :span="8">
          <el-form-item label="学年"
                        prop="Year"
                        label-width="120px">
            <el-select ref="reftube"
                       v-model="testlistform.Year"
                       placeholder="请选择学年"
                       style="width:100%">
              <el-option v-for="item in years"
                         :key="item.value"
                         :label="item.label"
                         :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="学期"
                        prop="Term"
                        label-width="120px">
            <el-input v-model="testlistform.Term"
                      placeholder="请输入"
                      style="width:100%"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="地点"
                        label-width="120px">
            <el-checkbox :indeterminate="isIndeterminate"
                         v-model="checkAll"
                         @change="handleCheckAllChange">全选</el-checkbox>
            <div style="margin: 15px 0;"></div>
            <el-checkbox-group v-model="checkedCities"
                               @change="handleCheckedCitiesChange">
              <el-checkbox v-for="city in cities"
                           :label="city"
                           :key="city">{{city}}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="值班人员"
                        label-width="120px">
            <el-checkbox v-model="checked1"
                         label="张三"
                         border></el-checkbox>
            <el-checkbox v-model="checked2"
                         label="李四"
                         border></el-checkbox>
          </el-form-item>
        </el-col>
      </el-row>
      <template>
        <ag-grid-vue class="table ag-theme-balham"
                     style="width: 100%; height: 335px;"
                     id="grid1"
                     :gridOptions="gridOptions"
                     :columnDefs="columnDefs"
                     :rowData="rowData"
                     @gridReady="onGridReady">
        </ag-grid-vue>
      </template>

    </el-form>

    <span slot="footer">
      <el-button size="mini"
                 type="primary"
                 @click="savedata()">保存</el-button>
      <el-button size="mini"
                 @click="handleCloseAdd">关闭</el-button>
    </span>
  </el-dialog>
</template>

<script>
const cityOptions = ['计算机楼', '主楼', '科技楼'];
import DutyApi from '@/api/duty'
import axios from 'axios'
import { AgGridVue } from 'ag-grid-vue'
import uploadajax from '@/assets/js/uploadajax.js'
export default {
  name: 'dutyadd',
  components: { AgGridVue },
  data () {
    return {
      // ag-grid相关变量
      gridOptions: null,
      gridApi: null,
      columnApi: null,
      columnDefs: null,
      defaultColDef: null,
      rowData: [{
        Local: '计算机楼',
        Time: '8：00-10：00',
        Monday: '',
        Tuesday: '',
        Wednesday: '',
        Thursday: '',
        Friday: '',
        Saturday: '',
        Sunday: ''
      },
      {
        Local: '',
        Time: '',
        Monday: '',
        Tuesday: '',
        Wednesday: '',
        Thursday: '',
        Friday: '',
        Saturday: '',
        Sunday: ''
      },
      {
        Local: '',
        Time: '',
        Monday: '',
        Tuesday: '',
        Wednesday: '',
        Thursday: '',
        Friday: '',
        Saturday: '',
        Sunday: ''
      },
      {
        Local: '',
        Time: '',
        Monday: '',
        Tuesday: '',
        Wednesday: '',
        Thursday: '',
        Friday: '',
        Saturday: '',
        Sunday: ''
      },
      {
        Local: '',
        Time: '',
        Monday: '',
        Tuesday: '',
        Wednesday: '',
        Thursday: '',
        Friday: '',
        Saturday: '',
        Sunday: ''
      },
      {
        Local: '',
        Time: '',
        Monday: '',
        Tuesday: '',
        Wednesday: '',
        Thursday: '',
        Friday: '',
        Saturday: '',
        Sunday: ''
      }],
      prenum: '',
      multipleSelection: [],
      //详细list
      tableData: [],
      Local: '',
      Time: '',
      checkedDetail: [],
      checked1: '',
      checked2: '',
      checkAll: false,
      checkedCities: ['上海', '北京'],
      cities: cityOptions,
      isIndeterminate: true,
      years: [],
      form: {
        recentYear: ''
      },
      fileList: [],
      FileUrl: {},
      uploadFile: {},
      dialogvisible: false,
      formtype: '1',
      disabledbarcode: false,
      testlistform: {
        Term: '',
        Year: '',
        Classification: '',
        Responsible: '',
        State: 1,
        Remarks: '',
        CalibrationDeadlineType: 3,
        CalibrationTime: new Date(),
        CalibrationDeadline: 1,
        HeartbeatTime: new Date(),
        TimeNotification: 0,
        MaintenCycle: 1,
        CycleType: 3

      },
      Advancetime: 0,
      triggerlist: {},
      TimeNotification: false, // 有效期提醒
      classificationlist: [],
      getsupplierlist: [],

      rulestestlistform: {

        Code: [{
          required: true,
          message: '请输入设备编码',
          trigger: 'blur'
        }],
        Name: [{
          required: true,
          message: '请输入设备名称',
          trigger: 'blur'
        }]
      }
    }
  },
  beforeMount () {
    this.gridOptions = {
      rowHeight: 32, // 设置行高为32px
      // 缺省列属性
      defaultColDef: {
        width: 200,
        resizable: true,
        editable: true,//单元表格是否可编辑
      },
      // onCellEditingStopped: this.changesq,
      onCellClicked: this.changeClick,
      onRowSelected: this.handleSelectionChange, // 行选中
      onSortChanged: this.handleSortChange // 排序传递后台
    }
    this.columnDefs = [
      {
        headerName: '地点', field: 'Local'
      },
      {
        headerName: '时间段', field: 'Time'
      },
      {
        headerName: '周一', field: 'Monday'
      },
      {
        headerName: '周二', field: 'Tuesday'
      },
      {
        headerName: '周三', field: 'Wednesday'
      },
      {
        headerName: '周四', field: 'Thursday'
      },
      {
        headerName: '周五', field: 'Friday'
      },
      {
        headerName: '周六', field: 'Saturday'
      },
      {
        headerName: '周日', field: 'Sunday'
      }
    ]

  },
  created () {
    this.init()
  },
  mounted () {
    this.gridOptions.context = { page: this }
    this.gridApi = this.gridOptions.api
    this.gridColumnApi = this.gridOptions.columnApi
    this.doRefresh()
  },
  methods: {
    // 表格就绪后后执行
    onGridReady (params) {
      // 调整表格列宽大小自适应
      this.gridApi.sizeColumnsToFit()
    },
    handleSortChange (val) {
      var sortState = this.gridApi.getSortModel()
      // 获取排序的字段
      if (sortState && sortState.length > 0) {
        var item = sortState[0]
        this.sort.prop = item.colId
        this.sort.order = item.sort
      }
      this.doRefresh()
    },
    //单选框选中数据
    handleDetailSelectionChange (selection) {
      if (selection.length > 1) {
        this.$refs.multipleTable.clearSelection();
        this.$refs.multipleTable.toggleRowSelection(selection.pop());
      } else {
        this.checkedDetail = selection;
      }
    },
    // 表格就绪后后执行
    onGridReady (params) {
      this.gridApi = params.api
      this.columnApi = params.columnApi
      // 调整表格列宽大小自适应
      this.gridApi.sizeColumnsToFit()
    },
    // 选择
    changeClick (event) {
      // 判断是否选取的是ABCDEFGH列
      // if (event.colDef.field === 'k') {
      var _this = this
      var rowNode = this.gridOptions.api.getRowNode(event.rowIndex)
      var rows = JSON.parse(JSON.stringify(rowNode.data))
      var headerArr = ['Local', 'Time', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
      headerArr.forEach(function (key, num) {
        if (rows[key]) {
          var evRow = event.rowIndex + 1
          var evNum = num + 1
          var ev = evRow.toString() + evNum.toString()
          var rowsNodeArray = rows[key].split(',')
          // 如果是黄色则变为绿色
          // 黄色
          if (rowsNodeArray.length < 4) {
            if (rowsNodeArray[1] === '0') {
              // 变为绿色
              rowNode.data[key] = rowsNodeArray[0] + ',1,' + rowsNodeArray[2]
              // 加入数组
              _this.tableNum[ev] = event.rowIndex
              _this.tableField[ev] = key
            } else if (rowsNodeArray[1] === '1') {
              // 绿色则改成黄色，并从数组清空数值
              rowNode.data[key] = rowsNodeArray[0] + ',0,' + rowsNodeArray[2]
              _this.tableNum[ev] = ''
              _this.tableField[ev] = ''
            }
          }
        }
      })
      // 刷新表格
      // this.refreshAll()
      // }

      // 获取单元格颜色
      var span = 0
      var nowColor = event.event.toElement.style.backgroundColor
      if (!nowColor) {
        span = 1
        // 点击到了<span>文本上
        nowColor = event.event.toElement.parentElement.style.backgroundColor
      }

      // 判断是否有数据
      if (nowColor !== 'rgb(0, 255, 0)' && nowColor !== 'yellow') {
        //   return false
      }
      var evArray = event.value.split(',')
      if (evArray[1] != 0 && evArray[1] != 1 && evArray.length > 3) {
        return false
      }
      if (evArray.length < 4) {
        // 根据颜色存入数组，列值，单元格值
        var evNum = event.rowIndex + 1
        var ev = evNum + event.colDef.headerName
        var eventArray = event.value.split(',')
        if (nowColor === 'rgb(0, 255, 0)') {
          this.nowclick.set(event.rowIndex.toString() + event.colDef.headerName, eventArray[2])
          // event.event.toElement.parentElement.style.backgroundColor = 'yellow'
          this.tableNum[ev] = ''
          this.tableField[ev] = ''
          if (span === 0) {
            event.event.toElement.style.backgroundColor = 'yellow'
          } else {
            event.event.toElement.parentElement.style.backgroundColor = 'yellow'
          }
          // 当点击改变为黄色时候，赋值，0
          event.data[event.colDef.field] = eventArray[0] + ',0,' + eventArray[2]
        } else if (nowColor === 'yellow') {
          this.nowclick.set(event.rowIndex.toString() + event.colDef.headerName, eventArray[2])
          this.tableNum[ev] = event.rowIndex
          this.tableField[ev] = event.colDef.field
          if (span === 0) {
            event.event.toElement.style.backgroundColor = '#00FF00'
          } else {
            event.event.toElement.parentElement.style.backgroundColor = '#FF0000'
          }
          event.data[event.colDef.field] = eventArray[0] + ',1,' + eventArray[2]
        }
      }
    },
    // 获取孔号详情
    getHoleInfoP () {
      let _this = this
      _this.rowData = []
      // 传入后台获取第一板的内容
      let params = {
        boardid: _this.mainBoardForm.Id
      }
      BoardApi.getHolePre(params)
        .then(res => {
          _this.rowData = res
          for (let row of _this.rowData) {
            let headerArr = ['Local', 'Time', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
            headerArr.forEach(function (key, num) {
              let rowarr = row[key].split(',')
              if (row[key] != '' && rowarr.length >= 3) {
                _this.samids.push(rowarr[2])
              }
            })
          }
          this.getIsQuick()
        })
    },
    // 处理列表选择
    handleSelectionChange () {
      let _this = this
      _this.multipleSelection = _this.gridOptions.api.getSelectedRows()
      _this.deleteBtnVisible = !_this.multipleSelection || _this.multipleSelection.length === 0
      if (!_this.deleteBtnVisible) {
        _this.deleteIds = []
        // 赋值删除id列表
        _this.multipleSelection.forEach((item, k) => {
          _this.deleteIds.push(item.Id)
        })
      } else {
        _this.deleteIds = []
      }
    },
    // 列表选择
    handle (row, column, event, cell) {
      console.log(row)
      console.log(column)
      console.log(event)
      console.log(cell)
    },
    // 学校地点多选框
    handleCheckAllChange (val) {
      this.checkedCities = val ? cityOptions : [];
      this.isIndeterminate = false;
    },
    // 学校地点多选框
    handleCheckedCitiesChange (value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.cities.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.cities.length;
    },
    init () {
      var myDate = new Date;
      var year = myDate.getFullYear();//获取当前年
      this.initSelectYear(year)
      this.form.recentYear = year;
    },
    initSelectYear (year) {
      this.years = [];
      for (let i = 0; i < 30; i++) {
        this.years.push({ value: (year - i), label: (year - i) + "年" });
      }
    },
    yearChange (value) {
      this.form.recentYear = value
    },

    //  保存新增班级信息
    savedata () {
      DutyApi.addduty(this.testlistform, {})
        .then(res => {
          // response
          this.$emit('closeAddDialog')
          this.dialogvisible = false
          this.fileList = []
          // 刷新
        })
        .catch(err => {
          // handle error
          console.error(err)
        })
    },
    refreshData () {
      this.$emit('refreshData')
    },
    closedialog () {
      this.dialogvisible = false
    },
    handleCloseAdd () {
      this.$refs['testlistform'].resetFields()
      // this.$refs['uploader'].clearFiles()
      this.testlistform.Code = ''
      this.testlistform.Name = ''
      this.testlistform.Brand = ''
      this.testlistform.SupplierId = ''
      this.testlistform.FactoryNum = ''
      this.testlistform.Responsible = ''
      this.testlistform.CalibrationDeadline = 1
      this.testlistform.MaintenCycle = 1
      this.testlistform.Model = ''
      this.testlistform.Remarks = ''
      this.testlistform.Classification = ''
      this.$emit('closeAddDialog')
    },

    // 计算日期
    addDate (date, days) {
      if (days === undefined || days === '') {
        days = 1
      }
      var dates = new Date(date)
      dates.setDate(dates.getDate() + days)
      var month = dates.getMonth() + 1
      var day = dates.getDate()
      var mm = "'" + month + "'"
      var dd = "'" + day + "'"

      // 单位数前面加0
      if (mm.length === 3) {
        month = '0' + month
      }
      if (dd.length === 3) {
        day = '0' + day
      }

      var time = dates.getFullYear() + '-' + month + '-' + day
      return time
    }
  }
}

</script>

<style lang="scss">
.button {
  padding: 0;
  float: right;
}

.donorsaddformcss .el-col-8 {
  height: 58px;
}
</style>
