<!--校秤时间配置-->
<template>
  <div class="systemBase">
    <div>
      <el-row>
        <el-col :span="10">
          <div class="common-title-div">计量点数据
          </div>
          <div class="common-table-div">
            <el-table ref="dataTable" border :height="tableHeight" highlight-current-row @selection-change="handleSelectionChange"
              :data="table.list2" :icore-filter-flag="icoreFilterFlag" @row-click="getDataList3">
              <el-table-column type="index" label="序号" fixed="left" align="center"></el-table-column>
              <el-table-column type="selection" width="55" align="center"></el-table-column>
              <el-table-column sortable min-width="120px" :show-overflow-tooltip="true" prop="baseSpotNo" label="计量点编号" align="center"></el-table-column>
              <el-table-column sortable min-width="120px" :show-overflow-tooltip="true" prop="baseSpotName" label="计量点名称" align="center"></el-table-column>
              <el-table-column sortable min-width="120px" :show-overflow-tooltip="true" prop="spotTypeName" label="计量点类型" align="center"></el-table-column>
            </el-table>
          </div>
          <div class="common-foot-style">
             <el-pagination v-loading="dataLoading" @size-change="pageSizeChange1" @current-change="pageCurrentChange1"
              :current-page="page1.pageNum" :page-sizes="[100, 500, 1000]" :page-size="page1.pageSize" layout="total, sizes, prev, pager, next, jumper"
              :total="page1.totalPage">
            </el-pagination>
          </div>
        </el-col>
        <el-col :span="14">
          <div class="common-title-div" style="height: 45px;">
            <div class="common-operation-button-div">
              <el-button size="mini" type="primary" icon="el-icon-circle-plus-outline" v-loading.fullscreen.lock="operateLoading"
              @click="selectData" v-privilege="activeMenu + 'ADD'">新增</el-button>
              <!-- <el-button icon="el-icon-edit" type="primary" size="mini">修改</el-button> -->
              <el-button size="mini" type="danger" plain icon="el-icon-delete"
              @click="deleteData2" v-privilege="activeMenu + 'DELETE'">删除</el-button>
              <!-- <el-button icon="el-icon-delete" type="primary" size="mini">取消</el-button> -->
            </div>
          </div>
          <div class="common-table-div">
            <el-table ref="dataTable2" border :height="tableHeight" highlight-current-row @selection-change="handleSelectionChange2"
              :data="table.list3" :exchangeFilterMap="{'calibrationTimeUnit':{'1':'小时','0':'天'}}"
              :icore-filter-flag="icoreFilterFlag">
              <el-table-column type="index" label="序号" fixed="left" align="center"></el-table-column>
              <el-table-column type="selection" width="55" align="center"></el-table-column>
              <el-table-column min-width="120px" sortable :show-overflow-tooltip="true" prop="baseSpotName" label="计量点名称" align="center"></el-table-column>
              <el-table-column min-width="80px" sortable :show-overflow-tooltip="true" prop="calibrationTimeUnit" label="时间单位" align="center">
                <template slot-scope="scope">
                   <span v-if="scope.row.calibrationTimeUnit == 1">小时</span>
                   <span v-else-if="scope.row.calibrationTimeUnit == 0">天</span>
                </template>
              </el-table-column>
              <el-table-column sortable min-width="160px" :show-overflow-tooltip="true" prop="startTime1" label="开始时间" align="center"></el-table-column>
              <el-table-column sortable min-width="160px" :show-overflow-tooltip="true" prop="endTime1" label="结束时间" align="center"></el-table-column>
              <el-table-column sortable min-width="80px" :show-overflow-tooltip="true" prop="dayNum" label="天数/小时" width="80px" align="center"></el-table-column>
              <el-table-column sortable min-width="80px" :show-overflow-tooltip="true" prop="calibrationTypeName" label="校秤类型" width="80px" align="center"></el-table-column>
            </el-table>
          </div>
          <div class="common-foot-style">
            <el-pagination v-loading="dataLoading" @size-change="pageSizeChange2" @current-change="pageCurrentChange2"
              :current-page="page2.pageNum" :page-sizes="[100, 500, 1000]" :page-size="page2.pageSize" layout="total, sizes, prev, pager, next, jumper"
              :total="page2.totalPage">
            </el-pagination>
          </div>
        </el-col>
      </el-row>
      <div class="lineDiv" v-if="detailData" style="border-bottom: 1px solid #DCDCDC;height:5px" ref="lineDiv"></div>
      <div class="common-title-div">校称时间
        <div class="common-operation-button-div">
          <el-button icon="el-icon-circle-plus-outline" type="primary" size="mini" v-loading.fullscreen.lock="operateLoading"
           @click="addData" v-privilege="activeMenu + 'ADD2'">新增</el-button>
          <el-button icon="el-icon-edit" type="primary" size="mini" v-loading.fullscreen.lock="operateLoading"
          @click="modifyData" v-privilege="activeMenu + 'UPDATE2'">修改</el-button>
          <el-button size="mini" type="danger" plain icon="el-icon-delete"
          @click="deleteData" v-privilege="activeMenu + 'DELETE2'">删除</el-button>
        </div>
      </div>
      <div class="common-table-div">
         <el-table v-loading="dataLoading" @row-click="rowChange" ref="dataTable3"
          border :height="tableHeight"  @selection-change="handleSelectionChange3" :data="table.list" highlight-current-row
          :exchangeFilterMap="{'calibrationTimeUnit':{'1':'小时','0':'天'}}"
          :icore-filter-flag="icoreFilterFlag">
          <el-table-column type="index" label="序号" fixed="left" align="center"></el-table-column>
          <el-table-column type="selection" width="55" align="center"></el-table-column>
          <el-table-column sortable min-width="120px" :show-overflow-tooltip="true" prop="calibrationTimeNo" label="时间编号" align="center"></el-table-column>
          <el-table-column sortable min-width="80px" :show-overflow-tooltip="true" prop="calibrationTimeUnit"  label="时间单位" align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.calibrationTimeUnit == 1">小时</span>
              <span v-else-if="scope.row.calibrationTimeUnit == 0">天</span>
            </template>
          </el-table-column>
          <el-table-column sortable min-width="160px" :show-overflow-tooltip="true" prop="startTime1" label="开始时间" align="center"></el-table-column>
          <el-table-column sortable min-width="160px" :show-overflow-tooltip="true" prop="endTime1" label="结束时间" align="center"></el-table-column>
          <el-table-column sortable min-width="80px" :show-overflow-tooltip="true" prop="dayNum"  label="天数/小时" align="center"></el-table-column>
          <el-table-column sortable min-width="80px" :show-overflow-tooltip="true" prop="calibrationTypeName"  label="校秤类型" align="center"></el-table-column>
          <el-table-column sortable min-width="80px" :show-overflow-tooltip="true" prop="createManName"  label="创建人" align="center"></el-table-column>
          <el-table-column sortable min-width="160px" :show-overflow-tooltip="true" prop="createTime" label="创建时间" align="center"></el-table-column>
          <el-table-column sortable min-width="80px" :show-overflow-tooltip="true" prop="updateManName"  label="修改人" align="center"></el-table-column>
          <el-table-column sortable min-width="160px" :show-overflow-tooltip="true" prop="updateTime" label="修改时间" align="center"></el-table-column>
        </el-table>
      </div>
      <div class="common-foot-style">
        <el-pagination v-loading="dataLoading" @size-change="pageSizeChange" @current-change="pageCurrentChange"
          :current-page="page.pageNum" :page-sizes="[100, 500, 1000]" :page-size="page.pageSize" layout="total, sizes, prev, pager, next, jumper"
          :total="page.totalPage">
        </el-pagination>
      </div>
      <div ref="editTitle" class="common-title-div" style="border-top: 1px solid #d5d5d5;">校称时间编辑区
      </div>
      <div ref="editDiv" class="commom-edit-div">
         <el-form ref="baseData" label-width="80px" :inline="true" :rules="ruleValidate" :model="baseData">
              <el-form-item label="时间单位">
                 <el-select v-model="calibrationTimeUnitIndex" filterable collapse-tags size="small" style="width:120px" @change="selectTrigger(calibrationTimeUnitIndex)">
                  <el-option v-for="(item,index) in calibrationTimeUnit" :key="index" :label="item.name" :value="index">
                  </el-option>
                </el-select>
              </el-form-item>
               <el-form-item prop="dayNum" label="天数/小时">
                <el-input v-model="baseData.dayNum" size="small" clearable style="width:120px" placeholder="请输入天数/小时" @change="onChangeInput(baseData.dayNum)"></el-input>
              </el-form-item>
              <el-form-item prop="startTime" label="开始时间">
                <el-time-picker size="small" v-model="baseData.startTime" clearable @change="onChangeStartTime" style="width:120px" :readonly="isDay" :disabled="isDay">
                </el-time-picker>
                <!-- <el-date-picker type="datetime" v-model="baseData.startTime" size="small" @change="onChangeStartTime">
                </el-date-picker> -->
              </el-form-item>
              <el-form-item prop="endTime" label="结束时间">
                <el-time-picker size="small" v-model="baseData.endTime" clearable style="width:120px" readonly :disabled="isDay">
                </el-time-picker>
                <!-- <el-date-picker type="datetime" v-model="baseData.endTime" readonly size="small">
                </el-date-picker> -->
              </el-form-item>
              <el-form-item label="校秤类型">
                 <el-select v-model="baseData.calibrationTypeNo" filterable collapse-tags size="small" style="width:120px">
                  <el-option v-for="(item,index) in calibrationType" :key="index" :label="item.baseName" :value="item.baseCode">
                  </el-option>
                </el-select>
              </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>
<script>
 import {
    formatDate
  } from '@/utils/util.js';
  import {
    meterbasecalibrationtimes,
    meterbasespotinfos,
    meterbasecalibrarelations,
    combaseinfos
  } from '../../../utils/api.js';
  import {
    add,
    modify,
    Delete,
    DeleteOne,
    RecoveryOne,
    discardOne
  } from '../../../utils/httpRequest.js';
  import pinyinUtils from '../../../utils/pinyin/pinyinUtils.js'
  import { momentImmutableMethods } from 'moment-immutable-methods'
  import moment from 'moment'
  momentImmutableMethods(moment)
  export default {
    data () {
      return {
        dataLoading: false,
        operateLoading: false,
        calibrationTimeUnitIndex: 0,
        icoreFilterFlag: true,
        isDay: true,
        baseData: {
          startTime: '',
          endTime: '',
          dayNum: '',
          calibrationTypeNo: ''
        },
        page: {
          pageSize: 500,
          pageNum: 1,
          totalPage: 0
        },
        page1: {
          pageSize: 500,
          pageNum: 1,
          totalPage: 0
        },
        page2: {
          pageSize: 500,
          pageNum: 1,
          totalPage: 0
        },
        table: {
          list: [],
          list2: [],
          list3: []
        },
        calibrationType: [],
        calibrationTimeUnit: [
          {id: '0', name: '天'},
          {id: '1', name: '小时'}
        ],
        multipleSelection: [],
        multipleSelection1: [],
        multipleSelection2: [],
        multipleSelection3: [],
        firstRow: '',
        tableHeight: 0,
        ruleValidate: {
          startTime: [{
            required: false,
            // message: '开始时间不能为空',
            validator: this.startTimeVerify, 
            trigger: 'blur'
          }],
          endTime: [{
            required: false,
            // message: '结束时间不能为空',
            validator: this.endTimeVerify, 
            trigger: 'blur'
          }],
          dayNum: [{
            required: true,
            message: '天数/小时不能为空',
            trigger: 'change'
          }]
        },
        detailData: true,
        activeMenu: ''
      }
    },
    created(){
      this.tableHeight = (window.innerHeight - 320)/2 > 200 ? (window.innerHeight - 320)/2 : 200;
      this.activeMenu = window.top.localStorage.getItem('activeMenu')
    },
    mounted () {
      // this.tableHeight = this.getTableHeight(this.$refs['dataTable'].$el) - 80;
      this.getDataList();
      this.getDataList2();
      // this.getDataList3();
      this.getCalibrationType()
      this.changeTableHeigh()
    },
    methods: {
       getCode (code, arr, codeKey, nameKey) {
       if (!code) {
         return '';
       }
       let targetRow = arr.find(item => {
         return item[codeKey] === code;
       });
       return targetRow ? targetRow[nameKey] : '';
     },
     changeTableHeigh () {
       var tableDiv = this.$refs.dataTable.$el
       var tableDiv2 = this.$refs.dataTable2.$el
       var dtable = this.$refs.dataTable3.$el
       var oDiv = this.$refs.lineDiv
       oDiv.onmousedown = function(ev){
       var theight = parseInt(tableDiv.offsetHeight)
       var theight2 = parseInt(tableDiv2.offsetHeight)//parseInt为了不指向对象
       var dheight = parseInt(dtable.offsetHeight)
       oDiv.style.cursor = 's-resize'
       var ev = ev || event;
       //鼠标按下坐标
       var mouseDownX = ev.clientX;
       var mouseDownY = ev.clientY;
       // IE8 取消默认行为-设置全局捕获
       if(oDiv.setCapture){
       oDiv.setCapture();
       }
       document.onmousemove = function(ev){
       var ev = ev || event;
       // 鼠标移动时的鼠标位置
       var mouseMoveX = ev.clientX;
       var mouseMoveY = ev.clientY;
       tableDiv.style.height = theight+(mouseMoveY-mouseDownY)+"px"
       tableDiv2.style.height = theight2+(mouseMoveY-mouseDownY)+"px"
       dtable.style.height = dheight +(mouseDownY-mouseMoveY)+"px"
       }
       }
       document.onmouseup = function(){
       document.onmousemove = null;
       // 释放全局捕获
       if(oDiv.releaseCapture){
       oDiv.releaseCapture();
       }
       }
       return false;
      },
      rowChange (row, column, event) {
        let row1 = Object.assign ({}, row)
        this.baseData = row1;
        // for (var i = 0; i < this.calibrationType.length; i++) {
        //   if (this.calibrationType[i].baseCode === this.baseData.calibrationTypeNo) {
        //     this.calibrationTypeIndex = i;
        //   }
        // }
        this.calibrationTimeUnitIndex = this.baseData.calibrationTimeUnit === '0' ? 0 : 1
        if (row.calibrationTimeUnit === '0') {
          this.isDay = true
          this.ruleValidate.startTime[0].required = false
          this.ruleValidate.endTime[0].required = false
        } else {
          this.isDay = false
          this.ruleValidate.startTime[0].required = true
          this.ruleValidate.endTime[0].required = true
        }
      },
      startTimeVerify (rule, value, callback) {
        if (this.calibrationTimeUnitIndex === 1 && this.baseData.startTime === '') {
	            callback(new Error('开始时间不能为空！'));
	        } else {
	          callback();
          }
      },
      endTimeVerify (rule, value, callback) {
        if (this.calibrationTimeUnitIndex === 1 && this.baseData.endTime === '') {
	            callback(new Error('结束时间不能为空！'));
	        } else {
	          callback();
          }
      },
      onChangeInput(e){
      e = Number(e)
      var startTime = this.baseData.startTime;
      if (this.calibrationTimeUnitIndex ===0) {
        this.isDay = true
        //  this.baseData.endTime = moment(this.baseData.startTime).add('days',e);
      } else {
         this.baseData.endTime = moment(this.baseData.startTime).add('hours',e);
         this.isDay = false
      } 
     },
     selectTrigger(calibrationTimeUnitIndex) {
        var e = Number(this.baseData.dayNum)
        var startTime = this.baseData.startTime;
        if (e!=='' || e!== null) {
          if (calibrationTimeUnitIndex === 0) {
            this.isDay = true
            this.baseData.endTime = ''
            this.baseData.startTime = ''
            this.ruleValidate.startTime[0].required = false
            this.ruleValidate.endTime[0].required = false
          //  this.baseData.endTime = moment(this.baseData.startTime).add('days',e);
          } else {
           this.baseData.endTime = moment(this.baseData.startTime).add('hours',e);
           this.isDay = false
           this.ruleValidate.startTime[0].required = true
           this.ruleValidate.endTime[0].required = true
          } 
        } else {
          return 
        }
     },
     onChangeStartTime() {
      var e = Number(this.baseData.dayNum)
       var startTime = this.baseData.startTime;
       if (e!=='' || e!== null) {
         if (this.calibrationTimeUnitIndex ===0) {
          this.baseData.endTime = moment(this.baseData.startTime).add('days',e);
         } else {
          this.baseData.endTime = moment(this.baseData.startTime).add('hours',e);
         } 
       } else {
         return 
       }
     },
    addData () {
        let _this = this;
        _this.$refs['baseData'].validate((valid) => {
          if (valid) {
            _this.operateLoading = true;
            let baseDataAdd = {};
            baseDataAdd.startTime = _this.baseData.startTime;
            baseDataAdd.endTime = _this.baseData.endTime;
            baseDataAdd.dayNum = _this.baseData.dayNum;
            baseDataAdd.calibrationTypeNo = _this.baseData.calibrationTypeNo;
            baseDataAdd.calibrationTypeName =  _this.getCode (this.baseData.calibrationTypeNo, this.calibrationType, 'baseCode', 'baseName')
            // _this.baseData.calibrationTimeUnitNo = _this.calibrationTimeUnit[_this.calibrationTimeUnitIndex].id;
            baseDataAdd.calibrationTimeUnit = _this.calibrationTimeUnit[_this.calibrationTimeUnitIndex].id;
            add(meterbasecalibrationtimes, baseDataAdd, (e) => {
              _this.operateLoading = false;
              _this.getDataList();
              if (!e) {
                _this.$refs['baseData'].resetFields && _this.$refs['baseData'].resetFields();
              }
            })
          }
        });
      },
      selectData () {
            let _this = this;
             if (_this.multipleSelection1.length === 0) {
              this.$message.warning('请选择计量点数据！');
            } else if (_this.multipleSelection.length === 0) {
              this.$message.warning('请选择计量时间数据！');
            } else {
            _this.operateLoading = true;
            var m = 0;
            for (var i = 0; i < _this.multipleSelection1.length; i++) {
              for (var j = 0; j < _this.multipleSelection.length; j++) {
                  _this.multipleSelection3[m] = {..._this.multipleSelection1[i], ..._this.multipleSelection[j]}
                  m++;
                }
             }
            add(meterbasecalibrarelations, _this.multipleSelection3, (e) => {
              _this.operateLoading = false;
              _this.getDataList();
              // _this.getDataList2();
              _this.getDataList3(this.firstRow);
              _this.multipleSelection3 = [];
              if (!e) {
                _this.$refs['baseData'].resetFields && _this.$refs['baseData'].resetFields();
              }
            })
            }
          },
      modifyData () {
        let _this = this;
        _this.$refs['baseData'].validate((valid) => {
          if (valid) {
            _this.operateLoading = true;
            _this.baseData.calibrationTypeName = _this.getCode (this.baseData.calibrationTypeNo, this.calibrationType, 'baseCode', 'baseName')
            _this.baseData.calibrationTimeUnit = _this.calibrationTimeUnit[_this.calibrationTimeUnitIndex].id;
            modify(meterbasecalibrationtimes + _this.baseData.calibrationTimeNo + '/', _this.baseData, (e) => {
              _this.operateLoading = false;
              _this.getDataList();
              if (!e) {
                _this.$refs['baseData'].resetFields && _this.$refs['baseData'].resetFields();
              }
            })
          }
        });
      },
      deleteData2 () {
        this.$confirm('确定删除选中的校称时间匹配信息？', {
            confirmButtonText: '确定',
            cancelButtonText: '取消'
          })
          .then(() => {
            this.operateLoading = true;
            Delete(meterbasecalibrarelations, this.multipleSelection2, (e) => {
              this.operateLoading = false;
              if (!e) {
                this.getDataList3(this.firstRow);
                // this.getDataList2();
              }
            })
          })
          .catch(action => {
            this.$message({
              type: 'info',
              message: action === 'cancel' ? '放弃保存并离开页面' : '停留在当前页面'
            })
          });
      },
       deleteData () {
        this.$confirm('确定删除选中的计量时间配置吗？', {
            confirmButtonText: '确定',
            cancelButtonText: '取消'
          })
          .then(() => {
            this.operateLoading = true;
            Delete(meterbasecalibrationtimes, this.multipleSelection, (e) => {
              this.operateLoading = false;
              if (!e) {
                this.getDataList();
              }
            })
          })
          .catch(action => {
            this.$message({
              type: 'info',
              message: action === 'cancel' ? '放弃保存并离开页面' : '停留在当前页面'
            })
          });
      },
      handleSelectionChange3 (val) {
        this.multipleSelection = val;
      },
      handleSelectionChange (val) {
        this.multipleSelection1 = val;
        if (val.length > 1) {
        this.$refs.dataTable.setCurrentRow(this.multipleSelection1[val.length-1])
        this.getDataList3(this.multipleSelection1[val.length-1])
        }
      },
      handleSelectionChange2 (val) {
        this.multipleSelection2 = val;
      },
      getTableHeight (dom) {
        return (window.innerHeight - dom.offsetTop);
      },
      pageSizeChange (size) {
        this.page.pageSize = size;
        this.getDataList();
      },

      pageCurrentChange (index) {
        this.page.pageNum = index;
        this.getDataList();
      },
       pageSizeChange1 (size) {
        this.page1.pageSize = size;
        this.getDataList2();
      },

      pageCurrentChange1 (index) {
        this.page1.pageNum = index;
        this.getDataList2();
      },
       pageSizeChange2 (size) {
        this.page2.pageSize = size;
        this.getDataList3(this.firstRow);
      },

      pageCurrentChange2 (index) {
        this.page2.pageNum = index;
        this.getDataList3(this.firstRow);
      },
      getDataList () {
        this.dataLoading = true;
        this.axios.get(meterbasecalibrationtimes + '?pageNum=' + this.page.pageNum + '&pageSize=' + this.page.pageSize)
          .then(res => {
            this.dataLoading = false;
            this.table.list = res.data.list;
            this.table.list.forEach(item => {item
              item.startTime1 = formatDate(item.startTime,'HH:mm:ss')
              item.endTime1 = formatDate(item.endTime,'HH:mm:ss')
            });
            this.page.totalPage = res.data.total;
          }).catch(e => {
            this.dataLoading = false;
          });
      },
      getDataList2 () {
        this.dataLoading = true;
        this.axios.get(meterbasespotinfos + 'calibcorrelation' + '?pageNum=' + this.page1.pageNum + '&pageSize=' + this.page1.pageSize)
          .then(res => {
            this.dataLoading = false;
            this.table.list2 = res.data.list;
             if (res.data.list.length > 0) {
              let firstRow = res.data.list[0]
              this.$refs.dataTable.setCurrentRow(firstRow)
              this.getDataList3(firstRow)
             }
            this.page1.totalPage = res.data.total;
          }).catch(e => {
            this.dataLoading = false;
          });
      },
      getDataList3 (row) {
        this.firstRow = row
         this.dataLoading = true;
        this.axios.get(meterbasecalibrarelations + '?pageNum=' + this.page2.pageNum + '&pageSize=' + this.page2.pageSize + '&baseSpotNo=' + row.baseSpotNo)
          .then(res => {
            this.dataLoading = false;
            this.table.list3 = res.data.list;
            this.table.list3.forEach(item => {item
              item.startTime1 = formatDate(item.startTime,'HH:mm:ss')
              item.endTime1 = formatDate(item.endTime,'HH:mm:ss')
            });
            this.page2.totalPage = res.data.total;
          }).catch(e => {
            this.dataLoading = false;
          });
      },
      getCalibrationType () {
          this.axios.get(combaseinfos + 'noPage' + '?pBaseCode=001005' + '&validFlag=1')
            .then(res => {
              this.calibrationType = res.data;
              this.baseData.calibrationTypeNo = res.data[0].baseCode ? res.data[0].baseCode : ''
            })
        },
    }
  }
</script>

<style scoped>
  .lineDiv:hover{
    cursor:s-resize;
  }
  .el-select {
    width: 100%;
  }
</style>
