<!--预报超差配置-->
<template>
  <div class="systemBase">
    <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 + 'ADD'">新增</el-button>
          <el-button icon="el-icon-edit" type="primary" size="mini" v-loading.fullscreen.lock="operateLoading"
          @click="modifyData" v-privilege="activeMenu + 'UPDATE'">修改</el-button>
          <el-button size="mini" type="danger" plain icon="el-icon-remove-outline" v-loading.fullscreen.lock="operateLoading"
          @click="abolishData" v-privilege="activeMenu + 'ABOLISH'">废除</el-button>
        <el-button size="mini" type="primary" icon="el-icon-check" v-loading.fullscreen.lock="operateLoading"
          @click="recoveryData" v-privilege="activeMenu + 'RECOVERY'">启用</el-button>
        </div>
      </div>
      <div class="common-table-div">
        <el-table v-loading="dataLoading" @row-click="rowChange" ref="dataTable" :row-class-name="tableRowClassName" 
        border :height="tableHeight"  @current-change="handleCurrentChange" :data="table.list" highlight-current-row
        :exchangeFilterMap="{'valueFlag':{'1':'无效','0':'有效'}}"
        :icore-filter-flag="icoreFilterFlag"
        @cell-click="getDataList3">
          <el-table-column type="index" label="序号" fixed="left" align="center"></el-table-column>
          <el-table-column sortable :show-overflow-tooltip="true" min-width="100px" prop="diffTypeName" label="超差方式" align="center"></el-table-column>
          <el-table-column sortable :show-overflow-tooltip="true" min-width="100px" prop="meterTypeName" label="计量类型" align="center"></el-table-column>
          <el-table-column sortable :show-overflow-tooltip="true" min-width="100px" prop="rateValue" label="比例值（%）" align="right"></el-table-column>
          <el-table-column sortable :show-overflow-tooltip="true" min-width="100px" prop="fixedWeightValue" label="固重值（kg）" align="right"></el-table-column>
          <el-table-column sortable :show-overflow-tooltip="true" min-width="80px" prop="valueFlag" label="状态" align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.valueFlag == 1">无效</span>
              <span v-else-if="scope.row.valueFlag == 0">有效</span>
            </template>
          </el-table-column>
          <el-table-column sortable :show-overflow-tooltip="true" min-width="200px" prop="memo" 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 class="lineDiv" v-if="detailData" style="border-bottom: 1px solid #DCDCDC;height:5px" ref="lineDiv"></div>
      <el-row>
        <el-col :span="12">
          <div class="common-title-div">待选物料
            <div class="common-operation-button-div">
              <el-button size="mini" type="primary" icon="el-icon-check" v-loading.fullscreen.lock="operateLoading"
           @click="selectData" v-privilege="activeMenu + 'SELECT'">选中</el-button>
            </div>
          </div>
          <div class="common-table-div">
            <el-table ref="dataTable2" border :height="tableHeight" highlight-current-row @selection-change="handleSelectionChange"
              :data="table.list2" :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 :show-overflow-tooltip="true" min-width="100px" prop="matterNo" label="物料编号" align="center"></el-table-column>
              <el-table-column sortable :show-overflow-tooltip="true" min-width="100px" prop="matterName" label="物料名称" align="center"></el-table-column>
              <el-table-column sortable :show-overflow-tooltip="true" min-width="100px" prop="matterNatureName" label="物料属性" align="center"></el-table-column>
              <el-table-column sortable :show-overflow-tooltip="true" min-width="100px" prop="meterNatureName" 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="12">
          <div class="common-title-div">已选物料
            <div class="common-operation-button-div">
              <el-button size="mini" type="danger" plain icon="el-icon-delete"  v-loading.fullscreen.lock="operateLoading"
              @click="deleteData2" v-privilege="activeMenu + 'REMOVE'">移除</el-button>
            </div>
          </div>
          <div class="common-table-div">
            <el-table ref="dataTable3" border :height="tableHeight" highlight-current-row @selection-change="handleSelectionChange2"
              :data="table.list3" :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 :show-overflow-tooltip="true" min-width="100px" prop="matterNo" label="物料编号" align="center"></el-table-column>
              <el-table-column sortable :show-overflow-tooltip="true" min-width="100px" prop="matterName" label="物料名称" align="center"></el-table-column>
              <el-table-column sortable :show-overflow-tooltip="true" min-width="100px" prop="matterNatureName" label="物料属性" align="center"></el-table-column>
              <el-table-column sortable :show-overflow-tooltip="true" min-width="100px" prop="meterNatureName" label="计量属性" 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 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 prop="diffTypeName" label="超差方式">
                <el-select v-model="baseData.diffTypeName" clearable filterable collapse-tags size="small" style="width:130px" @change="selectTrigger(baseData.diffTypeName)">
                 <el-option v-for="(item,index) in diffType" :key="index" :label="item.baseName" :value="item.baseName">
                 </el-option>
               </el-select>
             </el-form-item>
             <el-form-item prop="rateValue" label="比例值%">
               <el-input v-model="baseData.rateValue" clearable size="small" style="width:130px" :readonly="isReteValue" :disabled="isReteValue" placeholder="0-100"></el-input>
             </el-form-item>
             <el-form-item prop="meterTypeName" label="计量类型">
               <el-select v-model="baseData.meterTypeName" clearable filterable collapse-tags size="small" style="width:130px">
                 <el-option v-for="(item,index) in meterType" :key="index" :label="item.baseName" :value="item.baseName">
                 </el-option>
               </el-select>
             </el-form-item>
             <el-form-item prop="fixedWeightValue" label="固重值kg">
               <el-input v-model="baseData.fixedWeightValue" clearable size="small" style="width:130px" :readonly="!isReteValue" :disabled="!isReteValue" placeholder="0-1000"></el-input>
             </el-form-item>
            <el-form-item prop="memo" label="备注">
              <el-input v-model="baseData.memo" size="small" clearable style="width:130px" placeholder="请输入"></el-input>
            </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
  import {
    meterbasepredictiondiffs,
    meterbasematterinfos,
    meterbasediffrelations,
    combaseinfos
  } from '../../../utils/api.js';
  import {
    add,
    modify,
    Delete,
    DeleteOne,
    RecoveryOne,
    discardOne
  } from '../../../utils/httpRequest.js';
  import pinyinUtils from '../../../utils/pinyin/pinyinUtils.js'
  export default {
    data () {
      return {
        dataLoading: false,
        operateLoading: false,
        isReteValue: false,
        // meterTypeIndex: 0,
        // diffTypeIndex: 0,
        icoreFilterFlag: true,
        baseData: {
          memo: '',
          rateValue: '',
          fixedWeightValue: '',
          meterTypeName: '',
          diffTypeName: ''
        },
        page: {
          pageSize: 500,
          pageNum: 1,
          totalPage: 0
        },
        page1: {
          pageSize: 500,
          pageNum: 1,
          totalPage: 0
        },
        page2: {
          pageSize: 500,
          pageNum: 1,
          totalPage: 0
        },
        diffNoRow: {},
        table: {
          list: [],
          list2: [],
          list3: []
        },
        meterType: [
          // {id: '00001', name: '采购进厂'},
          // {id: '00002', name: '销售出厂'},
          // {id: '00003', name: '内部倒运'}
        ],
        diffType: [
          // {id: '00001', name: '比例'},
          // {id: '00002', name: '固重'}
        ],
        // multipleSelection: {},
        multipleSelection1: [],
        multipleSelection2: [],
        tableHeight: 0,
        ruleValidate: {
           rateValue: [{
            required: true,
            validator: this.rateValueEmpty,
            trigger: 'change'
          }],
          fixedWeightValue: [{
            required: false,
            validator: this.fixedWeightValueEmpty,
            trigger: 'change'
          }],
          diffTypeName: [{
            required: true,
            message: '该项不能为空',
            trigger: 'change'
          }],
          meterTypeName: [{
            required: true,
            message: '该项不能为空',
            trigger: 'change'
          }],
        },
        detailData: true,
        activeMenu: ''
      }
    },
    created () {
      this.tableHeight = (window.innerHeight - 340)/2 > 200 ? (window.innerHeight - 340)/2 : 200
      this.activeMenu = window.top.localStorage.getItem('activeMenu')
    },
    mounted () {
      // this.tableHeight = this.getTableHeight(this.$refs['dataTable'].$el) - 80;
      this.getDataList();
      this.getDataList2();
      this.getMeterType();
      this.getDiffType();
      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 dtable = this.$refs.dataTable2.$el
          var dtable2 = this.$refs.dataTable3.$el
          var oDiv = this.$refs.lineDiv
          oDiv.onmousedown = function(ev){
          var theight = parseInt(tableDiv.offsetHeight)//parseInt为了不指向对象
          var dheight = parseInt(dtable.offsetHeight)
          var dheight2 = parseInt(dtable2.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"
          dtable.style.height = dheight +(mouseDownY-mouseMoveY)+"px"
          dtable2.style.height = dheight2 +(mouseDownY-mouseMoveY)+"px"
          }
          }
          document.onmouseup = function(){
          document.onmousemove = null;
          // 释放全局捕获
          if(oDiv.releaseCapture){
          oDiv.releaseCapture();
          }
          }
          return false;
      },
      rowChange (row, column, event) {
        this.baseData =  Object.assign ({}, row);
        // for (let i=0; i<this.diffType.length; i++) {
        //   if (this.diffType[i].baseCode === this.baseData.diffTypeNo) {
        //     this.diffTypeIndex = i
        //   }
        // }
        // for (let i=0; i<this.meterType.length; i++) {
        //   if (this.meterType[i].baseCode === this.baseData.meterTypeNo) {
        //     this.meterTypeIndex = i
        //   }
        // }
        if (row.diffTypeName === '比例') {
          this.baseData.fixedWeightValue = '';
          this.isReteValue = false;
          this.ruleValidate.fixedWeightValue[0].required = false;
          this.ruleValidate.rateValue[0].required = true;
        } else {
          this.baseData.rateValue = '';
          this.isReteValue= true;
          this.ruleValidate.fixedWeightValue[0].required = true;
          this.ruleValidate.rateValue[0].required = false;
        }
      },
      selectTrigger (diffTypeName) {
        if (diffTypeName === '比例') {
          this.baseData.fixedWeightValue = '';
          this.isReteValue = false;
          this.ruleValidate.fixedWeightValue[0].required = false;
          this.ruleValidate.rateValue[0].required = true;
        } else {
          this.baseData.rateValue = '';
          this.isReteValue= true;
          this.ruleValidate.fixedWeightValue[0].required = true;
          this.ruleValidate.rateValue[0].required = false;
        }
      },
       rateValueEmpty (rule, value, callback) {
         const age= /^[0-9]*$/
        if (this.baseData.diffTypeName === '比例' && (this.baseData.rateValue === '' || this.baseData.rateValue === null)) {
          return callback(new Error('比例值不能为空'))
        } else if (this.baseData.rateValue) {
            if (!age.test(this.baseData.rateValue)) {
             return callback(new Error('请输入数字！'))
             } else if (Number(this.baseData.rateValue >100)) {
               return callback(new Error('请输入为0-100的数字！'))
             } else {
               return callback()
             }
        }else {
          return callback()
        }
      },
      fixedWeightValueEmpty (rule, value, callback) {
         const age= /^[0-9]*$/
        if (this.baseData.diffTypeName === '固重' && (this.baseData.fixedWeightValue === ''|| this.baseData.fixedWeightValue === null)) {
            return callback(new Error('固重值不能为空'))
          } else if (this.baseData.fixedWeightValue) {
            if (!age.test(this.baseData.fixedWeightValue)) {
             return callback(new Error('请输入数字！'))
             } else if (Number(this.baseData.fixedWeightValue) - 0 > 1000) {
               return callback(new Error('请输入为0-1000的数字！'))
             } else {
               return callback()
             }
        } else {
          return callback()
        }
      },
      addData () {
        let _this = this;
        _this.$refs['baseData'].validate((valid) => {
          if (valid) {
            _this.operateLoading = true;
            let baseDataAdd = {};
            baseDataAdd.memo =  _this.baseData.memo,
            baseDataAdd.rateValue =  _this.baseData.rateValue,
            baseDataAdd.fixedWeightValue =  _this.baseData.fixedWeightValue,
            baseDataAdd.meterTypeName = _this.baseData.meterTypeName;
            baseDataAdd.diffTypeName = _this.baseData.diffTypeName;
            baseDataAdd.meterTypeNo = _this.getCode(this.baseData.meterTypeName, this.meterType, 'baseName', 'baseCode');
            baseDataAdd.diffTypeNo = _this.getCode(this.baseData.diffTypeName, this.diffType, 'baseName', 'baseCode');
            add(meterbasepredictiondiffs, baseDataAdd, (e) => {
              _this.operateLoading = false;
              _this.getDataList();
              if (!e) {
                _this.$refs['baseData'].resetFields && _this.$refs['baseData'].resetFields();
              }
            })
          }
        });
      },
      selectData () {
            let _this = this;
            if (typeof _this.multipleSelection === 'undefined' || _this.multipleSelection == null || _this.multipleSelection === '') {
               this.$message.warning('请选择预报超差数据！');
            } else if (_this.multipleSelection1.length === 0) {
               this.$message.warning('请选择物料数据！');
            } else {
               _this.operateLoading = true;
               for (var i = 0; i < _this.multipleSelection1.length; i++) {
                _this.multipleSelection1[i].diffNo = _this.multipleSelection.diffNo;
                _this.multipleSelection1[i].id = null;
               }
            add(meterbasediffrelations, _this.multipleSelection1, (e) => {
              _this.operateLoading = false;
              // _this.getDataList();
              _this.getDataList2();
              _this.getDataList3(this.diffNoRow);
              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.meterTypeNo =  _this.getCode(this.baseData.meterTypeName, this.meterType, 'baseName', 'baseCode');
            _this.baseData.diffTypeNo = _this.getCode(this.baseData.diffTypeName, this.diffType, 'baseName', 'baseCode');
            modify(meterbasepredictiondiffs + _this.baseData.diffNo + '/', _this.baseData, (e) => {
              _this.operateLoading = false;
              _this.getDataList();
              if (!e) {
                _this.$refs['baseData'].resetFields && _this.$refs['baseData'].resetFields();
              }
            })
          }
        });
      },
      // recoveryData() {
      //   let _this = this;
      //   _this.operateLoading = true;
      //   Recovery(meterbasepredictiondiffs + "Recovery", _this.multipleSelection, (e) => {
      //     _this.operateLoading = false;
      //     if (!e) {
      //       _this.getDataList();
      //     }
      //   });
      // },
      deleteData2 () {
        this.$confirm('确定删除选中的物料信息？', {
            confirmButtonText: '确定',
            cancelButtonText: '取消'
          })
          .then(() => {
            this.operateLoading = true;
            Delete(meterbasediffrelations, this.multipleSelection2, (e) => {
              this.operateLoading = false;
              if (!e) {
                this.getDataList3(this.diffNoRow);
                this.getDataList2();
              }
            })
          })
          .catch(action => {
            this.$message({
              type: 'info',
              message: action === 'cancel' ? '放弃保存并离开页面' : '停留在当前页面'
            })
          });
      },
       recoveryData () {
        let _this = this;
        _this.operateLoading = true;
        RecoveryOne(meterbasepredictiondiffs + 'Recovery', _this.multipleSelection, (e) => {
          _this.operateLoading = false;
          if (!e) {
            _this.getDataList();
          }
        });
      },
       abolishData () {
        let _this = this;
        _this.operateLoading = true;
        discardOne(meterbasepredictiondiffs + 'abolish', _this.multipleSelection, (e) => {
          _this.operateLoading = false;
          if (!e) {
            _this.getDataList();
          }
        });
      },
      //  deleteData () {
      //   this.$confirm('确定删除选中的配置吗？', {
      //       confirmButtonText: '确定',
      //       cancelButtonText: '取消'
      //     })
      //     .then(() => {
      //       this.operateLoading = true;
      //       DeleteOne(meterbasepredictiondiffs + this.multipleSelection.diffNo, (e) => {
      //         this.operateLoading = false;
      //         if (!e) {
      //           this.getDataList();
      //         }
      //       })
      //     })
      //     .catch(action => {
      //       this.$message({
      //         type: 'info',
      //         message: action === 'cancel' ? '放弃保存并离开页面' : '停留在当前页面'
      //       })
      //     });
      // },
      handleCurrentChange (val) {
        this.multipleSelection = val;
      },
      handleSelectionChange (val) {
        this.multipleSelection1 = val;
      },
      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.diffNoRow);
      },

      pageCurrentChange2 (index) {
        this.page2.pageNum = index;
        this.getDataList3(this.diffNoRow);
      },
      getDataList () {
        this.dataLoading = true;
        this.axios.get(meterbasepredictiondiffs + '?pageNum=' + this.page.pageNum + '&pageSize=' + this.page.pageSize)
          .then(res => {
            this.dataLoading = false;
            this.table.list = res.data.list;
            this.page.totalPage = res.data.total;
            if (this.table.list.length > 0) {
            this.$refs.dataTable.setCurrentRow(this.table.list[0])
            this.getDataList3(this.table.list[0])  
            } 
          }).catch(e => {
            this.dataLoading = false;
          });
      },
      tableRowClassName ({
        row,
        rowIndex
      }) {
        if (row.valueFlag !== '0') {
          return 'error-row2';
        }
        return '';
      },
      getDataList2 () {
        this.dataLoading = true;
        this.axios.get(meterbasematterinfos + 'diffscorrelation' + '?pageNum=' + this.page1.pageNum + '&pageSize=' + this.page1.pageSize + '&validFlag=1')
          .then(res => {
            this.dataLoading = false;
            this.table.list2 = res.data.list;
            this.page1.totalPage = res.data.total;
          }).catch(e => {
            this.dataLoading = false;
          });
      },
      getDataList3 (row) {
         this.dataLoading = true;
         this.diffNoRow = row
         this.axios.get(meterbasediffrelations + '?pageNum=' + this.page2.pageNum + '&pageSize=' + this.page2.pageSize + '&diffNo=' + row.diffNo)
          .then(res => {
            this.dataLoading = false;
            this.table.list3 = res.data.list;
            this.page2.totalPage = res.data.total;
          }).catch(e => {
            this.dataLoading = false;
          });
      },
      getMeterType () {
          this.axios.get(combaseinfos + 'noPage' + '?pBaseCode=001006' + '&validFlag=1')
          .then(res => {
            this.meterType = res.data;
            this.baseData.meterTypeName = res.data[0].baseName
          })
      },
      getDiffType () {
          this.axios.get(combaseinfos + 'noPage' + '?pBaseCode=001014' + '&validFlag=1')
          .then(res => {
            this.diffType = res.data;
            this.baseData.diffTypeName = res.data[0].baseName
          })
      }
      // myBlur() {
      //   if (this.baseData.customerSupplierName) {
      //     this.baseData.mnemonicCode = pinyinUtils.initial(this.baseData.customerSupplierName);
      //   }
      // }
    }
  }
</script>
<style scoped>
  .lineDiv:hover{
    cursor:s-resize;
  }
  .el-select {
    width: 100%;
  }
</style>
