<!--计量回皮时间管理-->
<template>
  <div class="systemBase">
    <div>
      <div class="common-title-div">计量回皮时间管理
        <div class="common-operation-button-div">
           <el-form :inline="true" :model="search"  @submit.native.prevent>
           <el-form-item prop="matterName" label="物料名称">
             <el-input v-model="search.matterName" clearable size="small"  style="width:150px" placeholder="请输入" @keyup.enter.native="searchDatas"></el-input>
           </el-form-item>
          <el-form-item label-width="20px">
            <el-button icon="el-icon-search" type="primary" size="mini" @click="searchDatas" v-loading.fullscreen.lock="operateLoading"  v-privilege="activeMenu + 'SEARCH'">查询</el-button>
          </el-form-item>
          <el-form-item label-width="20px">
          <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-form-item>
           <el-form-item label-width="20px">
          <el-button icon="el-icon-edit" type="primary" size="mini" v-loading.fullscreen.lock="operateLoading"
          @click="modifyData" v-privilege="activeMenu + 'UPDATE'">修改</el-button>
           </el-form-item>
           <el-form-item>
             <el-button size="mini" type="danger" plain icon="el-icon-delete" v-loading.fullscreen.lock="operateLoading"
          @click="deleteData" v-privilege="activeMenu + 'DELETE'">删除</el-button>
           </el-form-item>
          </el-form>
        </div>
      </div>
      <div class="common-table-div">
        <el-table v-loading="dataLoading" @row-click="rowChange" ref="dataTable" highlight-current-row
          border :height="tableHeight" @selection-change="handleSelectionChange" :data="table.list"
          :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="meterTypeNo" 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="tareTypeName" label="回皮时间类型" align="center"></el-table-column>
          <el-table-column sortable :show-overflow-tooltip="true" min-width="160px" prop="tareTime" label="回皮时间" align="center"></el-table-column>
          <el-table-column sortable :show-overflow-tooltip="true" min-width="140px" prop="tareSpaceTime" label="回皮时间间隔（M）" align="right"></el-table-column>
          <el-table-column sortable :show-overflow-tooltip="true" min-width="200px" prop="memo" label="备注" align="center"></el-table-column>
          <el-table-column sortable :show-overflow-tooltip="true" min-width="80px" prop="createManName" label="创建人" align="center"></el-table-column>
          <el-table-column sortable :show-overflow-tooltip="true" min-width="160px" prop="createTime" label="创建时间" align="center"></el-table-column>
          <el-table-column sortable :show-overflow-tooltip="true" min-width="80px" prop="updateManName" label="修改人" align="center"></el-table-column>
          <el-table-column sortable :show-overflow-tooltip="true" min-width="160px" 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" style="border-top: 1px solid #d5d5d5; margin-top: 10px">
        <el-form ref="baseData" :inline="true" label-width="90px" :rules="ruleValidate" :model="baseData">
            <el-form-item prop="matterName" label="物料名称">
              <el-select v-model="baseData.matterName" clearable filterable collapse-tags size="small"  style="width: 120px;" :filter-method="getMatterName">
                <el-option v-for="(item,index) in metterType" :key="index" :label="item.matterName" :value="item.matterName">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="tareTypeName" label="回皮类型">
              <el-select v-model="baseData.tareTypeName" clearable filterable collapse-tags size="small"  style="width: 120px;"  @change="selectTrigger(baseData.tareTypeName)">
                <el-option v-for="(item,index) in skinBackType" :key="index" :label="item.baseName" :value="item.baseName" >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="tareSpaceTime" label="间隔时间(M)">
              <el-input v-model="baseData.tareSpaceTime" clearable size="small"  style="width: 120px;" :readonly="isInput" :disabled="isInput" placeholder="请输入"></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: 120px;">
               <el-option v-for="(item,index) in type" :key="index" :label="item.baseName" :value="item.baseName">
               </el-option>
             </el-select>
            </el-form-item>
            <el-form-item prop="tareTime" label="回皮时间">
              <el-time-picker size="small"  clearable style="width: 120px;" v-model="baseData.tareTime" :readonly="!isInput" :disabled="!isInput" placeholder="任意时间点">
              </el-time-picker>
            </el-form-item>
           <el-form-item prop="memo" label="备注">
             <el-input v-model="baseData.memo"  clearable style="width: 120px;" size="small" placeholder="请输入"></el-input>
           </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>
<script>
import {
    formatDate,
    convertDate
  } from '@/utils/util.js';
import {
    meterbasematterinfos,
    meterbasetares,
    combaseinfos
  } from '../../../utils/api.js';
   import {
    add,
    modify,
    Delete
  } from '../../../utils/httpRequest.js';
  export default {
    data () {
      return {
        dataLoading: false,
        operateLoading: false,
        isInput: true,
        icoreFilterFlag: true,
        baseData: {
          tareSpaceTime: '',
          tareTime: '',
          memo: '',
          matterName: '',
          tareTypeName: '',
          meterTypeName: ''
        },
        type: [
          // {id: '00001', name: '采购进场'},
          // {id: '00002', name: '销售出厂'}
        ],
        skinBackType: [
          // {id: '00001', name: '按固定时间'},
          // {id: '00002', name: '按时间间隔'}
        ],
        metterType: [],
        page: {
          pageSize: 500,
          pageNum: 1,
          totalPage: 0
        },
        table: {
          list: []
        },
        multipleSelection: [],
        tableHeight: 0,
        ruleValidate: {
          tareTime: [{
            required: true,
            validator: this.tareTimeEmpty,
            trigger: 'change'
          }],
          tareSpaceTime: [{
            required: false,
            validator: this.tareSpaceTimeEmpty,
            trigger: 'change'
          }],
          matterName: [{
            required: true,
            message: '该项不能为空',
            trigger: 'change'
          }],
          tareTypeName: [{
            required: true,
            message: '该项不能为空',
            trigger: 'change'
          }],
          meterTypeName: [{
            required: true,
            message: '该项不能为空',
            trigger: 'change'
          }]
        },
        activeMenu: '',
        search: {
           matterName: '',
        },
      }
    },
    created(){
      this.tableHeight = (window.innerHeight - 220) > 400 ? window.innerHeight - 220 : 400;
      this.activeMenu = window.top.localStorage.getItem('activeMenu')
    },
    mounted () {
      this.getDataList();
      // this.getDataList2();
      this.getType();
      this.getSkinBackType()
    },
    methods: {
      getCode (code, arr, codeKey, nameKey) {
          if (!code) {
            return '';
          }
          let targetRow = arr.find(item => {
            return item[codeKey] === code;
          });
          return targetRow ? targetRow[nameKey] : '';
      },
       searchDatas () {
        this.page.pageNum = 1
        this.searchData ()
      },
      searchData () {
         let obj = {
          pageNum: this.page.pageNum,
          pageSize: this.page.pageSize,
          matterName: this.search.matterName,
         }
         this.axios.post('pass/systemBase/v1/meterbasetares/listLike',obj,{individualType: 'json'})
         .then(res => {
           this.table.list = res.data.list;
           this.page.totalPage = res.data.total
         })
      },
      rowChange (row, column, event) {
        this.baseData = Object.assign ({}, row);
        // console.log(this.baseData.tareTime);
         this.axios.get('pass/systemBase/v1/meterbasematterinfos/noPage'+ '?validFlag=1' + '&matterNo='+ this.baseData.matterNo)
         .then(res => {
           this.metterType = res.data;
         })
        this.baseData.tareTime = convertDate('2020-10-26 ' + this.baseData.tareTime)
        if (this.baseData.tareTypeName === '时间间隔') {
          this.baseData.tareTime = '';
          this.isInput = false;
          this.ruleValidate.tareTime[0].required = false;
          this.ruleValidate.tareSpaceTime[0].required = true;
        } else {
          this.baseData.tareSpaceTime = '';
          this.isInput= true;
          this.ruleValidate.tareTime[0].required = true;
          this.ruleValidate.tareSpaceTime[0].required = false;
        }
      },
      selectTrigger (tareTypeName) {
        if (tareTypeName === '时间间隔') {
          this.baseData.tareTime = '';
          this.isInput = false;
          this.ruleValidate.tareTime[0].required = false;
          this.ruleValidate.tareSpaceTime[0].required = true;
        } else {
          this.baseData.tareSpaceTime = '';
          this.isInput= true;
          this.ruleValidate.tareTime[0].required = true;
          this.ruleValidate.tareSpaceTime[0].required = false;
        }
      },
       getMatterName (val) {
       this.axios.get('pass/systemBase/v1/meterbasematterinfos/noPage'+ '?validFlag=1' + '&matterName='+ val)
         .then(res => {
           this.metterType = res.data;
         })
      },
      // convertDateFromString(dateString) {
      //    if (dateString) {
      //    var date   = new Date(dateString.replace(/:/,",")) 
      //    console.log(date, dateString.replace(/:/,","))
      //     return date;
      //    }
      // },
      tareTimeEmpty (rule, value, callback) {
        if (this.baseData.tareTypeName === '回皮时间'  && (this.baseData.tareTime === '' || this.baseData.tareTime === null )) {
          return callback(new Error('回皮时间不能为空'))
        } else {
          return callback()
        }
      },
      tareSpaceTimeEmpty (rule, value, callback) {
        if (this.baseData.tareTypeName === '时间间隔' && (this.baseData.tareSpaceTime === '' || this.baseData.tareSpaceTime === null)) {
          return callback(new Error('时间间隔不能为空'))
        } else {
          return callback()
        }
      },
      addData () {
        let _this = this;
        _this.$refs['baseData'].validate((valid) => {
          if (valid) {
            let baseDataAdd = {};
            baseDataAdd.tareSpaceTime = _this.baseData.tareSpaceTime
            baseDataAdd.tareTime = _this.baseData.tareTime
            baseDataAdd.memo = _this.baseData.memo
            baseDataAdd.meterTypeName = _this.baseData.meterTypeName
            baseDataAdd.tareTypeName = _this.baseData.tareTypeName
            baseDataAdd.matterName = _this.baseData.matterName
            baseDataAdd.meterTypeNo = _this.getCode(this.baseData.meterTypeName, this.type, 'baseName', 'baseCode');
            baseDataAdd.tareTypeNo = _this.getCode(this.baseData.tareTypeName, this.skinBackType, 'baseName', 'baseCode');
            baseDataAdd.matterNo = _this.getCode(this.baseData.matterName, this.metterType, 'matterName', 'matterNo');
            baseDataAdd.tareTime = formatDate (this.baseData.tareTime, 'HH:mm:ss')
            // _this.baseData.scalePointNo = _this.balancePoint[_this.balancePointIndex].scalePointNo;
            // _this.baseData.scalePointName = _this.balancePoint[_this.balancePointIndex].scalePointName;
            _this.operateLoading = true;
            add(meterbasetares, baseDataAdd, (e) => {
              _this.operateLoading = false;
              _this.getDataList();
              if (!e) {
                _this.$refs['baseData'].resetFields && _this.$refs['baseData'].resetFields();
              }
            })
          }
        });
      },
      modifyData () {
        let _this = this;
        _this.$refs['baseData'].validate((valid) => {
          if (valid) {
            _this.baseData.meterTypeNo = _this.getCode(this.baseData.meterTypeName, this.type, 'baseName', 'baseCode');
            _this.baseData.tareTypeNo = _this.getCode(this.baseData.tareTypeName, this.skinBackType, 'baseName', 'baseCode');
            _this.baseData.matterNo = _this.getCode(this.baseData.matterName, this.metterType, 'matterName', 'matterNo');
            _this.baseData.tareTime = formatDate (this.baseData.tareTime, 'HH:mm:ss')
            // _this.baseData.scalePointNo = _this.balancePoint[_this.balancePointIndex].scalePointNo;
            // _this.baseData.scalePointName = _this.balancePoint[_this.balancePointIndex].scalePointName;
            _this.operateLoading = true;
            modify(meterbasetares + _this.baseData.tareNo + '/', _this.baseData, (e) => {
              _this.operateLoading = false;
              _this.getDataList();
              if (!e) {
                _this.$refs['baseData'].resetFields && _this.$refs['baseData'].resetFields();
              }
            })
          }
        });
      },
      deleteData () {
        this.$confirm('确定删除选中的配置吗？', {
            confirmButtonText: '确定',
            cancelButtonText: '取消'
          })
          .then(() => {
            this.operateLoading = true;
            Delete(meterbasetares, this.multipleSelection, (e) => {
              this.operateLoading = false;
              if (!e) {
                this.getDataList();
              }
            })
          })
          .catch(action => {
            this.$message({
              type: 'info',
              message: action === 'cancel' ? '放弃保存并离开页面' : '停留在当前页面'
            })
          });
      },
      handleSelectionChange (val) {
        this.multipleSelection = val;
      },
      getTableHeight (dom) {
        return (window.innerHeight - dom.offsetTop);
      },
      pageSizeChange (size) {
        this.page.pageSize = size;
        // this.getDataList();
        this.searchData()
      },

      pageCurrentChange (index) {
        this.page.pageNum = index;
        // this.getDataList();
        this.searchData()
      },
      getDataList () {
        this.dataLoading = true;
        this.axios.get(meterbasetares + '?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.tareTime1 = formatDate(item.tareTime,'HH:mm:ss')
            // });
            this.page.totalPage = res.data.total;
          }).catch(e => {
            this.dataLoading = false;
          });
      },
      // getDataList2 () {
      //   this.axios.get(meterbasematterinfos + 'noPage' + '?validFlag=1')
      //     .then(res => {
      //       this.metterType = res.data;
      //       this.baseData.matterName = res.data[0].matterName
      //     })
      // },
      getType () {
         this.axios.get(combaseinfos + 'noPage' + '?pBaseCode=001006' + '&validFlag=1')
          .then(res => {
            this.type = res.data;
            this.baseData.meterTypeName = res.data[0].baseName
          })
      },
      getSkinBackType () {
         this.axios.get(combaseinfos + 'noPage' + '?pBaseCode=001007' + '&validFlag=1')
          .then(res => {
            this.skinBackType = res.data;
            this.baseData.tareTypeName = res.data[0].baseName
          })
      }
    }
  }
</script>

<style scoped>
  .el-select {
    width: 100%;
  }
</style>
