<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select v-model="getdataListParm.parammaps.pastureName" placeholder="牧场" class="filter-item" @change="changePastureName">
        <el-option v-for="item in findAllPasture" :key="item.id" :label="item.name" :value="item.name" />
      </el-select>
      <el-select v-model="getdataListParm.parammaps.departmentName" clearable placeholder="部门" class="filter-item">
        <el-option v-for="item in findAllDepart" :key="item.id" :label="item.name" :value="item.name" />
      </el-select>
      <el-autocomplete ref="cardNumber" v-model="getdataListParm.parammaps.cardNumber" style="width:300px" value-key="cardNumber" class="inline-input filter-item" :fetch-suggestions="cardNumberSearch" placeholder="请选择油卡编号" @select="handlecardNumberSelect">
        <template slot-scope="{ item }">
          <div class="name" style="display: inline;">{{ item.cardNumber }}</div>
        </template>
      </el-autocomplete>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="form_search">搜索</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="form_add">新增</el-button>
      <el-button class="filter-item"  style="margin-left: 10px;display: inline-block;" type="info" icon="el-icon-tickets" @click="handleDownloadTemp"> 模板 </el-button>
      <el-button v-if="isOtherinfoExport" class="filter-item" type="success"  style="margin-left: 10px;" icon="el-icon-download" @click="handleDownload">导出</el-button>
      <el-upload :headers="headers" style="margin-left: 10px;display: inline-block;" :data="uploadData" :action="uploadExcelUrl" :show-file-list="false" :before-upload="beforeImportExcel" :on-success="handleImportExcelSuccess">
        <el-button v-waves class="filter-item" type="warning" icon="el-icon-download">导入</el-button>
      </el-upload>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      element-loading-text="给我一点时间"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      :row-style="rowStyle"
      :cell-style="cellStyle"
      class="elTable"
      @sort-change="tableSort"
    >
      <el-table-column label="序号" align="center" type="index" width="50px">
        <template slot-scope="scope">
          <span>{{ scope.$index + (pageNum-1) * pageSize + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="部门" min-width="110px" align="center" prop="departmentName" />
      <el-table-column label="油卡编号" min-width="110px" align="center" prop="cardNumber" />
      <el-table-column label="油卡类型" min-width="110px" align="center" prop="cardType" />
      <el-table-column label="剩余余额" min-width="110px" align="center" sortable prop="cardAmount" />
      <el-table-column label="设备编号" min-width="110px" align="center" prop="assetNumber" />
      <el-table-column label="设备名称" min-width="110px" align="center" prop="assetName" />
      <el-table-column label="油卡状态" min-width="110px" align="center" prop="assetName">
        <template slot-scope="scope">
          <span v-if="scope.row.enable == 0">启用</span>
          <span v-else>停用</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="350" class-name="small-padding fixed-width" fixed="right">
        <template slot-scope="{row}">
          <el-button v-if="row.enable == 0" type="success" size="mini" @click="form_edit(row)">编辑</el-button>
          <el-button type="success" size="mini" @click="handleChange(row)">变更记录</el-button>
          <el-button type="success" size="mini" @click="handleRecharge(row)">充值</el-button>
          <el-button v-if="row.enable == 0" type="danger" size="mini" @click="handleDisable(row)">停用</el-button>
          <el-button v-else type="danger" size="mini" @click="handleDisable(row)">启用</el-button>
          <el-button v-if="row.enable == 1" type="danger" size="mini" @click="form_delete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="getdataListParm.offset" :limit.sync="getdataListParm.pagecount" @pagination="getList" />
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false" width="50%">
      <el-form ref="temp" :rules="rules" :model="temp" label-position="right" label-width="100px" style="width: 800px; margin-left:50px;">
        <el-row>
          <el-col :span="12">
            <el-form-item label="卡号:" prop="cardNumber">
              <el-input ref="cardNumber" v-model="temp.cardNumber" :disabled="dialogStatus=='update'" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="设备：" prop="assetSum">
              <el-autocomplete ref="assetSum" v-model="temp.assetSum" style="width:300px" value-key="assetSum" class="inline-input" :fetch-suggestions="formNumberSearch" placeholder="请选择设备" @select="handleformNameSelect" @blur="blurformNameSelect">
                <template slot-scope="{ item }">
                  <div class="name" style="display: inline;">{{ item.assetName }}</div>
                </template>
              </el-autocomplete>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="牧场：" prop="pastureName">
              <el-input ref="pastureName" v-model="temp.pastureName" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="部门：" prop="departmentName">
              <el-input ref="departmentName" v-model="temp.departmentName" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="卡类型:" prop="cardType">
              <el-select ref="cardType" v-model="temp.cardType" placeholder="卡类型" style="width:100%;">
                <el-option v-for="item in cardTypeList" :key="item.id" :label="item.name" :value="item.name" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="卡余额:" prop="cardAmount">
              <el-input ref="cardAmount" v-model="temp.cardAmount" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="dialogStatus==='create'" ref="createb" :disabled="isokDisable" type="success" @click="add_dialog_save_again()">保存并新增</el-button>
        <el-button type="primary" :disabled="isokDisable" @click="dialogStatus==='create'?add_dialog_save():edit_dialog_save()">保存并关闭</el-button>
        <el-button @click="dialogFormVisible = false;getList()">取消并关闭</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="textMap[tabledialogStatus]" :visible.sync="changeFormVisible" :close-on-click-modal="false" width="50%">
      <el-table
        :key="tableKey"
        v-loading="changelistLoading"
        element-loading-text="给我一点时间"
        :data="changelist"
        border
        fit
        highlight-current-row
        style="width: 100%;"
        :row-style="rowStyle"
        :cell-style="cellStyle"
        class="elTable"
      >
        <el-table-column label="变更日期" align="center" sortable min-width="110px" prop="changeDate" />
        <el-table-column label="变更类型" align="center" min-width="110px" prop="changeType" />
        <el-table-column label="变更前设备" align="center" min-width="110px" prop="beforeMaintenance" />
        <el-table-column label="变更后设备" align="center" min-width="110px" prop="afterMaintenance" />
        <el-table-column label="变更人" align="center" min-width="110px" prop="empname" />
      </el-table>
      <h3 style="font-weight: 300;">{{ cardNumber }}-启停记录</h3>
      <el-table
        :key="tableKey2"
        v-loading="changelistLoading"
        element-loading-text="给我一点时间"
        :data="changelist2"
        border
        fit
        highlight-current-row
        style="width: 100%;"
        :row-style="rowStyle"
        :cell-style="cellStyle"
        class="elTable"
      >
        <el-table-column label="启停日期" align="center" sortable min-width="110px" prop="oildCardDate" />
        <el-table-column label="启停类型" align="center" min-width="110px" prop="statue" />
        <el-table-column label="操作人" align="center" min-width="110px" prop="personName" />
      </el-table>
      <div slot="footer" class="dialog-footer" style="bottom:10px">
        <el-button @click="changeFormVisible = false;getList()">关闭</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="textMap[tabledialogStatus]" :visible.sync="rechargeFormVisible" :close-on-click-modal="false" width="50%">
      <el-table
        :key="tableKey"
        v-loading="rechargelistLoading"
        element-loading-text="给我一点时间"
        :data="rechargelist"
        border
        fit
        highlight-current-row
        style="width: 100%;"
        :row-style="rowStyle"
        :cell-style="cellStyle"
        class="elTable"
      >
        <el-table-column label="日期" align="center" type="index" width="150px">
          <template slot-scope="scope">
            <span>{{ scope.row.dateFormat }}</span>
          </template>
        </el-table-column>
        <el-table-column label="卡号" min-width="110px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.cardCode }}</span>
          </template>
        </el-table-column>
        <el-table-column label="充值金额" width="150px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.rechargeNum }}</span>
          </template>
        </el-table-column>
        <el-table-column label="充值人" width="150px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.empName }}</span>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer" style="bottom:10px">
        <el-button v-if="rechargeTemp.enable == 0" type="success" @click="createRecharge()">充值</el-button>
        <el-button @click="rechargeFormVisible = false;getList()">取消并关闭</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="rechargeFFormVisible" :close-on-click-modal="false" width="50%">
      <el-form ref="temp" :rules="rules" :model="temp" label-position="right" label-width="100px" style="width: 800px; margin-left:50px;">
        <el-row>
          <el-col :span="8">
            <el-form-item label="负责人：" prop="employeId">
              <el-select v-model="temp.employeId" placeholder="负责人" class="filter-item" style="width:100%;">
                <el-option v-for="item in findAllEmploye" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="当前时间：" prop="dateFormat" style="width:100%;">
              <el-date-picker v-model="temp.dateFormat" type="date" placeholder="当前时间" format="yyyy-MM-dd" value-format="yyyy-MM-dd" disabled style="width:100%;" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="充值金额" prop="rechargeNum" style="width:100%;">
              <el-input ref="rechargeNum" v-model="temp.rechargeNum" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="createRechargeData()">确认</el-button>
        <el-button @click="rechargeFFormVisible = false">取消并关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 引入
import { GetDataByName, GetDataByNames, PostDataByName, getRecuData, ExecDataByConfig, failproccess,checkButtons } from '@/api/common'
import waves from '@/directive/waves'
import { parseTime, sortChange,json2excel } from '@/utils/index.js'
import { validateEMail } from '@/utils/validate.js'
import Pagination from '@/components/Pagination'
import { MessageBox } from 'element-ui'
import Cookies from 'js-cookie'
import { getToken } from '@/utils/auth'
export default {
  name: 'Otherinfo',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      isOtherinfoExport:[],
      buttons:[],
      isokDisable: false,
      tableKey: 0,
      tableKey2: 0,
      list: null,
      changelist: null,
      changelist2: null,
      rechargelist: null,
      total: 0,
      listLoading: true,
      changelistLoading: true,
      rechargelistLoading: true,
      formNumberSearchList: [],
      requestParam: {
        name: 'insertAsset',
        offset: 0,
        pagecount: 0,
        parammaps: {}
      },
      requestParam2: {},
      parentDept: [],
      getDeptParm: { name: 'getdeptrecu', idname: 'value', params: [-1] },
      postDataPramas: { },
      getdataListParm: {
        name: 'getOilcardList', page: 1, offset: 1, pagecount: 10, returntype: 'Map',
        parammaps: { pname: '', pastureName: Cookies.get('pasturename') }
      },
      requestFilterParams: {
        name: '', page: 1, offset: 1, pagecount: 10, returntype: 'Map',
        parammaps: {}
      },
      requestFilterParams2: {
        name: '', page: 1, offset: 1, pagecount: 10, returntype: 'Map',
        parammaps: {}
      },
      getchangedataListParm: {
        name: 'getOilcardHistory', page: 1, offset: 1, pagecount: 10, returntype: 'Map',
        parammaps: { }
      },
      getchangedataListParm2: {
        // name: 'getOilcardHistory', page: 1, offset: 1, pagecount: 10, returntype: 'Map',
        // parammaps: { }
      },
      getrechargedataListParm: {
        name: 'getrechargerecordList', page: 1, offset: 1, pagecount: 10, returntype: 'Map',
        parammaps: { }
      },
      cardTypeList: [{ name: 'IC卡', id: '0' }, { name: '磁卡', id: '1' }],
      findAllProvider: [],
      findAllAssetType: [],
      findAllPasture: [],
      findAllDepart: [],
      findAllEmploye: [],
      getDictByName: [],
      findAllAsset: [],
      requestParams: [
        { name: 'findAllProvider', offset: 0, pagecount: 0, params: [] },
        { name: 'findAllAssetType', offset: 0, pagecount: 0, params: [] },
        { name: 'findAllPasture', offset: 0, pagecount: 0, returntype: 'Map', parammaps: { 'id': Cookies.get('pastureid') }},
        // { name: 'findAllDepart', offset: 0, pagecount: 0, parammaps: { 'pastureId': Cookies.get('pastureid') }},
        { name: 'findAllEmploye', offset: 0, pagecount: 0, parammaps: { 'pastureId': Cookies.get('pastureid') }},
        { name: 'findAllAsset', offset: 0, pagecount: 0, params: [] },
        { name: 'getDictByName', offset: 0, pagecount: 0, params: ['资产状态'] }
      ],
      getDepartParam: { name: 'findAllDepart1', offset: 0, pagecount: 0, parammaps: { 'pastureId': Cookies.get('pastureid'), 'eId': Cookies.get('employeid') }},
      dataform: { deptId: '', parentId: '' },
      temp: {},
      dialogFormVisible: false,
      changeFormVisible: false,
      rechargeFormVisible: false,
      rechargeFFormVisible: false,
      tabledialogStatus: '',
      dialogStatus: '',
      textMap: { update: '编辑', create: '新增', change: '变更记录', recharge: '充值记录', changeF: '换卡', rechargeF: '充值' },
      dialogPvVisible: false,
      // 校验规则
      rules: {
        cardNumber: [{ required: true, message: '必填', trigger: 'blur' }],
        cardType: [{ required: true, message: '必填', trigger: 'blur' }],
        cardAmount: [{ required: true, message: '必填', trigger: 'blur' }]
      },
      rechargeTemp: {},
      rowStyle: { maxHeight: 50 + 'px', height: 45 + 'px' },
      cellStyle: { padding: 0 + 'px' },
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      nodeKey: 'value',
      defaultCheckedKeys: [],
      cardNumber: '',
      isPercentage: false,
      percentage: 1,
      downLoadParm:{},
      downLoadList:[]
    }
  },
  computed: {
    // 设置请求头
    headers() {
      return {
        token: getToken()
      }
    },
    uploadData() {
      return {
        name: 'importOilcard',
        importParams: '牧场,车自编号,油卡,类型,上次用油量,部门',
        sheetname: 'SheetJS'
      }
    },
    // 设置上传地址
    uploadExcelUrl() {
      // process.env.VUE_APP_BASE_API是服务器的路径，也是axios的基本路径
      return process.env.VUE_APP_BASE_API + 'authdata/ImportExcel'
    }
  },

  created() {
    const that = this
    GetDataByName({ 'name': 'getUserPCButtons', 'parammaps': { 'jwt_username': Cookies.get('name') }}).then(response => {
      that.buttons = response.data.list
      that.getButtons()
    })
    this.getDownList()
    this.getList()
    this.getDepartDownList()
  },

  methods: {
    getButtons() {
      // 导出
      const OtherinfoExport = 'basic:otherinfo:otherinfoExport'
      const isOtherinfoExport = checkButtons(this.buttons, OtherinfoExport)
      this.isOtherinfoExport = isOtherinfoExport
    },
    tableSort(column) {
      sortChange(column, this.list)
    },
    getDeptList() {
      getRecuData(this.getDeptParm).then(response => {
        this.parentDept = response.data
      })
    },

    popoverHide(checkedIds, checkedData) {
      this.dataform.deptId = checkedIds
      this.dataform.parentId = checkedData.parentid
    },
    providerSearch(queryString, cb) {
      var returnList = this.findAllProvider
      var results = queryString
        ? returnList.filter(this.createFilter(queryString))
        : returnList
      // 调用 callback 返回建议列表的数据
      cb(results)
    },
    createFilter(queryString) {
      return returnValue => {
        return (
          returnValue.assetName.toLowerCase().indexOf(queryString.toLowerCase()) >= 0
        )
      }
    },
    handleSelect(item) {
      console.log(item)
    },

    getList() {
      this.listLoading = true
      GetDataByName(this.getdataListParm).then(response => {
        if (response.data.list !== null) {
          for (let i = 0; i < response.data.list.length; i++) {
            if (response.data.list[i].cardAmount !== undefined) {
              this.$set(response.data.list[i], 'cardAmount', parseFloat(response.data.list[i].cardAmount))
            }
          }
          this.list = response.data.list
          this.pageNum = response.data.pageNum
          this.pageSize = response.data.pageSize
        } else {
          this.list = []
          this.pageNum = 0
          this.pageSize = 0
        }

        this.total = response.data.total
        this.getDeptList()
        setTimeout(() => {
          this.listLoading = false
        }, 100)
      })
    },

    getDownList() {
      this.requestParams[5].params[0] = this.$store.state.user.pastureid
      GetDataByNames(this.requestParams).then(response => {
        this.findAllProvider = response.data.findAllProvider.list
        this.findAllAssetType = response.data.findAllAssetType.list
        this.findAllPasture = response.data.findAllPasture.list
        // this.findAllDepart = response.data.findAllDepart.list
        this.findAllEmploye = response.data.findAllEmploye.list
        this.findAllAsset = response.data.findAllAsset.list
        this.getDictByName = response.data.getDictByName.list
      })
    },
    changePastureName(item) {
      this.getDepartParam.parammaps.pastureId = this.findAllPasture.find(obj => obj.name == item).id
      this.getdataListParm.parammaps.departmentId = ''
      this.getDepartDownList()
    },
    getDepartDownList() {
      GetDataByName(this.getDepartParam).then(response => {
        this.findAllDepart = response.data.list
      })
    },
    form_search() {
      this.listLoading = true
      this.getdataListParm.offset = 1
      this.getList()
    },

    handleModifyStatus(row, status) {
      this.$message({ message: '操作成功', type: 'success' })
      row.status = status
    },
    form_reset() {
      this.temp = { inputDatetime: parseTime(new Date(), '{y}-{m}-{d}'), dateFormat: parseTime(new Date(), '{y}-{m}-{d}'), assetName: '', assetId: '', deptName: '', pastureName: '', pastureId: Cookies.get('pastureid'), cardNumber: '', cardType: '', cardAmount: '', rechargeNum: '' }
    },
    form_add() {
      this.form_reset()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['temp'].clearValidate()
      })
    },
    add_dialog_save() {
      this.$refs['temp'].validate(valid => {
        if (valid) {
          // 卡余额
          this.temp.cardAmount = parseFloat(this.temp.cardAmount).toFixed(2)
          console.log(this.requestParam, '000')
          this.requestParam = {}
          this.requestParam.common = { 'returnmap': '0' }
          this.requestParam.data = []
          if (this.temp.departmentId == undefined || this.temp.departmentId == '') {
            this.temp.departmentId = ''
            this.temp.departmentName = ''
          }
          if (this.temp.assetId == undefined || this.temp.assetId == '') {
            this.temp.assetId = ''
            this.temp.assetSum = ''
          }
          if (this.temp.pastureName == undefined || this.temp.pastureName == '') {
            this.temp.pastureName = Cookies.get('pasturename')
          }
          this.requestParam.data[0] = { 'name': 'checkOilcard', 'type': 'v', 'parammaps': {
            cardCode: this.temp.cardNumber,
            eqId: this.temp.assetId
          }}
          this.requestParam.data[1] = { 'name': 'insertOilcard', 'type': 'e', 'parammaps': {
            assetId: this.temp.assetId,
            assetName: this.temp.assetSum,
            cardAmount: this.temp.cardAmount,
            cardNumber: this.temp.cardNumber,
            cardType: this.temp.cardType,
            dateFormat: this.temp.dateFormat,
            departmentId: this.temp.departmentId,
            deptName: this.temp.departmentName,
            inputDatetime: this.temp.inputDatetime,
            pastureId: this.temp.pastureId,
            pastureName: this.temp.pastureName,
            rechargeNum: this.temp.rechargeNum
          }}
          if (this.temp.assetSum !== null && this.temp.assetSum !== undefined && this.temp.assetSum !== '') {
            this.requestParam.data[2] = { 'name': 'insertSpotList', 'resultmaps': { 'list': [{ changeType: '新增', beforeMaintenance: 0, afterMaintenance: this.temp.assetSum, changePersonId: Cookies.get('employeid') }] }}
            this.requestParam.data[2].children = []
            this.requestParam.data[2].children[0] = { 'name': 'insertOilcardHistory', 'type': 'e', 'parammaps': {
              oildcardId: '@insertOilcard.LastInsertId',
              changeType: '@insertSpotList.changeType',
              beforeMaintenance: '@insertSpotList.beforeMaintenance',
              afterMaintenance: '@insertSpotList.afterMaintenance',
              changePersonId: '@insertSpotList.changePersonId'
            }}
          }
          ExecDataByConfig(this.requestParam).then(response => {
            if (response.msg === 'fail') {
              this.$notify({ title: '失败', message: '保存失败-' + response.data, type: 'danger', duration: 2000 })
            } else {
              this.getList()
              this.dialogFormVisible = false
              this.$notify({ title: '成功', message: '新增成功', type: 'success', duration: 2000 })
            }
          })
        }
      })
    },
    add_dialog_save_again() {
      this.$refs['temp'].validate(valid => {
        if (valid) {
          // 卡余额
          this.temp.cardAmount = parseFloat(this.temp.cardAmount).toFixed(2)
          console.log(this.requestParam, '000')
          this.requestParam = {}
          this.requestParam.common = { 'returnmap': '0' }
          this.requestParam.data = []
          if (this.temp.departmentId == undefined || this.temp.departmentId == '') {
            this.temp.departmentId = ''
            this.temp.departmentName = ''
          }
          if (this.temp.assetId == undefined || this.temp.assetId == '') {
            this.temp.assetId = ''
            this.temp.assetSum = ''
          }
          if (this.temp.pastureName == undefined || this.temp.pastureName == '') {
            this.temp.pastureName = Cookies.get('pasturename')
          }
          this.requestParam.data[0] = { 'name': 'checkOilcard', 'type': 'v', 'parammaps': {
            cardCode: this.temp.cardNumber,
            eqId: this.temp.assetId
          }}
          this.requestParam.data[1] = { 'name': 'insertOilcard', 'type': 'e', 'parammaps': {
            assetId: this.temp.assetId,
            assetName: this.temp.assetSum,
            cardAmount: this.temp.cardAmount,
            cardNumber: this.temp.cardNumber,
            cardType: this.temp.cardType,
            dateFormat: this.temp.dateFormat,
            departmentId: this.temp.departmentId,
            deptName: this.temp.departmentName,
            inputDatetime: this.temp.inputDatetime,
            pastureId: this.temp.pastureId,
            pastureName: this.temp.pastureName,
            rechargeNum: this.temp.rechargeNum
          }}
          if (this.temp.assetSum !== null && this.temp.assetSum !== undefined && this.temp.assetSum !== '') {
            this.requestParam.data[2] = { 'name': 'insertSpotList', 'resultmaps': { 'list': [{ changeType: '新增', beforeMaintenance: 0, afterMaintenance: this.temp.assetSum, changePersonId: Cookies.get('employeid') }] }}
            this.requestParam.data[2].children = []
            this.requestParam.data[2].children[0] = { 'name': 'insertOilcardHistory', 'type': 'e', 'parammaps': {
              oildcardId: '@insertOilcard.LastInsertId',
              changeType: '@insertSpotList.changeType',
              beforeMaintenance: '@insertSpotList.beforeMaintenance',
              afterMaintenance: '@insertSpotList.afterMaintenance',
              changePersonId: '@insertSpotList.changePersonId'
            }}
          }
          ExecDataByConfig(this.requestParam).then(response => {
            if (response.msg === 'fail') {
              this.$notify({ title: '失败', message: '保存失败-' + response.data, type: 'danger', duration: 2000 })
            } else {
              this.form_reset()
              this.$notify({ title: '成功', message: '新增成功', type: 'success', duration: 2000 })
            }
          })
        }
      })
    },

    createRechargeData() {
      this.$refs['temp'].validate(valid => {
        if (valid) {
          const rechargeNum = /^\d+(\.\d{1,2})?$/
          // 充值金额
          if (!rechargeNum.test(parseFloat(this.temp.rechargeNum))) {
            this.$message({ type: 'error', message: '充值金额请保留两位小数', duration: 2000 })
            return false
          }
          this.postDataPramas.common = { 'returnmap': '0' }
          this.postDataPramas.data = []
          this.postDataPramas.data[0] = { 'name': 'insertrechargerecord', 'type': 'e', 'parammaps': {
            'id': this.temp.id,
            'employeId': this.temp.employeId,
            'cardCode': this.temp.cardCode,
            'rechargeNum': this.temp.rechargeNum
          }}
          this.postDataPramas.data[1] = { 'name': 'updateCardbalanceExecData', 'type': 'e', 'parammaps': {
            'id': this.temp.id,
            'rechargeNum': this.temp.rechargeNum
          }}
          ExecDataByConfig(this.postDataPramas).then(response => {
            if (response.msg === 'fail') {
              this.$notify({ title: '保存失败', message: response.data, type: 'warning', duration: 2000 })
            } else {
              this.getList()
              this.getrechargedataListParmList()
              this.rechargeFFormVisible = false
              this.$notify({ title: '', message: '保存成功', type: 'success', duration: 2000 })
            }
          })
        }
      })
    },

    createRecharge() {
      this.dialogStatus = 'recharge'
      this.rechargeFFormVisible = true
      this.$set(this.temp, 'employeId', parseFloat(Cookies.get('employeid')))
      this.$set(this.temp, 'rechargeNum', '')
      this.temp.id = this.$store.id
      this.temp.dateFormat = parseTime(new Date(), '{y}-{m}-{d}')
      this.temp.cardCode = this.$store.cardCode
      // this.$nextTick(() => {
      //   this.$refs['temp'].clearValidate()
      // })
    },
    handleChange(row) {
      this.textMap.change = row.cardNumber + '-变更记录'
      this.cardNumber = row.cardNumber
      this.tabledialogStatus = 'change'
      this.changeFormVisible = true
      this.getchangedataListParm.parammaps['oildcardId'] = row.id
      this.temp.dateFormat = parseTime(new Date(), '{y}-{m}-{d}')
      // this.getchangedataListParmList()
      this.getchangedataListParmList2(row)
    },

    getchangedataListParmList2(row) {
      this.changelistLoading = true
      this.getchangedataListParm2 = {}
      this.getchangedataListParm2.common = { 'returnmap': '0' }
      this.getchangedataListParm2.data = []
      this.getchangedataListParm2.data[0] = { 'name': 'getOilcardstatuehistory', 'type': 'sm', 'parammaps': {
        id: row.id
      }}
      this.getchangedataListParm2.data[1] = { 'name': 'getOilcardHistory', 'type': 'sm', 'parammaps': {
        id: row.id
      }}
      ExecDataByConfig(this.getchangedataListParm2).then(response => {
        if (response.data[0].resultmaps !== null) {
          this.changelist2 = response.data[0].resultmaps
        } else {
          this.changelist2 = []
        }
        if (response.data[1].resultmaps !== null) {
          this.changelist = response.data[1].resultmaps
        } else {
          this.changelist = []
        }
        setTimeout(() => {
          this.changelistLoading = false
        }, 100)
      })
      // GetDataByName(this.getchangedataListParm2).then(response => {
      //   if (response.data.list !== null) {
      //     this.changelist2 = response.data.list
      //   } else {
      //     this.changelist2 = []
      //   }
      //   setTimeout(() => {
      //     this.changelistLoading2 = false
      //   }, 100)
      // })
    },

    handleRecharge(row) {
      this.rechargeTemp = Object.assign({}, row)
      this.tabledialogStatus = 'recharge'
      this.rechargeFormVisible = true
      this.rechargelistLoading = true
      this.getrechargedataListParm.parammaps['cardId'] = row.id
      this.$store.id = row.id
      this.$store.cardCode = row.cardNumber
      this.getrechargedataListParmList()
    },
    getrechargedataListParmList() {
      GetDataByName(this.getrechargedataListParm).then(response => {
        this.rechargelist = response.data.list
        setTimeout(() => {
          this.rechargelistLoading = false
        }, 100)
      })
    },
    form_edit(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      if (this.temp.assetId == '' || this.temp.assetId == undefined) {
        this.temp.pastureName = ''
      }
      this.$nextTick(() => {
        this.$refs['temp'].clearValidate()
      })
    },
    edit_dialog_save() {
      this.$refs['temp'].validate(valid => {
        if (valid) {
          // 卡余额
          this.temp.cardAmount = parseFloat(this.temp.cardAmount).toFixed(2)
          this.requestParam = {}
          this.requestParam.common = { 'returnmap': '0' }
          this.requestParam.data = []
          if (this.temp.pastureName == undefined || this.temp.pastureName == '') {
            this.temp.pastureName = Cookies.get('pasturename')
          }
          if (this.temp.assetSum == '' || this.temp.assetSum == null || this.temp.assetSum == undefined) {
            this.temp.pastureName = ''
            this.temp.deptName = ''
            this.temp.departmentId = ''
            this.temp.assetId = ''
            this.requestParam.data[0] = { 'name': 'insertOilcardHistory', 'type': 'e', 'parammaps': {
              changeType: '删除',
              beforeMaintenance: 1,
              afterMaintenance: this.temp.assetSum,
              changePersonId: Cookies.get('employeid'),
              oildcardId: this.temp.id,
              pastureId: this.temp.pastureId,
              pastureName: this.temp.pastureName
            }}
          } else {
            this.requestParam.data[0] = { 'name': 'insertOilcardHistory', 'type': 'e', 'parammaps': {
              changeType: '修改',
              beforeMaintenance: 1,
              afterMaintenance: this.temp.assetSum,
              changePersonId: Cookies.get('employeid'),
              oildcardId: this.temp.id,
              pastureId: this.temp.pastureId,
              pastureName: this.temp.pastureName
            }}
          }
          this.requestParam.data[1] = { 'name': 'updateOilcard', 'type': 'e', 'parammaps': {
            cardNumber: this.temp.cardNumber,
            cardType: this.temp.cardType,
            cardAmount: this.temp.cardAmount,
            assetId: this.temp.assetId,
            departmentId: this.temp.departmentId,
            id: this.temp.id,
            pastureId: this.temp.pastureId,
            pastureName: this.temp.pastureName
          }}

          ExecDataByConfig(this.requestParam).then(response => {
            if (response.msg === 'fail') {
              this.$notify({ title: '失败', message: '保存失败-' + response.data, type: 'danger', duration: 2000 })
            } else {
              this.getList()
              this.dialogFormVisible = false
              this.$notify({ title: '成功', message: '修改成功', type: 'success', duration: 2000 })
            }
          })
        }
      })
    },
    handleDisable(row) {
      var statue = ''
      if (row.enable == 0) {
        statue = '停用'
      } else {
        statue = '启用'
      }
      var enable = ''
      if (row.enable == 0) {
        enable = '1'
      } else {
        enable = '0'
      }
      var aa = '确认' + statue + '？'
      MessageBox.confirm('油卡编号' + row.cardNumber, aa, { confirmButtonText: '确认', cancelButtonText: '取消', type: 'warning' }).then(() => {
        this.requestParam = {}
        this.requestParam.common = { 'returnmap': '0' }
        this.requestParam.data = []
        this.requestParam.data[0] = { 'name': 'insertOilcardstatuehistory', 'type': 'e', 'parammaps': {
          oilCardId: row.id,
          statue: statue,
          personId: Cookies.get('employeid')
        }}
        this.requestParam.data[1] = { 'name': 'deleteOilcard', 'type': 'e', 'parammaps': {
          id: row.id,
          enable: enable
        }}
        console.log(this.requestParam)
        ExecDataByConfig(this.requestParam).then(response => {
          if (response.msg === 'fail') {
            this.$notify({ title: '失败', message: '失败' + response.data, type: 'danger', duration: 2000 })
          } else {
            this.getList()
            this.dialogFormVisible = false
            this.$notify({ title: '成功', message: '成功', type: 'success', duration: 2000 })
          }
        })
      }).catch(() => {
        this.$message({ type: 'info', message: '已取消停用' })
      })
    },
    form_delete(row) {
      MessageBox.confirm('油卡编号' + row.cardNumber, '确认删除？', { confirmButtonText: '确认', cancelButtonText: '取消', type: 'warning' }).then(() => {
        this.requestParam = {}
        this.requestParam.name = 'checkDeleteOilcard'
        this.requestParam.type = 'v'
        this.requestParam.parammaps = {}
        this.requestParam.parammaps.id = row.id
        ExecDataByConfig(this.requestParam).then((response) => {
          console.log(response)
          if (response.data == '成功执行！') {
            this.requestParam2.name = 'deleteOilcard2'
            this.requestParam2.parammaps = {}
            this.requestParam2.parammaps['id'] = row.id
            PostDataByName(this.requestParam2).then((response) => {
              if (response.msg == 'fail') {
                this.$notify({ title: '失败', message: '失败' + response.data, type: 'danger', duration: 2000 })
              } else {
                this.getList()
                this.$notify({ title: '成功', message: '删除成功', type: 'success', duration: 2000 })
              }
            })
          } else {
            this.$notify({ title: '失败', message: '失败' + response.data, type: 'danger', duration: 2000 })
          }
        })
      }).catch(() => {
        this.$message({ type: 'info', message: '已取消删除' })
      })
    },
    handleformNameSelect(item) {
      console.log(item)
      this.temp.assetSum = item.assetName
      this.temp.assetId = item.assetId
      this.temp.departmentName = item.deptName
      this.temp.departmentId = item.departmentId
      this.temp.pastureId = item.pastureId
      this.temp.pastureName = item.pastureName
    },
    blurformNameSelect(item) {
      this.temp.assetSum = ''
      this.temp.assetId = ''
      this.temp.deptName = ''
      this.temp.departmentId = ''
      this.temp.departmentName = ''
      this.temp.pastureName = ''
    },
    formNumberSearch(queryString, cb) {
      this.requestFilterParams.name = 'findAssetM'
      this.requestFilterParams.parammaps['pastureId'] = Cookies.get('pastureid')
      this.requestFilterParams.parammaps['assetName'] = queryString
      GetDataByName(this.requestFilterParams).then(response => {
        if (response.data.list === null) {
          this.formNumberSearchList = []
        } else {
          this.formNumberSearchList = response.data.list
        }
        console.log(this.formNumberSearchList)
        console.log(this.formNumberSearchList[0])
        console.log('queryString', queryString)
        var results = queryString ? this.formNumberSearchList.filter(this.createFilter(queryString)) : this.formNumberSearchList
        cb(results)
      })
    },
    beforeImportExcel(file) {
      const isLt2M = file.size / 1024 / 1024 < 10
      if (!isLt2M) {
        this.$message.error('上传文件大小不能超过 10MB!')
      }
      return isLt2M
    },

    handleImportExcelSuccess(res, file) {
      this.getList()
      if (res.msg === 'ok') {
        this.$message({ title: '成功', message: '导入成功:' + res.data.success + '条!', type: 'success', duration: 2000 })
        if (res.data.err_count > 0) {
          this.$notify({ title: '失败', message: '导入失败:' + res.data.err_count + '条!', type: 'danger', duration: 2000 })
            import('@/vendor/Export2Excel').then(excel => {
              const list1 = res.data.result
              const tHeader = ['牧场', '车自编号', '油卡', '类型', '上次用油量', '部门', '错误信息']
              const filterVal = ['牧场', '车自编号', '油卡', '类型', '上次用油量', '部门', 'error_msg']
              const data1 = this.formatJson(filterVal, list1)
              excel.export_json_to_excel({ header: tHeader, data: data1, filename: '油卡', autoWidth: true, bookType: 'xlsx' })
            })
        }
      } else {
        this.$notify({ title: '失败', message: '上传失败', type: 'danger', duration: 2000 })
      }
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v =>
        filterVal.map(j => {
          if (j === 'timestamp') { return parseTime(v[j]) } else { return v[j] }
        })
      )
    },
    handleDownloadTemp() {
      import('@/vendor/Export2Excel').then(excel => {
        const list1 = []
        const tHeader = [
          '牧场', '车自编号', '油卡', '类型', '余额', '部门'
        ]
        const filterVal = [
          '牧场', '车自编号', '油卡', '类型', '余额', '部门'
        ]
        const data1 = this.formatJson(filterVal, list1)
        excel.export_json_to_excel({ header: tHeader, data: data1, filename: '油卡模板', autoWidth: true, bookType: 'xlsx' })
      })
    },
    handlecardNumberSelect(item) {
      console.log(item)
      this.getdataListParm.parammaps.cardNumber = item.assetName
    },
    cardNumberSearch(queryString, cb) {
      this.requestFilterParams2.name = 'getOilcardList'
      this.requestFilterParams2.parammaps['cardNumber'] = queryString
      GetDataByName(this.requestFilterParams2).then(response => {
        if (response.data.list === null) {
          this.cardNumberSearchList = []
        } else {
          this.cardNumberSearchList = response.data.list
        }
        var results = queryString ? this.cardNumberSearchList.filter(this.createFilter(queryString)) : this.cardNumberSearchList
        cb(results)
      })
    },
    handleDownload() {
      this.$alert('油卡正在导出中，请勿刷新或离开本页面，若导出时间过长，建议缩小导出数据范围重新导出', {})
      this.isPercentage = true
      this.percentage = 1
      var timer = setInterval(() => {
        this.percentage += 5
        if (this.percentage > 95) {
          this.percentage = 99
          clearInterval(timer)
        }
        this.percentage = this.percentage
      }, 1000)
      this.downLoadParm.name = 'getOilcardList'
      this.downLoadParm.parammaps = this.getdataListParm.parammaps
      GetDataByName(this.downLoadParm).then(response => {
        if(response.data.list !== null && response.data.list !== ''){
          for(let i=0;i<response.data.list.length;i++){
            if(response.data.list[i].enable == 0){
              this.$set(response.data.list[i],'enable','启用')
            }else{
              this.$set(response.data.list[i],'enable','停用')
            }
          }
        }
        this.downLoadList = response.data.list
        if (response.data.list !== '') {
          this.percentage = 99
          setTimeout(() => {
            this.isPercentage = false
          }, 2000)
        }
        console.log(this.downLoadList)
        const elecExcelDatas = [
          {
            tHeader: ['部门', '油卡编号', '油卡类型', '剩余余额', '设备编号', '设备名称', '油卡状态'],
            filterVal: ['departmentName', 'cardNumber', 'cardType', 'cardAmount', 'assetNumber', 'assetName', 'enable'],
            tableDatas: this.downLoadList,
            sheetName: '油卡'
          }
        ]
        json2excel(elecExcelDatas, '油卡', true, 'xlsx')
      })
    },

  }
}
</script>
