<!--秤体量程配置-->
<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-delete"
            v-loading.fullscreen.lock="operateLoading"
            @click="deleteData"
            v-privilege="activeMenu + 'DELETE'"
            >删除</el-button
          >
        </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"
            fixed="left"
            align="center"
          ></el-table-column>
          <el-table-column
            sortable
            :show-overflow-tooltip="true"
            min-width="100px"
            prop="baseSpotNo"
            label="计量点编号"
            align="center"
          ></el-table-column>
          <el-table-column
            sortable
            :show-overflow-tooltip="true"
            min-width="120px"
            prop="baseSpotName"
            label="计量点名称"
            align="center"
          ></el-table-column>
          <el-table-column
            sortable
            :show-overflow-tooltip="true"
            min-width="120px"
            prop="scalePointNo"
            label="秤点编号"
            align="center"
          ></el-table-column>
          <el-table-column
            sortable
            :show-overflow-tooltip="true"
            min-width="120px"
            prop="scalePointName"
            label="秤点名称"
          ></el-table-column>
          <el-table-column
            sortable
            :show-overflow-tooltip="true"
            min-width="120px"
            prop="counterWeight"
            label="砝码重量（t）"
            align="right"
          >
            <template slot-scope="scope">
              {{ Math.floor((scope.row.counterWeight - 0) / 10) / 100 }}
            </template>
          </el-table-column>
          <el-table-column
            sortable
            :show-overflow-tooltip="true"
            min-width="120px"
            prop="counterWeightDiff"
            label="允许差值（t）"
            align="right"
          >
            <template slot-scope="scope">
              {{ Math.floor((scope.row.counterWeightDiff - 0) / 10) / 100 }}
            </template>
          </el-table-column>
          <el-table-column
            sortable
            :show-overflow-tooltip="true"
            min-width="120px"
            prop="upperRange"
            label="最大量程（t）"
            align="right"
          >
            <template slot-scope="scope">
              {{ Math.floor((scope.row.upperRange - 0) / 10) / 100 }}
            </template>
          </el-table-column>
          <el-table-column
            sortable
            :show-overflow-tooltip="true"
            min-width="130px"
            prop="indexValue"
            label="秤体仪表分度值(t)"
            align="right"
          >
            <template slot-scope="scope">
              {{ Math.floor((scope.row.indexValue - 0) / 10) / 100 }}
            </template>
          </el-table-column>
          <el-table-column
            sortable
            :show-overflow-tooltip="true"
            min-width="120px"
            prop="stableRate"
            label="判稳频率(次数)"
            align="right"
          ></el-table-column>
          <el-table-column
            sortable
            :show-overflow-tooltip="true"
            min-width="120px"
            prop="stableDiff"
            label="判稳差值（t）"
            align="right"
          >
            <template slot-scope="scope">
              {{ Math.floor((scope.row.stableDiff - 0) / 10) / 100 }}
            </template>
          </el-table-column>
          <el-table-column
            sortable
            :show-overflow-tooltip="true"
            min-width="130px"
            prop="upperLimitClearZero"
            label="仪表清零上限（t）"
            align="right"
          >
            <template slot-scope="scope">
              {{ Math.floor((scope.row.upperLimitClearZero - 0) / 10) / 100 }}
            </template>
          </el-table-column>
          <el-table-column
            sortable
            :show-overflow-tooltip="true"
            min-width="130px"
            prop="lowerLimitClearZero"
            label="仪表清零下限（t）"
            align="right"
          >
            <template slot-scope="scope">
              {{ Math.floor((scope.row.lowerLimitClearZero - 0) / 10) / 100 }}
            </template>
          </el-table-column>
          <el-table-column
            sortable
            :show-overflow-tooltip="true"
            min-width="100px"
            prop="selfWeightDiff"
            label="自检差值（t）"
            align="right"
          >
            <template slot-scope="scope">
              {{ Math.floor((scope.row.selfWeightDiff - 0) / 10) / 100 }}
            </template>
          </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="100px"
          :inline="true"
          :rules="ruleValidate"
          :model="baseData"
        >
          <el-form-item prop="baseSpotNo" label="计量点">
            <el-select
              v-model="baseData.baseSpotNo"
              clearable
              filterable
              collapse-tags
              size="small"
              style="width: 120px"
              @change="getDataList3(baseData.baseSpotNo)"
            >
              <el-option
                v-for="(item, index) in meteringPoint"
                :key="index"
                :label="item.baseSpotName"
                :value="item.baseSpotNo"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="scalePointNo" label="秤点" label-width="60px">
            <el-select
              v-model="baseData.scalePointNo"
              clearable
              filterable
              collapse-tags
              size="small"
              style="width: 160px"
            >
              <el-option
                v-for="(item, index) in balancePoint"
                :key="index"
                :label="item.scalePointName"
                :value="item.scalePointNo"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="counterWeight" label="砝码重量(t)">
            <el-input
              v-model="baseData.counterWeight"
              clearable
              size="small"
              placeholder="请输入"
              style="width: 120px"
            ></el-input>
          </el-form-item>
          <el-form-item prop="counterWeightDiff" label="允许差值(t)">
            <el-input
              v-model="baseData.counterWeightDiff"
              clearable
              size="small"
              placeholder="请输入"
              style="width: 120px"
            ></el-input>
          </el-form-item>
          <el-form-item prop="upperRange" label="最大量程(t)">
            <el-input
              v-model="baseData.upperRange"
              clearable
              size="small"
              placeholder="请输入"
              style="width: 120px"
            ></el-input>
          </el-form-item>
          <el-form-item prop="stableRate" label="判稳频率(次数)">
            <el-input
              v-model="baseData.stableRate"
              clearable
              size="small"
              placeholder="请输入"
              style="width: 120px"
            ></el-input>
          </el-form-item>
          <el-form-item prop="indexValue" label="分度值(t)">
            <el-input
              v-model="baseData.indexValue"
              clearable
              size="small"
              placeholder="请输入"
              style="width: 120px"
            ></el-input>
          </el-form-item>
          <el-form-item prop="stableDiff" label="判稳差值(t)">
            <el-input
              v-model="baseData.stableDiff"
              clearable
              size="small"
              placeholder="请输入"
              style="width: 120px"
            ></el-input>
          </el-form-item>
          <el-form-item prop="upperLimitClearZero" label="清零上限(t)">
            <el-input
              v-model="baseData.upperLimitClearZero"
              clearable
              size="small"
              placeholder="请输入"
              style="width: 120px"
            ></el-input>
          </el-form-item>
          <el-form-item prop="lowerLimitClearZero" label="清零下限(t)">
            <el-input
              v-model="baseData.lowerLimitClearZero"
              clearable
              size="small"
              placeholder="请输入"
              style="width: 120px"
            ></el-input>
          </el-form-item>
          <el-form-item prop="selfWeightDiff" label="自检差值(t)">
            <el-input
              v-model="baseData.selfWeightDiff"
              clearable
              size="small"
              placeholder="请输入"
              style="width: 120px"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>
<script>
import {
  meterbasespotinfos,
  meterbasescalepoints,
  meterbasescaleranges
} from '../../../utils/api.js';
import {
  add,
  modify,
  Delete
} from '../../../utils/httpRequest.js';
export default {
  data () {
    return {
      dataLoading: false,
      operateLoading: false,
      icoreFilterFlag: true,
      meteringPoint: [],
      balancePoint: [],
      baseData: {
        counterWeight: '',
        upperRange: '',
        stableRate: '',
        counterWeightDiff: '',
        indexValue: '',
        stableDiff: '',
        upperLimitClearZero: '',
        lowerLimitClearZero: '',
        selfWeightDiff: ''
      },
      page: {
        pageSize: 500,
        pageNum: 1,
        totalPage: 0
      },
      table: {
        list: []
      },
      multipleSelection: [],
      tableHeight: 0,
      ruleValidate: {
        baseSpotNo: [{
          required: true,
          message: '该项不能为空',
          trigger: 'change'
        }],
        selfWeightDiff: [{
          required: true,
          message: '该项不能为空',
          trigger: 'change'
        }],
        counterWeight: [{
          required: true,
          message: '砝码重量不能为空',
          trigger: 'change'
        },
        { required: true, validator: this.counterWeightIsNum, trigger: 'blur' },
        ],
        upperRange: [{
          required: true,
          message: '最大量程不能为空',
          trigger: 'change'
        },
        { required: true, validator: this.upperRangeIsNum, trigger: 'blur' },],
        // stableRate: [{
        //   required: true,
        //   message: '判稳频率不能为空',
        //   trigger: 'change'
        // },
        // { required: true, validator: this.stableRateIsNum, trigger: 'blur'},],
        counterWeightDiff: [{
          required: true,
          message: '允许差值不能为空',
          trigger: 'change'
        },
        { required: true, validator: this.counterWeightDiffIsNum, trigger: 'blur' },],
        indexValue: [{
          required: true,
          message: '分度值不能为空',
          trigger: 'change'
        },
        { required: true, validator: this.indexValueIsNum, trigger: 'blur' },],
        // stableDiff: [{
        //   required: true,
        //   message: '判稳差值不能为空',
        //   trigger: 'change'
        // },
        // { required: true, validator: this.stableDiffIsNum, trigger: 'blur'},],
        upperLimitClearZero: [{
          required: true,
          message: '清零上限不能为空',
          trigger: 'change'
        },
        { required: true, validator: this.upperLimitClearZeroIsNum, trigger: 'blur' },],
        lowerLimitClearZero: [{
          required: true,
          message: '清零下限不能为空',
          trigger: 'change'
        },
        { required: true, validator: this.lowerLimitClearZeroIsNum, trigger: 'blur' },
        ]
      },
      activeMenu: ''
    }
  },
  created () {
    this.tableHeight = (window.innerHeight - 220) > 500 ? (window.innerHeight - 220) : 500;
    this.activeMenu = window.top.localStorage.getItem('activeMenu')
  },
  mounted () {
    this.getDataList();
    this.getDataList2();
  },
  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);
      // 将对应的重量转换为吨后显示
      this.baseData.counterWeight = Math.floor((this.baseData.counterWeight - 0) / 10) / 100
      this.baseData.counterWeightDiff = Math.floor((this.baseData.counterWeightDiff - 0) / 10) / 100
      this.baseData.upperRange = Math.floor((this.baseData.upperRange - 0) / 10) / 100
      this.baseData.indexValue = Math.floor((this.baseData.indexValue - 0) / 10) / 100
      this.baseData.stableDiff = Math.floor((this.baseData.stableDiff - 0) / 10) / 100
      this.baseData.upperLimitClearZero = Math.floor((this.baseData.upperLimitClearZero - 0) / 10) / 100
      this.baseData.lowerLimitClearZero = Math.floor((this.baseData.lowerLimitClearZero - 0) / 10) / 100
      this.baseData.selfWeightDiff = Math.floor((this.baseData.selfWeightDiff - 0) / 10) / 100
      this.getDataList4(this.baseData.baseSpotNo)
    },
    counterWeightIsNum (rule, value, callback) {
      const patrn = /^\d+(\.\d+)?$/
      if (!patrn.test(this.baseData.counterWeight)) {
        callback(new Error('请输入数字！'))
      }
      // else if (Number (this.baseData.counterWeight) >= 1000) {
      //   callback(new Error('请输入小于1000的数！'))
      // } 
      else {
        callback()
      }
    },
    upperRangeIsNum (rule, value, callback) {
      const patrn = /^\d+(\.\d+)?$/
      if (!patrn.test(this.baseData.upperRange)) {
        callback(new Error('请输入数字！'))
      }
      // else if (Number (this.baseData.upperRange) >= 1000) {
      //   callback(new Error('请请输入小于1000的数！'))
      // } 
      else {
        callback()
      }
    },
    counterWeightDiffIsNum (rule, value, callback) {
      const patrn = /^\d+(\.\d+)?$/
      if (!patrn.test(this.baseData.counterWeightDiff)) {
        callback(new Error('请输入数字！'))
      }
      // else if (Number (this.baseData.counterWeightDiff) >= 1000) {
      //   callback(new Error('请输入小于1000的数！'))
      // }  
      else if (Number(this.baseData.counterWeightDiff) >= Number(this.baseData.counterWeight)) {
        callback(new Error('不能大于等于砝码重量！'))
      } else {
        callback()
      }
    },
    stableRateIsNum (rule, value, callback) {
      const patrn = /^[0-9]*$/
      if (!patrn.test(this.baseData.stableRate)) {
        callback(new Error('请输入整数！'))
      } else {
        callback()
      }
    },
    indexValueIsNum (rule, value, callback) {
      const patrn = /^\d+(\.\d+)?$/
      if (!patrn.test(this.baseData.indexValue)) {
        callback(new Error('请输入数字！'))
      }
      // else if (Number (this.baseData.indexValue) >= 1000) {
      //   callback(new Error('请输入小于1000的数！'))
      // } 
      else {
        callback()
      }
    },
    stableDiffIsNum (rule, value, callback) {
      const patrn = /^\d+(\.\d+)?$/
      if (!patrn.test(this.baseData.stableDiff)) {
        callback(new Error('请输入数字！'))
      }
      // else if (Number (this.baseData.stableDiff) >= 1000) {
      //   callback(new Error('请输入小于1000的数！'))
      // } 
      else {
        callback()
      }
    },
    upperLimitClearZeroIsNum (rule, value, callback) {
      const patrn = /^\d+(\.\d+)?$/
      if (!patrn.test(this.baseData.upperLimitClearZero)) {
        callback(new Error('请输入数字！'))
      }
      // else if (Number (this.baseData.upperLimitClearZero) >= 1000) {
      //   callback(new Error('请输入小于1000的数！'))
      // } 
      else {
        callback()
      }
    },
    lowerLimitClearZeroIsNum (rule, value, callback) {
      const patrn = /^\-?[0-9]\d*.?\d*$/g
      if (!patrn.test(this.baseData.lowerLimitClearZero)) {
        callback(new Error('请输入数字！'))
      }
      // else if (Number (this.baseData.lowerLimitClearZero) <= -1000) {
      //   callback(new Error('请输入大于-1000的数！'))
      // } 
      else if (Number(this.baseData.lowerLimitClearZero) >= Number(this.baseData.upperLimitClearZero)) {
        callback(new Error('下限不允许大于上限！'))
      } else {
        callback()
      }
    },
    // searchData() {
    //   this.dataLoading = true;
    //   this.page.pageNum = 1;
    //   this.axios.get(meterbasescaleranges + "like/?pageNum=" + this.page.pageNum + "&pageSize=" + this.page.pageSize +
    //       "&carrierUnitName=" + this.search.carrierUnitName + "&cusSupCarNo=" + this.search.cusSupCarNo)
    //     .then(res => {
    //       this.dataLoading = false;
    //       this.table.list = res.data.list;
    //       this.page.totalPage = res.data.total;
    //     }).catch(e => {
    //       this.dataLoading = false;
    //     });
    // },
    addData () {
      let _this = this;
      _this.$refs['baseData'].validate((valid) => {
        if (valid) {
          let baseDataAdd = {};
          baseDataAdd.counterWeight = _this.baseData.counterWeight * 1000
          baseDataAdd.upperRange = _this.baseData.upperRange * 1000
          baseDataAdd.stableRate = _this.baseData.stableRate
          baseDataAdd.counterWeightDiff = _this.baseData.counterWeightDiff * 1000
          baseDataAdd.indexValue = _this.baseData.indexValue * 1000
          baseDataAdd.stableDiff = _this.baseData.stableDiff * 1000
          baseDataAdd.upperLimitClearZero = _this.baseData.upperLimitClearZero * 1000
          baseDataAdd.lowerLimitClearZero = _this.baseData.lowerLimitClearZero * 1000
          baseDataAdd.baseSpotNo = _this.baseData.baseSpotNo;
          baseDataAdd.scalePointNo = _this.baseData.scalePointNo;
          baseDataAdd.selfWeightDiff = this.baseData.selfWeightDiff * 1000;
          baseDataAdd.baseSpotName = _this.getCode(this.baseData.baseSpotNo, this.meteringPoint, 'baseSpotNo', 'baseSpotName');
          baseDataAdd.scalePointName = _this.getCode(this.baseData.scalePointNo, this.balancePoint, 'scalePointNo', 'scalePointName');
          _this.operateLoading = true;
          add(meterbasescaleranges, 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.operateLoading = true;
          _this.baseData.counterWeight = _this.baseData.counterWeight * 1000
          _this.baseData.upperRange = _this.baseData.upperRange * 1000
          _this.baseData.counterWeightDiff = _this.baseData.counterWeightDiff * 1000
          _this.baseData.indexValue = _this.baseData.indexValue * 1000
          _this.baseData.stableDiff = _this.baseData.stableDiff * 1000
          _this.baseData.upperLimitClearZero = _this.baseData.upperLimitClearZero * 1000
          _this.baseData.lowerLimitClearZero = _this.baseData.lowerLimitClearZero * 1000
          _this.baseData.selfWeightDiff = this.baseData.selfWeightDiff * 1000;
          _this.baseData.baseSpotName = _this.getCode(this.baseData.baseSpotNo, this.meteringPoint, 'baseSpotNo', 'baseSpotName');
          _this.baseData.scalePointName = _this.getCode(this.baseData.scalePointNo, this.balancePoint, 'scalePointNo', 'scalePointName');
          modify(meterbasescaleranges + _this.baseData.scaleRangeNo + '/', _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(meterbasescaleranges + "Recovery", _this.multipleSelection, (e) => {
    //     _this.operateLoading = false;
    //     if (!e) {
    //       _this.getDataList();
    //     }
    //   }, "服役成功");
    // },
    // abolishData() {
    //   let _this = this;
    //   _this.operateLoading = true;
    //   discard(meterbasescaleranges + "abolish", _this.multipleSelection, (e) => {
    //     _this.operateLoading = false;
    //     if (!e) {
    //       _this.getDataList();
    //     }
    //   }, "停役成功");
    // },
    deleteData () {
      this.$confirm('确定删除选中的配置吗？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      })
        .then(() => {
          this.operateLoading = true;
          Delete(meterbasescaleranges, 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();
    },

    pageCurrentChange (index) {
      this.page.pageNum = index;
      this.getDataList();
    },
    getDataList () {
      this.dataLoading = true;
      this.axios.get(meterbasescaleranges + '?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;
        });
    },
    // tableRowClassName({
    //   row,
    //   rowIndex
    // }) {
    //   if (row.validFlag != 0) {
    //     return 'error-row2';
    //   }
    //   return '';
    // },
    getDataList2 () {
      this.axios.get(meterbasespotinfos + 'noPage' + '?validFlag=1')
        .then(res => {
          this.meteringPoint = res.data;
          this.baseData.baseSpotNo = res.data.length > 0 ? res.data[0].baseSpotNo : ''
          this.getDataList3(res.data[0].baseSpotNo)
        });
    },
    getDataList3 (baseSpotNo) {
      this.axios.get(meterbasescalepoints + 'noPage' + '?validFlag=1' + '&baseSpotNo=' + baseSpotNo)
        .then(res => {
          this.balancePoint = res.data;
          this.baseData.scalePointNo = res.data.length > 0 ? res.data[0].scalePointNo : ''
        });
    },
    getDataList4 (baseSpotNo) {
      this.axios.get(meterbasescalepoints + 'noPage' + '?validFlag=1' + '&baseSpotNo=' + baseSpotNo)
        .then(res => {
          this.balancePoint = res.data;
        });
    }
  },
  filters: {
    num: (val, fix = 2) => {
      val = val.toFixed(fix);	// 保留小数2位
      val = "" + val;	// 转换成字符串
      var int = val.slice(0, fix * -1 - 1);	// 拿到整数
      var ext = val.slice(fix * -1 - 1);	// 获取到小数
      //每个三位价格逗号
      int = int.split("").reverse().join("") // 翻转整数
      var temp = ""; // 临时变量
      for (var i = 0; i < int.length; i++) {
        temp += int[i];
        if ((i + 1) % 3 == 0 && i != int.length - 1) {
          temp += ",";	// 每隔三个数字拼接一个逗号
        }
      }
      temp = temp.split("").reverse().join("");	// 加完逗号之后翻转
      temp = temp + ext;	// 整数小数拼接
      return temp;	// 返回
    }
  }
}
</script>

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