<!--历史皮重计算配置-->
<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"
        @current-change="handleCurrentChange"
        :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
          :show-overflow-tooltip="true"
          min-width="100px"
          align="center"
          label="皮重类型"
          prop="typeName"
        ></el-table-column>
        <el-table-column
          sortable
          :show-overflow-tooltip="true"
          prop="countTypeName"
          min-width="120px"
          label="计算方式"
          align="center"
        ></el-table-column>
        <el-table-column
          sortable
          :show-overflow-tooltip="true"
          prop="countEdition"
          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="fixedWeightValue"
          min-width="100px"
          label="固重值（kg）"
          align="right"
        ></el-table-column>
        <el-table-column
          sortable
          :show-overflow-tooltip="true"
          prop="contrastTypeName"
          min-width="120px"
          label="对比类型"
          align="center"
        ></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="typeName" label="皮重类型">
          <el-select
            v-model="baseData.typeName"
            clearable
            filterable
            collapse-tags
            size="mini"
            style="width: 150px"
          >
            <el-option
              v-for="(item, index) in tareTypeList"
              :key="index"
              :label="item.baseName"
              :value="item.baseName"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="countTypeName" label="计算方式">
          <el-select
            v-model="baseData.countTypeName"
            clearable
            filterable
            collapse-tags
            size="mini"
            @change="selectTrigger(baseData.countTypeName)"
            style="width: 150px"
          >
            <el-option
              v-for="(item, index) in countType"
              :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
            :readonly="isReteValue"
            :disabled="isReteValue"
            size="small"
            style="width: 150px"
          ></el-input>
        </el-form-item>
        <el-form-item prop="contrastTypeName" label="对比类型">
          <el-select
            v-model="baseData.contrastTypeName"
            clearable
            filterable
            collapse-tags
            size="mini"
            style="width: 150px"
          >
            <el-option
              v-for="(item, index) in contrastType"
              :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
            :readonly="!isReteValue"
            :disabled="!isReteValue"
            size="small"
            style="width: 150px"
          ></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>
</template>

<script>
import {
  meterbasehistarecounts,
  combaseinfos
} from '../../../utils/api.js';
import {
  discard,
  Recovery,
  add,
  modify
} from '../../../utils/httpRequest.js';
import { exportToExcel } from '../../../utils/utils.js'

export default {
  data () {
    return {
      dataLoading: false,
      operateLoading: false,
      isReteValue: true,
      icoreFilterFlag: true,
      countType: [
        // {id: '0001', name: '固重'},
        // {id: '0002', name: '比例'}
      ],
      contrastType: [
        // {id: '0001', name: '上一次皮重'},
        // {id: '0002', name: '平均皮重'}
      ],
      baseData: {
        countTypeName: '',
        contrastTypeName: '',
        fixedWeightValue: '',
        rateValue: '',
        memo: '',
        typeName: ''
      },
      isInput: true,
      page: {
        pageSize: 500,
        pageNum: 1,
        totalPage: 0
      },
      table: {
        list: []
      },
      multipleSelection: {},
      tableHeight: 0,
      ruleValidate: {
        rateValue: [{
          required: false,
          validator: this.rateValueEmpty,
          trigger: 'change'
        }],
        fixedWeightValue: [{
          required: true,
          validator: this.fixedWeightValueEmpty,
          trigger: 'change'
        }],
        countTypeName: [{
          required: true,
          message: '计算方式不能为空',
          trigger: 'change'
        }],
        contrastTypeName: [{
          required: true,
          message: '对比类型不能为空',
          trigger: 'change'
        }],
        typeName: [{
          required: true,
          message: '皮重类型不能为空',
          trigger: 'change'
        }],
      },
      activeMenu: '',
      tareTypeList: []
    }
  },
  created () {
    this.tableHeight = window.innerHeight - 220 > 500 ? window.innerHeight - 220 : 500;
    this.activeMenu = window.top.localStorage.getItem('activeMenu')
  },
  mounted () {
    // this.tableHeight = this.getTableHeight(this.$refs['dataTable'].$el) - 80;
    this.getDataList();
    this.getCountType();
    this.getContrastType();
    this.getTareType();
  },
  methods: {
    getTareType () {
      this.axios.get('pass/systemBase/v1/combaseinfos/?pageNum=1&pageSize=500&pBaseCode=001033')
        .then(res => {
          console.log(res, '基础数据返回结果')
          this.tareTypeList = [...res.data.list];
        })
    },
    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.countTypeName === '比例') {
        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 (countTypeName) {
      if (countTypeName === '比例') {
        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.countTypeName === '比例' && (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 || Number(this.baseData.rateValue) < 0) {
          return callback(new Error('请输入为0-100的数字！'))
        } else {
          return callback()
        }
      } else {
        return callback()
      }
    },
    fixedWeightValueEmpty (rule, value, callback) {
      const age = /^[0-9]*$/
      if (this.baseData.countTypeName === '固重' && (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 (this.baseData.fixedWeightValue.length > 3 && this.baseData.fixedWeightValue - 0 > 1000) {
          return callback(new Error('请输入为0-1000的数字！'))
        } else {
          return callback()
        }
      } else {
        return callback()
      }
    },
    baseDataClear () {
      this.baseData.fixedWeightValue = '';
      this.baseData.rateValue = '';
      this.baseData.memo = '';
    },
    searchData () {
      this.page.pageNum = 1;
      this.getDataList()
    },
    addData () {
      let _this = this;
      _this.$refs['baseData'].validate(async (valid) => {
        if (this.baseData.typeName.indexOf('通用') !== -1) {
          const result = await this.$confirm('是否确认新增？新增数据有可能将原来相同类型的数据状态置为无效！', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).catch(e => 'cancel')
          if (result === 'cancel') {
            return false;
          }
        }
        if (valid) {
          _this.operateLoading = true;
          let baseDataAdd = {};
          baseDataAdd.fixedWeightValue = _this.baseData.fixedWeightValue
          baseDataAdd.rateValue = _this.baseData.rateValue
          baseDataAdd.memo = _this.baseData.memo
          baseDataAdd.contrastTypeName = _this.baseData.contrastTypeName
          baseDataAdd.countTypeName = _this.baseData.countTypeName
          baseDataAdd.contrastTypeNo = _this.getCode(this.baseData.contrastTypeName, this.contrastType, 'baseName', 'baseCode');
          baseDataAdd.countTypeNo = _this.getCode(this.baseData.countTypeName, this.countType, 'baseName', 'baseCode');
          add(meterbasehistarecounts, baseDataAdd, (e) => {
            _this.operateLoading = false;
            _this.getDataList();
            _this.baseDataClear();
            if (!e) {
              _this.$refs['baseData'].resetFields && _this.$refs['baseData'].resetFields();
            }
          })
        } else {
          this.$message.error('请规范填写数据')
        }
      });
    },
    modifyData () {
      let _this = this;
      _this.$refs['baseData'].validate((valid) => {
        if (valid) {
          _this.operateLoading = true;
          _this.baseData.contrastTypeNo = _this.getCode(this.baseData.contrastTypeName, this.contrastType, 'baseName', 'baseCode');
          _this.baseData.countTypeNo = _this.getCode(this.baseData.countTypeName, this.countType, 'baseName', 'baseCode');
          modify(meterbasehistarecounts + _this.baseData.countNo + '/', _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/meterbasehistarecounts/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/meterbasehistarecounts/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)
      })
    },
    // deleteData () {
    //   this.$confirm('确定删除选中的客运车辆？', {
    //       confirmButtonText: '确定',
    //       cancelButtonText: '取消'
    //     })
    //     .then(() => {
    //       this.operateLoading = true;
    //       Delete(meterbasehistarecounts, this.multipleSelection, (e) => {
    //         this.operateLoading = false;
    //         if (!e) {
    //           this.getDataList();
    //         }
    //       })
    //     })
    //     .catch(action => {
    //       this.$message({
    //         type: 'info',
    //         message: action === 'cancel' ? '放弃保存并离开页面' : '停留在当前页面'
    //       })
    //     });
    // },
    handleCurrentChange (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(meterbasehistarecounts + '?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;
        });
    },
    getCountType () {
      this.axios.get(combaseinfos + 'noPage' + '?pBaseCode=001011' + '&validFlag=1')
        .then(res => {
          this.countType = res.data;
          this.baseData.countTypeName = res.data[0].baseName
        })
    },
    getContrastType () {
      this.axios.get(combaseinfos + 'noPage' + '?pBaseCode=001012' + '&validFlag=1')
        .then(res => {
          this.contrastType = res.data;
          this.baseData.contrastTypeName = res.data[0].baseName
        })
    },
    tableRowClassName ({
      row,
      rowIndex
    }) {
      if (row.valueFlag !== '0') {
        return 'error-row2';
      }
      return '';
    }
  }
}
</script>

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