<!--期限皮重时间配置-->
<template>
  <div class="systemBase common-container-deriction">
    <div class="common-title-div">期限皮重时间配置
      <div class="common-operation-button-div">
        <el-button icon="el-icon-search" type="primary" size="mini" @click="searchData"
        v-loading.fullscreen.lock="operateLoading" v-privilege="activeMenu + 'SEARCH'">查询</el-button>
        <el-button icon="el-icon-circle-plus-outline" type="primary" size="mini" @click="addData"
        v-loading.fullscreen.lock="operateLoading" 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" :row-class-name="tableRowClassName" ref="dataTable" highlight-current-row
        border :height="tableHeight" @selection-change="handleSelectionChange" :data="table.list" :exchangeFilterMap="{'valueFlag':{'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 :show-overflow-tooltip="true" prop="timeTypeName" min-width="120px" label="配置方式" align="center"></el-table-column>
        <el-table-column sortable :show-overflow-tooltip="true" prop="timeEdition" min-width="100px" label="配置版本" align="center"></el-table-column>
        <el-table-column sortable :show-overflow-tooltip="true" prop="rateValue" min-width="100px" label="随机值/天" align="right"></el-table-column>
        <el-table-column sortable :show-overflow-tooltip="true" prop="fixedValue" min-width="100px" label="固定值/天" align="right"></el-table-column>
        <el-table-column sortable :show-overflow-tooltip="true" prop="warnValue" min-width="100px" label="提醒值/小时" align="right"></el-table-column>
        <el-table-column sortable :show-overflow-tooltip="true" prop="valueFlag" min-width="80px" 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" prop="memo" min-width="200px" 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" label-width="70px" :inline="true" :rules="ruleValidate" :model="baseData">
           <el-form-item prop="timeTypeName" label="配置方式">
             <el-select v-model="baseData.timeTypeName" clearable filterable collapse-tags size="mini"  @change="selectTrigger(baseData.timeTypeName)" style="width:150px;">
               <el-option v-for="(item,index) in timeType" :key="index" :label="item.baseName" :value="item.baseName">
               </el-option>
             </el-select>
           </el-form-item>
           <el-form-item prop="rateValue" label="随机值/天" label-width="85px">
             <el-input v-model="baseData.rateValue" clearable size="mini" :readonly="isReteValue" :disabled="isReteValue" placeholder="0-99" style="width:150px;"></el-input>
           </el-form-item>
           <el-form-item prop="warnValue" label="提醒值/小时" label-width="90px">
             <el-input v-model="baseData.warnValue" clearable size="mini" placeholder="0-99" style="width:150px;"></el-input>
           </el-form-item>
           <el-form-item prop="fixedValue" label="固定值/天" label-width="90px">
             <el-input v-model="baseData.fixedValue" clearable size="mini" :readonly="isFixedValue" :disabled="isFixedValue" placeholder="1-99" style="width:150px;"></el-input>
           </el-form-item>
           <el-form-item prop="memo" label="备注">
             <el-input v-model="baseData.memo" clearable size="mini" placeholder="请输入" style="width:150px;"></el-input>
           </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
 import {
    meterbasetermtaretimes,
    combaseinfos
  } from '../../../utils/api.js';
  import {
    discard,
    Recovery,
    add,
    modify
  } from '../../../utils/httpRequest.js';
  export default {
    data () {
      return {
        dataLoading: false,
        operateLoading: false,
        isReteValue: false,
        isFixedValue: true,
        timeType: [
          // {id: '0001', name: '随机间隔'},
          // {id: '0002', name: '前固后随'},
          // {id: '0002', name: '固定间隔'}
        ],
        icoreFilterFlag: true,
        baseData: {
          rateValue: '',
          warnValue: '',
          fixedValue: '',
          memo: '',
          timeTypeName: ''
        },
        page: {
          pageSize: 500,
          pageNum: 1,
          totalPage: 0
        },
        table: {
          list: []
        },
        multipleSelection: [],
        tableHeight: 0,
        ruleValidate: {
          rateValue: [{
            required: true,
            validator: this.rateValueEmpty,
            // message: '随机值不能为空',
            trigger: 'change'
          }],
          warnValue: [{
            required: true,
            message: '提醒值不能为空',
            trigger: 'change'
          },
          {
            validator: this.warnValueEmpty,
            trigger: 'change'
          }],
          fixedValue: [{
            required: false,
            validator: this.fixedWeightValueEmpty,
            trigger: 'change'
          }],
          timeTypeName: [{
            required: true,
            message: '该项不能为空',
            trigger: 'change'
          }],
        },
        activeMenu: ''
      }
    },
    created () {
      this.tableHeight = (window.innerHeight - 220) > 400 ? window.innerHeight - 220 : 400;
      this.activeMenu = window.top.localStorage.getItem('activeMenu')
    },
    mounted () {
      this.getDataList();
      this.getTimeType()
    },
    methods: {
       getCode (code, arr, codeKey, nameKey) {
          if (!code) {
            return '';
          }
          let targetRow = arr.find(item => {
            return item[codeKey] === code;
          });
          return targetRow ? targetRow[nameKey] : '';
        },
      rowChange (row, column, event) {
        this.baseData = Object.assign ({}, row);
        if (row.timeTypeName === '固定间隔') {
          this.baseData.rateValue = '';
          this.isReteValue= true;
          this.isFixedValue = false;
          this.ruleValidate.rateValue[0].required = false;
          this.ruleValidate.fixedValue[0].required = true;
        } else if (row.timeTypeName === '随机间隔') {
          this.baseData.fixedValue = '';
          this.isReteValue = false;
          this.isFixedValue = true;
          this.ruleValidate.rateValue[0].required = true;
          this.ruleValidate.fixedValue[0].required = false;
        } else if (row.timeTypeName === '前固后随'){
          this.isReteValue = false;
          this.isFixedValue = false;
          this.ruleValidate.rateValue[0].required = true;
          this.ruleValidate.fixedValue[0].required = true;
        }
      },
      selectTrigger (timeTypeName) {
        if (timeTypeName === '固定间隔') {
          this.baseData.rateValue = '';
          this.isReteValue= true;
          this.isFixedValue = false;
          this.ruleValidate.rateValue[0].required = false;
          this.ruleValidate.fixedValue[0].required = true;
        } else if (timeTypeName === '随机间隔') {
          this.baseData.fixedValue = '';
          this.isReteValue = false;
          this.isFixedValue = true;
          this.ruleValidate.rateValue[0].required = true;
          this.ruleValidate.fixedValue[0].required = false;
        } else if(timeTypeName === '前固后随'){
          this.isReteValue = false;
          this.isFixedValue = false;
          this.ruleValidate.rateValue[0].required = true;
          this.ruleValidate.fixedValue[0].required = true;
        }
      },
      baseDataClear () {
        this.baseData.warnValue = '';
        this.baseData.rateValue = '';
        this.baseData.fixedValue = '';
        this.baseData.memo = '';
      },
      searchData () {
        this.page.pageNum = 1;
        this.getDataList()
      },
      rateValueEmpty (rule, value, callback) {
        const age= /^[0-9]*$/
        if ((this.baseData.timeTypeName === '前固后随' || this.baseData.timeTypeName === '随机间隔') && (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 (this.baseData.rateValue > 99 || this.baseData.rateValue < 0) {
               return callback(new Error('请输入为0-99的数字！'))
             } else {
               return callback()
             }
        }else {
          return callback()
        }
      },
      fixedWeightValueEmpty (rule, value, callback) {
        const age= /^[0-9]*$/
        if ((this.baseData.timeTypeName === '前固后随' || this.baseData.timeTypeName === '固定间隔') && (this.baseData.fixedValue === ''|| this.baseData.fixedValue === null)) {
            return callback(new Error('固重值不能为空'))
          } else if (this.baseData.fixedValue) {
            if (!age.test(this.baseData.fixedValue)) {
             return callback(new Error('请输入正整数！'))
             } else if (this.baseData.fixedValue > 99 || this.baseData.fixedValue < 1) {
               return callback(new Error('请输入为1-99的数字！'))
             } else {
               return callback()
             }
        } else {
          return callback()
        }
      },
      warnValueEmpty (rule, value, callback) {
        const age= /^[0-9]*$/
        if (this.baseData.warnValue) {
            if (!age.test(this.baseData.warnValue)) {
             return callback(new Error('请输入正整数！'))
             } else if (this.baseData.warnValue > 99 || this.baseData.warnValue < 0) {
               return callback(new Error('请输入为0-99的数字！'))
             } else {
               return callback()
             }
         } else {
           return callback()
         }
      },
      addData () {
        let _this = this;
        _this.$refs['baseData'].validate((valid) => {
          if (valid) {
             this.$confirm('是否确认新增？新增数据有可能将原来的数据状态置为无效！', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
            _this.operateLoading = true;
            let baseDataAdd = {};
            baseDataAdd.rateValue = _this.baseData.rateValue
            baseDataAdd.warnValue = _this.baseData.warnValue
            baseDataAdd.fixedValue = _this.baseData.fixedValue
            baseDataAdd.memo = _this.baseData.memo
            baseDataAdd.timeTypeName = _this.baseData.timeTypeName;
            baseDataAdd.timeTypeNo = _this.getCode(this.baseData.timeTypeName, this.timeType, 'baseName', 'baseCode');
            add(meterbasetermtaretimes, baseDataAdd, (e) => {
              _this.operateLoading = false;
              _this.getDataList();
              _this.baseDataClear();
              if (!e) {
                _this.$refs['baseData'].resetFields && _this.$refs['baseData'].resetFields();
              }
            })
            }).catch(() => {
              this.$message({
                type: 'info',
                message: '已取消新增'
              });          
            });
          }
        });
      },
      modifyData () {
        let _this = this;
        _this.$refs['baseData'].validate((valid) => {
          if (valid) {
            _this.operateLoading = true;
            _this.baseData.timeTypeNo = _this.getCode(this.baseData.timeTypeName, this.timeType, 'baseName', 'baseCode');
            modify(meterbasetermtaretimes + _this.baseData.timeNo + '/', _this.baseData, (e) => {
              _this.operateLoading = false;
              _this.getDataList();
              _this.baseDataClear();
              if (!e) {
                _this.$refs['baseData'].resetFields && _this.$refs['baseData'].resetFields();
              }
            })
          }
        });
      },
      recoveryData () {
        if (JSON.stringify(this.multipleSelection) == "{}") {
            this.$message.warning('请选择您要启用的数据！');
            return;
          }
         this.$confirm('是否确认启用？启用数据有可能将原来的数据状态置为无效！', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
                 if (this.multipleSelection.valueFlag === '0') {
                       this.$message.warning('请选择状态为无效的数据！');
                       return false;
                  }
                  this.axios.post('pass/systemBase/v1/meterbasetermtaretimes/Recovery', this.multipleSelection, {individualType: 'json'}).then(res => {
                     if (res.succeed) {
                       this.$message.success('启用成功');
                       this.getDataList ();
                    }  else {
                     this.$message.error(res.message)
                    }
                    }).catch(e => {
                     this.$message.error(e.message)
                   })
               }).catch(() => {
              this.$message({
                type: 'info',
                message: '已取消启用'
              });          
            });
      },
      abolishData () {
       if (JSON.stringify(this.multipleSelection) == "{}") {
            this.$message.warning('请选择您要废除的数据！');
            return;
          }
         if (this.multipleSelection.valueFlag === '1') {
               this.$message.warning('请选择状态为有效的数据！');
               return false;
          }
          this.axios.post('pass/systemBase/v1/meterbasetermtaretimes/abolish', this.multipleSelection, {individualType: 'json'}).then(res => {
             if (res.succeed) {
               this.$message.success('废除成功');
               this.getDataList ();
            }  else {
             this.$message.error(res.message)
            }
            }).catch(e => {
             this.$message.error(e.message)
           })
      },
      handleSelectionChange (val) {
        this.multipleSelection = val;
      },
      getTableHeight (dom) {
        return (window.innerHeight - dom.offsetTop);
      },
      pageSizeChange (size) {
        this.page.pageSize = size;
        this.getDataList();
      },

      pageCurrentChange (index) {
        this.page.pageNum = index;
        this.getDataList();
      },
      getDataList () {
        this.dataLoading = true;
        this.axios.get(meterbasetermtaretimes + '?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;
          }).catch(e => {
            this.dataLoading = false;
          });
      },
      getTimeType () {
         this.axios.get(combaseinfos + 'noPage' + '?pBaseCode=001013' + '&validFlag=1')
          .then(res => {
            this.timeType = res.data;
            this.baseData.timeTypeName = res.data[0].baseName
          })
      },
      tableRowClassName ({
        row,
        rowIndex
      }) {
        if (row.valueFlag !== '0') {
          return 'error-row2';
        }
        return '';
      }
    }
  }
</script>

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