<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select v-model="getdataListParm.parammaps.pastureName" placeholder="牧场" class="filter-item">
        <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-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-upload style="display: inline-block;" :headers="headers" :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="操作" align="center" width="250" class-name="small-padding fixed-width" fixed="right">
        <template slot-scope="{row}">
          <el-button type="success" size="mini" @click="handleChange(row)">换卡</el-button>
          <el-button type="success" size="mini" @click="handleRecharge(row)">充值</el-button>
          <el-button 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" />
    <!-- 弹出层新增or修改 -->
    <!-- 新增油卡 -->
    <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="assetName">
              <el-autocomplete ref="assetName" v-model="temp.assetName" style="width:300px" value-key="assetName" class="inline-input" clearable :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="deptName">
              <el-input ref="deptName" v-model="temp.deptName" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="卡号:" prop="cardNumber">
              <el-input ref="cardNumber" v-model="temp.cardNumber" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="卡类型:" prop="cardType">
              <el-input ref="cardType" v-model="temp.cardType" />
            </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>

    <!-- 换卡弹出层新增or修改 -->
    <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" 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.empName }}</span>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer" style="bottom:10px">
        <el-button
          ref="createb"
          type="success"
          @click="createChange()"
        >换卡</el-button>
        <el-button @click="changeFormVisible = false;getList()">取消并关闭</el-button>
      </div>
    </el-dialog>
    <!-- 弹出层新增or修改 -->
    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="changeFFormVisible"
      :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="cardCode">
              <el-input ref="cardNumber" v-model="temp.cardCode" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="更换卡类型" prop="cardType">
              <el-input ref="cardType" v-model="temp.cardType" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="负责人：" prop="employeId">
              <el-select v-model="temp.employeId" placeholder="负责人" class="filter-item">
                <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">
              <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-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :disabled="isokDisable" @click="createChangeData()">保存并关闭</el-button>
        <el-button @click="changeFFormVisible = false">取消并关闭</el-button>
      </div>
    </el-dialog>
    <!-- 弹出层新增or修改 -->
    <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"
      >
        <!-- table表格 -->
        <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
          ref="createb"
          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">
                <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">
              <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">
              <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 TreeSelect from '@/components/TreeSelect'   TreeSelect
import { GetDataByName, GetDataByNames, PostDataByName, getRecuData, ExecDataByConfig, failproccess } from '@/api/common'
import waves from '@/directive/waves' // waves directive
import { parseTime, sortChange } from '@/utils/index.js'
// eslint-disable-next-line no-unused-vars
import { validateEMail } from '@/utils/validate.js'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { MessageBox } from 'element-ui'
// eslint-disable-next-line no-unused-vars
import Cookies from 'js-cookie'
import { getToken } from '@/utils/auth'
export default {
  name: 'Otherinfo',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      isokDisable: false,
      tableKey: 0,
      list: null,
      changelist: null,
      rechargelist: null,
      total: 0,
      listLoading: true,
      changelistLoading: true,
      rechargelistLoading: true,
      formNumberSearchList: [],
      requestParam: {
        name: 'insertAsset',
        offset: 0,
        pagecount: 0,
        parammaps: {}
      },
      parentDept: [],
      getDeptParm: { name: 'getdeptrecu', idname: 'value', params: [-1] },
      postDataPramas: {

      },
      // 1-2:table&搜索传参
      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: {}
      },
      getchangedataListParm: {
        name: 'getcardrecordList',
        page: 1,
        offset: 1,
        pagecount: 10,
        returntype: 'Map',
        parammaps: {
        }
      },
      getrechargedataListParm: {
        name: 'getrechargerecordList',
        page: 1,
        offset: 1,
        pagecount: 10,
        returntype: 'Map',
        parammaps: {
        }
      },
      // 2-3：下拉框请求后数据加入[]
      findAllProvider: [],
      findAllAssetType: [],
      findAllPasture: [],
      findAllDepart: [],
      findAllEmploye: [],
      getDictByName: [],
      findAllAsset: [],
      // 2-1.请求下拉框接口
      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: ['资产状态'] }
      ],

      dataform: {
        deptId: '',
        parentId: ''
      },

      temp: {},
      dialogFormVisible: false,
      changeFormVisible: false,
      rechargeFormVisible: false,
      changeFFormVisible: false,
      rechargeFFormVisible: false,
      tabledialogStatus: '',
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新增',
        change: '换卡记录',
        recharge: '充值记录',
        changeF: '换卡',
        rechargeF: '充值'
      },
      dialogPvVisible: false,
      // 校验规则
      rules: {
        assetName: [
          { required: true, message: '必填', trigger: 'blur' }

          // 引入自定义校验并使用
          // { validator: validateEMail, trigger: 'blur' }
        ],
        pastureName: [{ required: true, message: '必填', trigger: 'blur' }],
        deptName: [{ required: true, message: '必填', trigger: 'blur' }],
        cardNumber: [{ required: true, message: '必填', trigger: 'blur' }],
        cardAmount: [{ required: true, message: '必填', trigger: 'blur' }]
      },
      rowStyle: { maxHeight: 50 + 'px', height: 45 + 'px' },
      cellStyle: { padding: 0 + 'px' },
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      nodeKey: 'value',
      defaultCheckedKeys: []
    }
  },
  computed: {
    // 设置请求头
    headers() {
      return {
        // 设置token
        // eslint-disable-next-line no-undef
        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() {
    this.get_select_list()
    this.getList()
  },

  methods: {
    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 => {
        this.list = response.data.list
        this.pageNum = response.data.pageNum
        this.pageSize = response.data.pageSize
        if (response.data.total) {
          this.total = response.data.total
        }
        this.getDeptList()
        setTimeout(() => {
          this.listLoading = false
        }, 100)
      })
    },

    get_select_list() {
      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
      })
    },
    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: '', 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.requestParam.name = 'insertOilcard'
          this.requestParam.parammaps = this.temp
          const cardAmount = /^\d+(\.\d{1,2})?$/
          // 卡余额
          if (!cardAmount.test(parseFloat(this.temp.cardAmount))) {
            this.$message({ type: 'error', message: '卡余额请保留两位小数', duration: 2000 })
            return false
          }
          PostDataByName(this.requestParam).then(response => {
            console.log(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.isokDisable = true
      setTimeout(() => {
        this.isokDisable = false
      }, 1000)
      this.$refs['temp'].validate((valid) => {
        if (valid) {
          this.requestParam.name = 'insertOilcard'
          this.requestParam.parammaps = this.temp
          const cardAmount = /^\d+(\.\d{1,2})?$/
          // 卡余额
          if (!cardAmount.test(parseFloat(this.temp.cardAmount))) {
            this.$message({ type: 'error', message: '卡余额请保留两位小数', duration: 2000 })
            return false
          }
          PostDataByName(this.requestParam).then(response => {
            console.log(response)
            if (response.msg !== 'fail') {
              this.form_reset()
              this.$nextTick(() => {
                this.$refs['temp'].clearValidate()
              })
              this.$notify({ title: '成功', message: '新增成功', type: 'success', duration: 2000 })
            } else {
              failproccess(response, this.$notify)
            }
          })
        }
      })
    },
    createChangeData() {
      this.$refs['temp'].validate(valid => {
        if (valid) {
          this.postDataPramas.common = { 'returnmap': '0' }
          this.postDataPramas.data = []
          this.postDataPramas.data[0] = { 'name': 'insertchangerecord', 'type': 'e', 'parammaps': {
            'id': this.temp.id,
            'employeId': this.temp.employeId,
            'cardCode': this.temp.cardCode,
            'cardType': this.temp.cardType
          }}
          this.postDataPramas.data[1] = { 'name': 'updateCardExecData', 'type': 'e', 'parammaps': {
            'id': this.temp.id,
            'employeId': this.temp.employeId,
            'cardCode': this.temp.cardCode,
            'cardType': this.temp.cardType
          }}
          ExecDataByConfig(this.postDataPramas).then(response => {
            if (response.msg === 'fail') {
              this.$notify({ title: '保存失败', message: response.data, type: 'warning', duration: 2000 })
            } else {
              this.getList()
              this.getchangedataListParmList()
              this.changeFFormVisible = false
              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 })
            }
          })
        }
      })
    },
    createChange() {
      this.dialogStatus = 'change'
      this.changeFFormVisible = true
      this.form_reset()
      this.$set(this.temp, 'employeId', parseFloat(Cookies.get('employeid')))
      this.$set(this.temp, 'cardNumber', '')
      this.$set(this.temp, 'cardType', '')
      this.temp.dateFormat = parseTime(new Date(), '{y}-{m}-{d}')
      this.temp.id = this.$store.id
      this.temp.departmentId = this.$store.state.user.departmentid
      this.temp.pastureId = this.$store.state.user.pastureid
      this.$nextTick(() => {
        this.$refs['temp'].clearValidate()
      })
    },
    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.tabledialogStatus = 'change'
      this.changeFormVisible = true
      this.changelistLoading = true
      this.getchangedataListParm.parammaps['cardId'] = row.id
      this.$store.id = row.id
      this.temp.dateFormat = parseTime(new Date(), '{y}-{m}-{d}')
      this.getchangedataListParmList()
    },
    getchangedataListParmList() {
      GetDataByName(this.getchangedataListParm).then(response => {
        this.changelist = response.data.list
        setTimeout(() => {
          this.changelistLoading = false
        }, 100)
      })
    },
    edit_dialog_save() {
      this.$refs['temp'].validate(valid => {
        if (valid) {
          this.requestParam.name = 'updateOilcard'
          this.requestParam.parammaps = this.temp
          PostDataByName(this.requestParam).then(response => {
            console.log(response)
            if (response.msg === 'fail') {
              this.$notify({ title: '失败', message: '保存失败-' + response.data, type: 'warning', duration: 2000 })
            } else {
              this.getList()
              this.dialogFormVisible = false
              this.$notify({ title: '成功', message: '修改成功', type: 'success', duration: 2000 })
            }
          })
        }
      })
    },
    handleRecharge(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
      this.$nextTick(() => {
        this.$refs['temp'].clearValidate()
      })
    },
    form_delete(row) {
      MessageBox.confirm('油卡编号' + row.cardNumber, '确认删除？', { confirmButtonText: '确认', cancelButtonText: '取消', type: 'warning' }).then(() => {
        this.requestParam.name = 'deleteOilcard'
        this.requestParam.parammaps = {}
        this.requestParam.parammaps['id'] = row.id
        PostDataByName(this.requestParam).then(() => {
          this.getList()
          this.dialogFormVisible = false
          this.$notify({ title: '成功', message: '删除成功', type: 'success', duration: 2000 })
        })
      }).catch(() => {
        this.$message({ type: 'info', message: '已取消删除' })
      })
    },
    handleformNameSelect(item) {
      console.log(item)
      this.temp.assetName = item.assetName
      this.temp.assetId = item.assetId
      this.temp.deptName = item.deptName
      this.temp.departmentId = item.departmentId
      this.temp.pastureId = item.pastureId
      this.temp.pastureName = item.pastureName
    },
    blurformNameSelect(item) {
      this.temp.assetName = ''
      this.temp.assetId = ''
      this.temp.deptName = ''
      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] }
        })
      )
    }

  }
}
</script>
