<!--仪表回零配置-->
<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"
            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="100px"
            prop="baseSpotName"
            label="计量点名称"
            align="center"
          ></el-table-column>
          <el-table-column
            sortable
            :show-overflow-tooltip="true"
            min-width="100px"
            prop="scalePointNo"
            label="秤点编号"
            align="center"
          ></el-table-column>
          <el-table-column
            sortable
            :show-overflow-tooltip="true"
            min-width="120px"
            prop="scalePointName"
            label="秤点名称"
            align="center"
          ></el-table-column>
          <el-table-column
            sortable
            :show-overflow-tooltip="true"
            min-width="120px"
            prop="upperLimitWeight"
            label="上限重量（T）"
            align="right"
          >
            <template slot-scope="scope">
              {{ Math.floor((scope.row.upperLimitWeight - 0) / 10) / 100 }}
            </template>
          </el-table-column>
          <el-table-column
            sortable
            :show-overflow-tooltip="true"
            min-width="120px"
            prop="lowerLimitWeight"
            label="下限重量（T）"
            align="right"
          >
            <template slot-scope="scope">
              {{ Math.floor((scope.row.lowerLimitWeight - 0) / 10) / 100 }}
            </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-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"
          :rules="ruleValidate"
          :model="baseData"
        >
          <el-form-item prop="baseSpotNo" label="计量点">
            <el-select
              v-model="baseData.baseSpotNo"
              clearable
              filterable
              collapse-tags
              size="small"
              style="width: 150px"
              @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="秤点">
            <el-select
              v-model="baseData.scalePointNo"
              clearable
              filterable
              collapse-tags
              size="small"
              style="width: 150px"
            >
              <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="upperLimitWeight" label="上限重量(T)">
            <el-input
              v-model="baseData.upperLimitWeight"
              clearable
              size="small"
              style="width: 150px"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
          <el-form-item prop="lowerLimitWeight" label="下限重量(T)">
            <el-input
              v-model="baseData.lowerLimitWeight"
              clearable
              size="small"
              style="width: 150px"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
          <el-form-item prop="memo" label="备注">
            <el-input
              v-model="baseData.memo"
              size="small"
              clearable
              style="width: 150px"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import {
  meterbasespotinfos,
  meterbasescalepoints,
  meterbasereturnzeros
} from '../../../utils/api.js';
import {
  add,
  modify,
  Delete
} from '../../../utils/httpRequest.js';
export default {
  data () {
    return {
      dataLoading: false,
      operateLoading: false,
      // meteringPointIndex: 0,
      // balancePointIndex: 0,
      meteringPoint: [],
      balancePoint: [],
      baseData: {
        upperLimitWeight: '',
        lowerLimitWeight: '',
        memo: ''
      },
      page: {
        pageSize: 500,
        pageNum: 1,
        totalPage: 0
      },
      table: {
        list: []
      },
      multipleSelection: [],
      icoreFilterFlag: true,
      tableHeight: 0,
      ruleValidate: {
        upperLimitWeight: [{
          required: true,
          message: '上限重量不能为空',
          trigger: 'change'
        },
        { required: true, validator: this.upperLimitWeightIsNum, trigger: 'blur' },],
        lowerLimitWeight: [{
          required: true,
          message: '下限重量不能为空',
          trigger: 'change'
        },
        { required: true, validator: this.lowerLimitWeightIsNum, trigger: 'blur' },],
        baseSpotNo: [{
          required: true,
          message: '该项不能为空',
          trigger: 'change'
        }],
        // scalePointNo: [{
        //   required: true,
        //   message: '该项不能为空',
        //   trigger: 'change'
        // }]
      },
      activeMenu: ''
    }
  },
  created () {
    this.tableHeight = (window.innerHeight - 220) > 500 ? window.innerHeight - 220 : 500;
    this.activeMenu = window.top.localStorage.getItem('activeMenu')
  },
  mounted () {
    this.getDataList();
    this.getDataList2();
    this.getDataList3();
  },
  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.lowerLimitWeight = Math.floor((row.lowerLimitWeight - 0) / 10) / 100;
      this.baseData.upperLimitWeight = Math.floor((row.upperLimitWeight - 0) / 10) / 100;
      this.getDataList4(this.baseData.baseSpotNo)
    },
    upperLimitWeightIsNum (rule, value, callback) {
      const patrn = /^\d+(\.\d+)?$/
      if (!patrn.test(this.baseData.upperLimitWeight)) {
        callback(new Error('请输入数字！'))
      } else if (Number(this.baseData.upperLimitWeight) >= 1000) {
        callback(new Error('请输入小于1000的数！'))
      } else {
        callback()
      }
    },
    lowerLimitWeightIsNum (rule, value, callback) {
      const patrn = /^\-?[0-9]\d*.?\d*$/g
      if (!patrn.test(this.baseData.lowerLimitWeight)) {
        callback(new Error('请输入数字！'))
      } else if (Number(this.baseData.lowerLimitWeight) <= -1000) {
        callback(new Error('请输入大于-1000的数！'))
      } else if (Number(this.baseData.lowerLimitWeight) > Number(this.baseData.upperLimitWeight)) {
        callback(new Error('下限不允许大于上限！'))
      } else {
        callback()
      }
    },
    addData () {
      let _this = this;
      _this.$refs['baseData'].validate((valid) => {
        if (valid) {
          // 将上下限重量转换为
          let baseDataAdd = {};
          baseDataAdd.upperLimitWeight = _this.baseData.upperLimitWeight * 1000
          baseDataAdd.lowerLimitWeight = _this.baseData.lowerLimitWeight * 1000
          baseDataAdd.memo = _this.baseData.memo
          baseDataAdd.baseSpotNo = _this.baseData.baseSpotNo;
          baseDataAdd.scalePointNo = _this.baseData.scalePointNo;
          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(meterbasereturnzeros, 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.lowerLimitWeight = _this.baseData.lowerLimitWeight * 1000
          _this.baseData.upperLimitWeight = _this.baseData.upperLimitWeight * 1000
          _this.operateLoading = true;
          _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(meterbasereturnzeros + _this.baseData.returnZeroNo + '/', _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(meterbasereturnzeros, 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(meterbasereturnzeros + '?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;
        });
    },
    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;
          // this.baseData.scalePointNo = res.data.length > 0 ? res.data[0].scalePointNo : ''
        });
    }
  }
}
</script>

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