<!--期限皮重车辆配置-->
<template>
  <div class="systemBase common-container-deriction">
    <div style="margin-top: 10px;  border-bottom: 1px solid #d5d5d5;">
         <el-form :inline="true" :model="search">
         <el-form-item>
             <div style="font-size: 16px; padding: 0px 20px;">期限皮重车辆配置
             </div>
         </el-form-item>
         <el-form-item prop="carNo" label=" 车号">
           <el-input v-model="search.carNo" clearable placeholder="请输入" width="120px" size="mini" />
         </el-form-item>
         <el-form-item prop="valueFlag" label=" 状态">
           <el-select v-model="search.valueFlag" clearable filterable width="120px" collapse-tags size="mini">
              <el-option v-for="(item,index) in valueFlag" :key="index" :label="item.name" :value="index">
              </el-option>
            </el-select>
         </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" @click="addData"
             v-loading.fullscreen.lock="operateLoading"  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 label-width="20px">
              <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-form-item>
        <el-form-item label-width="20px">
              <el-button size="mini" type="primary" icon="el-icon-check"
              v-loading.fullscreen.lock="operateLoading" @click="recoveryData"  v-privilege="activeMenu + 'RECOVERY'">服役</el-button>
         </el-form-item>
         <el-form-item label-width="20px">
              <el-upload
              class="upload"
              action=""
              :multiple="false"
              :show-file-list="false"
              accept="csv, application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
              :http-request="httpRequest">
              <el-button size="mini" type="primary" icon="el-icon-download"  v-privilege="activeMenu + 'IMPORT'">导入</el-button>
              </el-upload>
         </el-form-item>
         </el-form>
    </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="carNo" min-width="120" label="车号" align="center"></el-table-column>
        <el-table-column sortable :show-overflow-tooltip="true" prop="valueFlag" min-width="80" 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="meterNatureName" min-width="100" label="计量属性" align="center"></el-table-column>
        <el-table-column sortable :show-overflow-tooltip="true" prop="carOwnerName" min-width="100" label="车主姓名" align="center"></el-table-column>
        <el-table-column sortable :show-overflow-tooltip="true" prop="carDriverName" min-width="100" label="驾驶员" align="center"></el-table-column>
        <el-table-column sortable :show-overflow-tooltip="true" prop="carUnderUnit" min-width="260" label="隶属单位" align="center"></el-table-column>
        <el-table-column sortable :show-overflow-tooltip="true" prop="memo" min-width="200" 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="80px" :inline="true" :rules="ruleValidate" :model="baseData">
         <el-form-item prop="carNo" label="车号">
           <el-input v-model="baseData.carNo" clearable size="mini" placeholder="请输入" style="width:150px;"></el-input>
         </el-form-item>
         <el-form-item prop="carDriverName" label="驾驶员">
           <el-input v-model="baseData.carDriverName" clearable size="mini" placeholder="请输入" style="width:150px;"></el-input>
         </el-form-item>
         <el-form-item prop="carOwnerName" label="车主姓名">
           <el-input v-model="baseData.carOwnerName" clearable size="mini" placeholder="请输入" style="width:150px;"></el-input>
         </el-form-item>
         <el-form-item prop="carUnderUnit" label="隶属单位">
           <el-input v-model="baseData.carUnderUnit" clearable size="mini" placeholder="请输入" style="width:150px;"></el-input>
         </el-form-item>
         <el-form-item prop="meterNatureNo" label="计量属性">
           <el-select v-model="baseData.meterNatureNo" clearable filterable collapse-tags size="small"  style="width:150px">
             <el-option v-for="(item,index) in meteringType" :key="index" :label="item.baseName" :value="item.baseCode">
             </el-option>
           </el-select>
        </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 {
    meterbasetermtarecars,
    combaseinfos
  } from '../../../utils/api.js';
  import {
    discard,
    Recovery,
    add,
    modify,
    Delete,
    upload
  } from '../../../utils/httpRequest.js';
  import {
  getCookie
} from '@/utils/util.js';
import XLSX from 'xlsx'
export default {
    data () {
      return {
        dataLoading: false,
        operateLoading: false,
        icoreFilterFlag: true,
        valueFlagIndex: 0,
        meteringType: [],
        valueFlag: [
          {id: '0', name: '服役'},
          {id: '1', name: '停役'}
        ],
        baseData: {
          carNo: '',
          carDriverName: '',
          carOwnerName: '',
          carUnderUnit: '',
          memo: '',
          meterNatureNo: '',
        },
        page: {
          pageSize: 500,
          pageNum: 1,
          totalPage: 0
        },
        table: {
          list: []
        },
        valueFlag1: '',
        list: [],
        multipleSelection: [],
        tableHeight: 0,
        ruleValidate: {
          carNo: [{
            required: true,
            message: '车号不能为空',
            trigger: 'change'
          }],
          carDriverName: [{
            required: true,
            message: '驾驶员不能为空',
            trigger: 'change'
          }],
          carOwnerName: [{
            required: true,
            message: '车主姓名不能为空',
            trigger: 'change'
          }],
          carUnderUnit: [{
            required: true,
            message: '隶属单位不能为空',
            trigger: 'change'
          }],
          meterNatureNo: [{
            required: true,
            message: '计量属性不能为空',
            trigger: 'change'
          }]
        },
        search: {
          carNo: '',
          valueFlag: ''
        },
        activeMenu: ''
      }
    },
    created () {
      this.tableHeight = (window.innerHeight - 220) > 400 ? window.innerHeight - 220 : 400;
      this.activeMenu = window.top.localStorage.getItem('activeMenu')
    },
    mounted () {
      // this.tableHeight = this.getTableHeight(this.$refs['dataTable'].$el) - 80;
      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) {
        let row1 = Object.assign ({}, row)
        this.baseData = row1;
      },
      baseDataClear () {
        this.baseData.carNo = '';
        this.baseData.carDriverName = '';
        this.baseData.carOwnerName = '';
        this.baseData.carUnderUnit = '';
        this.baseData.memo = '';
      },
      searchDatas () {
        this.page.pageNum = 1;
        this.searchData()
      },
      searchData () {
        this.dataLoading = true;
        this.icoreFilterFlag = false
        this.axios.get(meterbasetermtarecars + 'like/?pageNum=' + this.page.pageNum + '&pageSize=' + this.page.pageSize +
            '&carNo=' + this.search.carNo + '&valueFlag=' + this.search.valueFlag)
          .then(res => {
            this.dataLoading = false;
            this.table.list = res.data.list;
            this.page.totalPage = res.data.total;
            this.icoreFilterFlag = true
          }).catch(e => {
            this.dataLoading = false;
            this.icoreFilterFlag = true
          });
      },
      addData () {
        let _this = this;
        _this.$refs['baseData'].validate((valid) => {
          if (valid) {
            _this.operateLoading = true;
            let baseDataAdd = {};
            baseDataAdd.carNo = _this.baseData.carNo
            baseDataAdd.carDriverName = _this.baseData.carDriverName
            baseDataAdd.carOwnerName = _this.baseData.carOwnerName
            baseDataAdd.carUnderUnit = _this.baseData.carUnderUnit
            baseDataAdd.meterNatureNo = _this.baseData.meterNatureNo
            baseDataAdd.memo = _this.baseData.memo
            baseDataAdd.meterNatureName = _this.getCode (this.baseData.meterNatureNo, this.meteringType, 'baseCode', 'baseName');
            add(meterbasetermtarecars, baseDataAdd, (e) => {
              _this.operateLoading = false;
              _this.getDataList();
              _this.baseDataClear();
              if (!e) {
                _this.$refs['baseData'].resetFields && _this.$refs['baseData'].resetFields();
              }
            })
          }
        });
      },
      modifyData () {
        let _this = this;
        _this.$refs['baseData'].validate((valid) => {
          if (valid) {
            _this.operateLoading = true;
            var carNo1 = _this.baseData.id;
            _this.baseData.id = _this.baseData.carNo;
            _this.baseData.carNo = carNo1;
            _this.baseData.meterNatureName = _this.getCode (this.baseData.meterNatureNo, this.meteringType, 'baseCode', 'baseName');
            modify(meterbasetermtarecars + _this.baseData.carNo + '/', _this.baseData, (e) => {
              _this.operateLoading = false;
              _this.getDataList();
              _this.baseDataClear();
              if (!e) {
                _this.$refs['baseData'].resetFields && _this.$refs['baseData'].resetFields();
              }
            })
          }
        });
      },
      recoveryData () {
        let _this = this;
        _this.operateLoading = true;
        Recovery(meterbasetermtarecars + 'Recovery', _this.multipleSelection, (e) => {
          _this.operateLoading = false;
          if (!e) {
            _this.getDataList();
          }
        }, '服役成功');
      },
      abolishData () {
        let _this = this;
        _this.operateLoading = true;
        discard(meterbasetermtarecars + 'abolish', _this.multipleSelection, (e) => {
          _this.operateLoading = false;
          if (!e) {
            _this.getDataList();
          }
        }, '停役成功');
      },
      deleteData () {
        this.$confirm('确定删除选中的客运车辆？', {
            confirmButtonText: '确定',
            cancelButtonText: '取消'
          })
          .then(() => {
            this.operateLoading = true;
            Delete(meterbasetermtarecars, this.multipleSelection, (e) => {
              this.operateLoading = false;
              if (!e) {
                this.getDataList();
              }
            })
          })
          .catch(action => {
            this.$message({
              type: 'info',
              message: action === 'cancel' ? '放弃保存并离开页面' : '停留在当前页面'
            })
          });
      },
      httpRequest (e) {
      let file = e.file // 文件信息
      if (!file) {
          // 没有文件
          return false
        } else if (!/\.(xls|xlsx)$/.test(file.name.toLowerCase())) {
          // 格式根据自己需求定义
          this.$message.error('上传格式不正确，请上传xls或者xlsx格式')
          return false
        }
        const fileReader = new FileReader()
        fileReader.onload = (ev) => {
          let _this = this;
          try {
            const data = ev.target.result
            const workbook = XLSX.read(data, {
              type: 'binary' // 以字符编码的方式解析
            })
            const exlname = workbook.SheetNames[0] // 取第一张表
            _this.jsonData = XLSX.utils.sheet_to_json(workbook.Sheets[exlname]) // 生成json表格内容
            for (var j = 0; j < _this.jsonData.length; j++) {
              // 按照生成jsonData 的数据格式 处理 生成所需表格
               if (_this.jsonData[j]['状态'] === '停役') {
                  _this.valueFlag1 = 1
                } else {
                  _this.valueFlag1 = 0
                }
              _this.list.push({
                carNo: _this.jsonData[j]['车号'],
                valueFlag: _this.valueFlag1,
                carOwnerName: _this.jsonData[j]['车主姓名'],
                carDriverName: _this.jsonData[j]['驾驶员'],
                carUnderUnit: _this.jsonData[j]['隶属单位'],
                memo: _this.jsonData[j]['备注']
              })
            }
            _this.operateLoading = true;
            upload(meterbasetermtarecars + 'list', _this.list, (e) => {
              _this.operateLoading = false;
              _this.list = [];
              _this.getDataList();
              if (!e) {
                _this.getDataList();
              }
            });
          } catch (e) {
            return false
          }
      }
      fileReader.readAsBinaryString(file)
     },
      handleSelectionChange (val) {
        this.multipleSelection = val;
      },
      getTableHeight (dom) {
        return (window.innerHeight - dom.offsetTop);
      },
      pageSizeChange (size) {
        this.page.pageSize = size;
        this.searchData()
      },

      pageCurrentChange (index) {
        this.page.pageNum = index;
        this.searchData()
      },
      getDataList () {
        this.dataLoading = true;
        this.axios.get(meterbasetermtarecars + '?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;
          });
      },
       getDataList3 () {
        this.axios.get(combaseinfos + 'noPage' + '?pBaseCode=001004'+ '&validFlag=1')
          .then(res => {
            this.meteringType = res.data;
            this.baseData.meterNatureNo = res.data.length > 0 ? res.data[0].baseCode : ''
          })
      },
      tableRowClassName ({
        row,
        rowIndex
      }) {
        if (row.valueFlag !== '0') {
          return 'error-row2';
        }
        return '';
      }
    }
  }
</script>

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