<template>
  <div class="app-container">
    <div v-if="isPercentage" class="percentage" style="width: 210px;height: 90px;background: #fff;position: fixed;bottom: 0;left: 0;z-index: 9999999999999;">
      <h4 style="padding-left: 10px;line-height: 0;">导出进度：</h4>
      <el-progress style="padding-left: 10px;" :text-inside="true" :stroke-width="26" :percentage="percentage" />
    </div>
    <div class="filter-container">
      <el-select v-model="getdataListParm.parammaps.pastureName" placeholder="牧场" style="width: 120px;" 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.deptName" placeholder="部门" style="width: 120px;" class="filter-item" clearable>
        <el-option v-for="item in findAllDepart" :key="item.id" :label="item.name" :value="item.name" />
      </el-select>
      <el-input v-model="getdataListParm.parammaps.cardNumber" placeholder="卡号" clearable class="filter-item" style="width: 120px" />
      <!-- <el-date-picker v-model="getdataListParm.parammaps.selTime" type="date" placeholder="交易时间" style="width:170px;top:-3px;" format="yyyy-MM-dd" value-format="yyyy-MM-dd" /> -->

      <el-date-picker ref="inputDatetime" v-model="getdataListParm.parammaps.inputDatetime" class="inputDatetime" type="datetimerange" style="width: 250px;top:-5px;" format="yyyy-MM-dd" value-format="yyyy-MM-dd" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" />
      <el-input v-model="getdataListParm.parammaps.equipmentNumber" placeholder="设备编号" clearable class="filter-item" style="width: 120px" />
      <el-input v-model="getdataListParm.parammaps.assetName" placeholder="设备名称" clearable class="filter-item" style="width: 120px" />
      <el-input v-model="getdataListParm.parammaps.employName" placeholder="加油工" clearable class="filter-item" style="width: 120px" />
      <el-input v-model="getdataListParm.parammaps.oilClass" placeholder="加油工班" clearable class="filter-item" style="width: 120px" />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="form_search">搜索</el-button>
      <div>
        <el-button v-if="isDieselAdd" class="filter-item" type="primary" icon="el-icon-edit" @click="form_add">新增</el-button>
        <el-button v-if="isDieselExport" v-waves class="filter-item" type="success" icon="el-icon-download" @click="handleDownloadTemp">导出</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-if="isRetreatImport" v-waves class="filter-item" type="warning" icon="el-icon-upload2" @click="form_search">导入</el-button>
        </el-upload>
        <el-button v-if="isDieselExport" v-waves class="filter-item" type="success" icon="el-icon-download" @click="handleDownload">数据导出</el-button>
        <el-button class="filter-item" type="danger" icon="el-icon-download" @click="form_delete">删除</el-button>
      </div>
    </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="tableSort1"
    >
      <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="牧场" width="90px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.pastureName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="部门" width="80px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.departName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="交易时间" sortable prop="selTime" width="90px" align="center" />
      <el-table-column label="车号" min-width="110px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.assetNumber }}</span>
        </template>
      </el-table-column>
      <el-table-column label="加油工班" width="80px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.oilClass }}</span>
        </template>
      </el-table-column>
      <el-table-column label="加油工" width="80px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.empId }}</span>
        </template>
      </el-table-column>
      <el-table-column label="卡号" width="90px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.cardNumber }}</span>
        </template>
      </el-table-column>
      <el-table-column label="卡类型" width="80px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.cardType }}</span>
        </template>
      </el-table-column>
      <el-table-column label="本次加油量(升)" sortable prop="oilAmount" width="80px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.oilAmount }}</span>
        </template>
      </el-table-column>
      <el-table-column label="本次消费金额(元)" sortable prop="nowPrice" width="80px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.nowPrice }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" min-width="110px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.note }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="200px" class-name="small-padding fixed-width" fixed="right">
        <template slot-scope="{row}">
          <el-button v-if="isDieselModify" type="success" size="mini" @click="handleDieselUpdate(row)">编辑</el-button>
          <!-- <el-button type="primary" size="mini" style="width:70px" @click="handleDosageRecord(row)">用量记录</el-button> -->
          <!-- <el-button v-if="isDieselUpdate" type="success" size="mini" @click="handleDieselUpdate(row)">修改</el-button> -->
          <!-- <el-button v-if="isDieselDel" type="danger" size="mini" @click="handleDieselDel(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">
      <el-form ref="temp" :rules="rules" :model="temp" label-position="right" label-width="150px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="油卡编号" prop="cardNumber">
              <el-autocomplete
                ref="cardNumber"
                v-model="temp.cardNumber"
                value-key="cardNumber"
                class="inline-input"
                :fetch-suggestions="formCardSearch"
                placeholder="请输入内容"
                :disabled="dialogStatus==='update'"
                @select="handleformNameSelect"
                @blur="blurformNameSelect"
              >
                <template slot-scope="{ item }">
                  <div class="name" style="display: inline;">{{ item.cardCode }}</div>
                </template>
              </el-autocomplete>

            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单价：" prop="price">
              <el-input ref="price" v-model="temp.price" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="油量(L)：" prop="oilAmount">
              <el-input ref="oilAmount" v-model="temp.oilAmount" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="设备名称：" prop="assetName">
              <el-autocomplete ref="assetName" v-model="temp.assetName" value-key="assetName" class="inline-input" :fetch-suggestions="formNameSearch" placeholder="" disabled @select="handleformNameSelect" />
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="牧场设备编号：" prop="eqCode">
              <el-autocomplete ref="eqCode" v-model="temp.eqCode" value-key="eqCode" class="inline-input" :fetch-suggestions="formNumberSearch" placeholder="" disabled @select="handleformNameSelect">
                <template slot-scope="{ item }">
                  <div class="name" style="display: inline;">{{ item.assetNumber }}</div>
                </template>
              </el-autocomplete>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="牧场" prop="pastureName">
              <el-input ref="pastureName" v-model="temp.pastureName" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <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="8">
            <el-form-item label="加油人：" prop="employeId">
              <el-input ref="employeId" v-model="temp.empId" :disabled="dialogStatus==='update'" />
              <!-- <el-select v-model="temp.employeId" placeholder="负责人" :disabled="dialogStatus==='update'" 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-col :span="8">
            <el-form-item label="录入人：" prop="inputId">
              <el-select v-model="temp.inputId" placeholder="负责人" :disabled="dialogStatus==='update'" 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-col :span="8">
            <el-form-item label="加油工班次：" prop="oilClass">
              <el-input ref="oilClass" v-model="temp.oilClass" :disabled="dialogStatus==='update'" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="交易时间：" prop="selTime">
              <el-date-picker v-model="temp.selTime" type="date" placeholder="交易时间" format="yyyy-MM-dd" value-format="yyyy-MM-dd" style="width:100%;" :disabled="dialogStatus==='update'" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="备注：" prop="note">
              <el-input v-model="temp.note" type="textarea" :rows="2" placeholder="请输入内容" />
            </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[dialogStatus]" :visible.sync="dialogFormDosageRecord" :close-on-click-modal="false">
      <div class="dosageRecord">
        <div style="position: absolute;top:20px;left:100px;font:18px/24px '' ;color:#303133;">
          <span style="margin:0 10px;">表名称：{{ dosageRecordTemp.formName }}</span>
          <span>表编号:{{ dosageRecordTemp.formNumber }}</span>
        </div>
        <el-table
          :key="tableKey"
          v-loading="listLoadingDosageRecord"
          element-loading-text="给我一点时间"
          :data="listDosageRecord"
          border
          fit
          highlight-current-row
          style="width: 100%;"
          :row-style="rowStyle"
          :cell-style="cellStyle"
          class="elTable"
          @sort-change="tableSort2"
        >
          <el-table-column label="序号" align="center" type="index" width="50px">
            <template slot-scope="scope">
              <span>{{ scope.$index + (pageNumDosageRecord-1) * pageSizeDosageRecord + 1 }}</span>
            </template>
          </el-table-column>
          <el-table-column label="上次值" sortable prop="lastAmount" min-width="110px" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.lastAmount }}</span>
            </template>
          </el-table-column>
          <el-table-column label="本次值" sortable prop="endAmount" min-width="110px" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.endAmount }}</span>
            </template>
          </el-table-column>
          <el-table-column label="用量" sortable prop="waterConsumption" min-width="110px" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.waterConsumption }}</span>
            </template>
          </el-table-column>
          <el-table-column label="单价" sortable prop="price" align="center" width="150">
            <template slot-scope="scope">
              <span>{{ scope.row.price }}</span>
            </template>
          </el-table-column>
          <el-table-column label="总价" sortable prop="sumPrice" align="center" width="150">
            <template slot-scope="scope">
              <span>{{ scope.row.sumPrice }}</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-column label="记录日期" min-width="110px" align="center" sortable prop="date" />
        </el-table>
        <pagination v-show="totalDosageRecord>=0" :total="totalDosageRecord" :page.sync="getDosageRecordListParm.offset" :limit.sync="getDosageRecordListParm.pagecount" @pagination="getDosageRecordList" />
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormDosageRecord = false">关闭</el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 删除 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormDelete" :close-on-click-modal="false" width="40%">
      <el-form ref="deleteTemp" :rules="rules" :model="deleteTemp" label-position="right" label-width="190px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="请选择要删除数据的日期:" prop="startTime">
              <el-date-picker ref="startTime" v-model="deleteTemp.startTime" :clearable="false" type="date" placeholder="日期" style="width:100%px;" format="yyyy-MM-dd" value-format="yyyy-MM-dd" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :disabled="isokDisable" @click="deleteData()">确认</el-button>
        <el-button @click="dialogFormDelete = false;getList()">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 引入
require('script-loader!file-saver')
import { GetDataByName, GetDataByNames, PostDataByName, checkButtons, ExecDataByConfig, failproccess, GetAccount } from '@/api/common'
// import {  DownloadExcel, GetDataByNameXlsx } from '@/api/common'
import waves from '@/directive/waves'
import { parseTime, sortChange } from '@/utils/index.js'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { MessageBox } from 'element-ui'
import { getToken } from '@/utils/auth'
import Cookies from 'js-cookie'
export default {
  name: 'Diesel',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      isokDisable: false,
      isDieselUpdate: [],
      isDieselDel: [],
      isDieselAdd: [],
      isDieselExport: [],
      isDieselModify: [],
      isRetreatImport: [],
      isRetreatMuban: [],
      formNumberSearchList: [],
      formNameSearchList: [],
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      requestParam: {
        name: 'insertDiesel',
        offset: 0,
        pagecount: 0,
        parammaps: {}
      },
      postDataPramas: {

      },
      // 1-2:table&搜索传参
      getdataListParm: {
        name: 'getDieselList',
        page: 1,
        offset: 1,
        pagecount: 10,
        returntype: 'Map',
        parammaps: {
          selTime: '',
          pastureName: Cookies.get('pasturename'),
          departName: ''
        }
      },
      // 2-3：下拉框请求后数据加入[]
      getDictByName: [],
      findAllAssetType: [],
      findAllPasture: [],
      findAllDepart: [],
      findAllEmploye: [],
      // 2-1.请求下拉框接口
      requestParams: [
        { name: 'getDictByName', 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') }}
      ],
      getDepartParam: {
        name: 'findAllDepart', offset: 0, pagecount: 0, parammaps: { 'pastureId': Cookies.get('pastureid') }
      },
      requestFilterParams: {
        name: 'getWaterList',
        page: 1,
        offset: 1,
        pagecount: 10,
        returntype: 'Map',
        parammaps: {}
      },
      temp: {
        selTime: parseTime(new Date(), '{y}-{m}-{d}'),
        oilClass: '', // 加油工班
        cardNumber: '',
        price: '',
        empId: '',
        inputId: this.$store.state.user.employeid,
        departmentId: this.$store.state.user.departmentid,
        pastureId: this.$store.state.user.pastureid,
        oilAmount: '',
        nowPrice: '',
        note: '',
        eqId: '',
        eqCode: '',
        oilcardId: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新增',
        DosageRecord: '用量记录',
        delete: '删除'
      },
      dialogFormDosageRecord: false,
      totalDosageRecord: 0,
      listDosageRecord: [],
      listLoadingDosageRecord: false,
      getDosageRecordListParm: {
        name: 'getDieselHistory',
        page: 1,
        offset: 1,
        pagecount: 10,
        returntype: 'Map',
        parammaps: {}
      },
      dosageRecordTemp: {},
      // 校验规则
      rules: {
        cardNumber: [{ required: true, message: '必填', trigger: 'blur' }],
        price: [{ required: true, message: '必填', trigger: 'blur' }],
        oilAmount: [{ required: true, message: '必填', trigger: 'blur' }],
        endAmount: [{ type: 'number', required: true, validator: (rule, value, callback) => {
          console.log(rule, value, callback)
          if (!value) {
            callback(new Error('不能为空'))
          }
          if (value < 0) {
            callback(new Error('必须大于0'))
          } else if (value < this.temp.aAmount) {
            callback(new Error('必须大于上次值'))
          }
          setTimeout(() => {
            const re = /^\d+$/ // /^[0-9]*[1-9][0-9]*$/
            const rsCheck = re.test(value)
            if (!rsCheck) {
              callback(new Error('请输入整数'))
            } else {
              callback()
            }
          }, 0)
        }, trigger: 'blur' }],
        equipmentName: [{ required: true, message: '必填', trigger: 'blur' }],
        startTime: [{ required: true, message: '必填', trigger: 'blur' }]
      },
      MeasureListbyfilter: [],
      rowStyle: { maxHeight: 50 + 'px', height: 45 + 'px' },
      cellStyle: { padding: 0 + 'px' },
      buttons: [],
      isPercentage: false,
      percentage: 1,
      dialogFormDelete: false,
      deleteTemp: {}
    }
  },

  computed: {
    // 设置请求头
    headers() {
      return {
        // 设置token
        token: getToken()
      }
    },
    uploadData() {
      return {
        name: 'importDiesel',
        importParams: '牧场,油卡编号,设备名称,设备编号,加油日期,加油量(L),单价,录入人,加油人,加油工班,备注',
        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.get_auto_buttons()
    })
    this.get_select_list()
    this.getList()
  },

  methods: {
    tableSort1(column) {
      sortChange(column, this.list)
    },
    tableSort2(column) {
      sortChange(column, this.listDosageRecord)
    },
    get_auto_buttons() {
      // 新增
      const DieselAdd = 'cost:diesel:add'
      const isDieselAdd = checkButtons(this.$store.state.user.buttons, DieselAdd)
      this.isDieselAdd = isDieselAdd
      // 模板
      const RetreatMuban = 'cost:diesel:muban'
      const isRetreatMuban = checkButtons(this.$store.state.user.buttons, RetreatMuban)
      this.isRetreatMuban = isRetreatMuban
      // 导出
      const DieselExport = 'cost:diesel:export'
      const isDieselExport = checkButtons(this.$store.state.user.buttons, DieselExport)
      this.isDieselExport = isDieselExport
      // 导入
      const RetreatImport = 'cost:diesel:import'
      const isRetreatImport = checkButtons(this.$store.state.user.buttons, RetreatImport)
      this.isRetreatImport = isRetreatImport
      // 编辑
      const DieselModify = 'cost:diesel:modify'
      const isDieselModify = checkButtons(this.$store.state.user.buttons, DieselModify)
      this.isDieselModify = isDieselModify
      // 修改
      const DieselUpdate = 'cost:diesel:update'
      const isDieselUpdate = checkButtons(this.$store.state.user.buttons, DieselUpdate)
      this.isDieselUpdate = isDieselUpdate
      // 删除
      const DieselDel = 'cost:diesel:del'
      const isDieselDel = checkButtons(this.$store.state.user.buttons, DieselDel)
      this.isDieselDel = isDieselDel
    },
    isIntegerZero_(rule, value, callback) {
      if (value === '' || value === undefined || value === null) {
        return callback(new Error('输入不可以为空'))
      }
      if (value.length === 0) {
        return callback(new Error('输入不可以为空'))
      }
      setTimeout(() => {
        const re = /^\d+$/ // /^[0-9]*[1-9][0-9]*$/
        const rsCheck = re.test(value)
        if (!rsCheck) {
          callback(new Error('请输入整数'))
        } else {
          callback()
        }
      }, 0)
    },

    // 模糊查询-报修名称
    formNumberSearch(queryString, cb) {
      this.requestFilterParams.name = 'findAssetMainOil'
      this.requestFilterParams.parammaps['assetNumber'] = queryString
      this.requestFilterParams.parammaps['pastureId'] = Cookies.get('pastureid')
      this.requestFilterParams.parammaps['assetName'] = ''
      this.requestFilterParams.parammaps['cardCode'] = ''
      GetDataByName(this.requestFilterParams).then(response => {
        this.formNumberSearchList = response.data.list
        var results = queryString ? this.formNumberSearchList.filter(this.createFilter(queryString)) : this.formNumberSearchList
        cb(results)
      })
    },
    createFilter(queryString) {
      return returnValue => {
        return (
          returnValue.assetNumber.toLowerCase().indexOf(queryString.toLowerCase()) >= 0
        )
      }
    },
    formNameSearch(queryString, cb) {
      this.requestFilterParams.name = 'findAssetMainOil'
      this.requestFilterParams.parammaps['assetNumber'] = ''
      this.requestFilterParams.parammaps['pastureId'] = Cookies.get('pastureid')
      this.requestFilterParams.parammaps['assetName'] = queryString
      this.requestFilterParams.parammaps['cardCode'] = ''
      GetDataByName(this.requestFilterParams).then(response => {
        this.formNameSearchList = response.data.list
        var results = queryString ? this.formNameSearchList.filter(this.createFilterName(queryString)) : this.formNameSearchList
        cb(results)
      })
    },
    formCardSearch(queryString, cb) {
      this.requestFilterParams.name = 'findAssetMainOil'
      this.requestFilterParams.parammaps['assetNumber'] = ''
      this.requestFilterParams.parammaps['assetName'] = ''
      this.requestFilterParams.parammaps['cardCode'] = queryString
      this.requestFilterParams.parammaps['pastureId'] = Cookies.get('pastureid')
      GetDataByName(this.requestFilterParams).then(response => {
        if (response.data.list === null) {
          this.formNameSearchList = []
        } else {
          this.formNameSearchList = response.data.list
        }
        var results = queryString ? this.formNameSearchList.filter(this.createFilterName(queryString)) : this.formNameSearchList
        cb(results)
      })
    },
    createFilterName(queryString) {
      return returnValue => {
        return (
          returnValue.cardCode.toLowerCase().indexOf(queryString.toLowerCase()) >= 0
        )
      }
    },
    handleformNameSelect(item) {
      this.temp.assetName = item.assetName
      this.temp.cardNumber = item.cardCode
      this.temp.eqId = item.eqId
      this.temp.eqCode = item.eqCode
      this.temp.oilcardId = item.oilcardId
      this.temp.deptName = item.deptName
      this.temp.departmentId = item.deptId
      this.temp.pastureName = item.pastureName
      this.temp.price = item.price
    },
    blurformNameSelect(item) {
      this.temp.assetName = ''
      this.temp.cardNumber = ''
      this.temp.eqId = ''
      this.temp.eqCode = ''
      this.temp.oilcardId = ''
      this.temp.deptName = ''
      this.temp.pastureName = ''
      this.temp.price = ''
    }, // 导出
    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.requestParam.name = 'getDieselList'
      this.requestParam.parammaps.pastureName = this.getdataListParm.parammaps.pastureName
      this.requestParam.parammaps.departName = this.getdataListParm.parammaps.departName
      this.requestParam.parammaps.startTime = this.getdataListParm.parammaps.startTime
      this.requestParam.parammaps.stopTime = this.getdataListParm.parammaps.stopTime
      GetAccount(this.requestParam).then(response => {
        if (response.data.list !== '') {
          this.percentage = 99
          setTimeout(() => {
            this.isPercentage = false
          }, 2000)
        }
        this.$nextTick(() => {
          import('@/vendor/Export2Excel').then(excel => {
            const list1 = response.data.list
            const tHeader = [
              '牧场', '部门', '交易时间', '车号', '加油工班', '加油工', '卡号', '卡类型', '本次加油量(升)', '本次消费金额(元)', '备注'
            ]
            const filterVal = [
              'pastureName', 'departName', 'selTime', 'assetNumber', 'oilClass', 'empId', 'cardNumber', 'cardType', 'oilAmount', 'nowPrice', 'note'
            ]
            const data1 = this.formatJson(filterVal, list1)
            excel.export_json_to_excel({ header: tHeader, data: data1, filename: '柴油用量', autoWidth: true, bookType: 'xlsx' })
          })
        })
      })
    },
    handleDownloadTemp() {
      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.requestParam.name = 'meteringOutfitDiesel'
      this.requestParam.parammaps.pastureName = this.getdataListParm.parammaps.pastureName
      this.requestParam.parammaps.departName = this.getdataListParm.parammaps.departName
      this.requestParam.parammaps.selTime = this.getdataListParm.parammaps.selTime
      GetAccount(this.requestParam).then(response => {
        if (response.data.list !== '') {
          this.percentage = 99
          setTimeout(() => {
            this.isPercentage = false
          }, 2000)
        }
        this.$nextTick(() => {
              import('@/vendor/Export2Excel').then(excel => {
                const list1 = response.data.list
                const tHeader = [
                  '编号', '牧场', '油卡编号', '设备名称', '设备编号', '加油日期', '加油量(L)', '单价', '录入人', '加油人', '加油工班', '备注'
                ]
                const filterVal = [
                  '编号', '牧场', '油卡编号', '设备名称', '设备编号', '加油日期', '加油量(L)', '单价', '录入人', '加油人', '加油工班', '备注'
                ]
                const data1 = this.formatJson(filterVal, list1)
                excel.export_json_to_excel({
                  header: tHeader,
                  data: data1,
                  filename: '柴油',
                  autoWidth: true,
                  bookType: 'xlsx'
                })
              })
        })
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v =>
        filterVal.map(j => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        })
      )
    },
    // 导入
    beforeImportExcel(file) {
      /*   const isExcel =
        file.type ===
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' */
      const isLt2M = file.size / 1024 / 1024 < 2
      /*  if (!isExcel) {
        this.$message.error(
          '上传文件必须是Xlsx格式!建议先导出，再修改导出文件再导入！'
        )
      }*/
      if (!isLt2M) {
        this.$message.error('上传文件大小不能超过 2MB!')
      }
      return isLt2M
    },
    handleImportExcelSuccess(res, file) {
    //  if (res.msg === 'ok') {
      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 = [
               '编号', '牧场', '油卡编号', '设备名称', '设备编号', '加油日期', '加油量(L)', '单价', '录入人', '加油人', '加油工班', '备注', '错误信息'
             ]
             const filterVal = [
               '编号', '牧场', '油卡编号', '设备名称', '设备编号', '加油日期', '加油量(L)', '单价', '录入人', '加油人', '加油工班', '备注', 'error_msg'
             ]
             const data1 = this.formatJson(filterVal, list1)
             excel.export_json_to_excel({
               header: tHeader,
               data: data1,
               filename: this.requestParam.parammaps.formType,
               autoWidth: true,
               bookType: 'xlsx'
             })
           })
        }
      } else {
        this.$notify({
          title: '失败',
          message: '上传失败',
          type: 'danger',
          duration: 2000
        })
      }
    },

    // 1-1: table&搜索
    getList() {
      this.listLoading = true
      GetDataByName(this.getdataListParm).then(response => {
        if (response.data.list == null) {
          this.list = []
        } else {
          this.list = response.data.list
          this.pageNum = response.data.pageNum
          this.pageSize = response.data.pageSize
          if (response.data.total) {
            this.total = response.data.total
          }
        }
        setTimeout(() => {
          this.listLoading = false
        }, 100)
      })
    },
    // 2-2：下拉框
    get_select_list() {
      GetDataByNames(this.requestParams).then(response => {
        this.getDictByName = response.data.getDictByName.list
        this.findAllAssetType = response.data.findAllAssetType.list
        this.findAllPasture = response.data.findAllPasture.list
        this.findAllEmploye = response.data.findAllEmploye.list
        this.getDepartDownList()
      })
    },
    getDepartDownList() {
      GetDataByName(this.getDepartParam).then(response => {
        this.findAllDepart = response.data.list
      })
    },
    changePastureName(item) {
      this.getDepartParam.parammaps.pastureId = this.findAllPasture.find(obj => obj.name == item).id
      this.getdataListParm.parammaps.deptName = ''
      this.getDepartDownList()
    },
    form_search() {
      this.listLoading = true
      this.getdataListParm.offset = 1
      if (this.getdataListParm.parammaps.inputDatetime == null) {
        this.getdataListParm.parammaps.inputDatetime = ''
      }
      if (this.getdataListParm.parammaps.inputDatetime !== '' && this.getdataListParm.parammaps.inputDatetime !== null) {
        this.getdataListParm.parammaps.startTime = parseTime(this.getdataListParm.parammaps.inputDatetime[0], '{y}-{m}-{d}')
        this.getdataListParm.parammaps.stopTime = parseTime(this.getdataListParm.parammaps.inputDatetime[1], '{y}-{m}-{d}')
      } else {
        this.getdataListParm.parammaps.inputDatetime = ''
        this.getdataListParm.parammaps.startTime = ''
        this.getdataListParm.parammaps.stopTime = ''
      }
      // if (this.getdataListParm.parammaps.selTime == null) {
      //   this.getdataListParm.parammaps.selTime = ''
      // }

      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作成功',
        type: 'success'
      })
      row.status = status
    },
    form_reset() {
      this.temp.cardNumber = ''
      this.temp.price = ''
      this.temp.oilAmount = ''
      this.temp.assetName = ''
      this.temp.eqCode = ''
      this.temp.pastureName = ''
      this.temp.deptName = ''
      this.temp.oilClass = ''
      this.temp.selTime = parseTime(new Date(), '{y}-{m}-{d}')
      this.temp.note = ''
    },
    form_add() {
      console.log(this.temp.DATE)
      this.form_reset()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.temp.empId = ''
      this.temp.departmentId = ''
      this.temp.pastureId = this.$store.state.user.pastureid
      this.$nextTick(() => {
        this.$refs['temp'].clearValidate()
      })
    },
    add_dialog_save() {
      this.isokDisable = true
      setTimeout(() => {
        this.isokDisable = false
      }, 1000)
      this.$refs['temp'].validate(valid => {
        if (valid) {
          this.postDataPramas.common = { 'returnmap': '0' }
          this.postDataPramas.data = []
          this.postDataPramas.data[0] = { 'name': 'insertDiesel', 'type': 'e', 'parammaps': {

            'pastureId': this.temp.pastureId,
            'selTime': this.temp.selTime,
            'oilClass': this.temp.oilClass,
            'oilAmount': this.temp.oilAmount,
            'eqId': this.temp.eqId,
            'eqCode': this.temp.eqCode,
            'departmentId': this.temp.departmentId,
            'note': this.temp.note,
            'nowPrice': this.temp.price * this.temp.oilAmount,
            'oilcardId': this.temp.oilcardId,
            'cardNumber': this.temp.cardNumber,
            'price': this.temp.price,
            'empId': this.temp.empId,
            'inputId': this.temp.inputId
          }}

          this.postDataPramas.data[1] = { 'name': 'updateOilCardExecData', 'type': 'e',
            'parammaps': {
              'id': this.temp.oilcardId,
              'nowPrice': this.temp.price * this.temp.oilAmount

            }}

          ExecDataByConfig(this.postDataPramas).then(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
              })
            }
          })
        }
      })
    },
    // 继续新增
    add_dialog_save_again() {
      this.isokDisable = true
      setTimeout(() => {
        this.isokDisable = false
      }, 1000)
      this.$refs['temp'].validate(valid => {
        if (valid) {
          this.postDataPramas.common = { 'returnmap': '0' }
          this.postDataPramas.data = []
          this.postDataPramas.data[0] = { 'name': 'insertDiesel', 'type': 'e', 'parammaps': {

            'pastureId': this.temp.pastureId,
            'selTime': this.temp.selTime,
            'oilClass': this.temp.oilClass,
            'oilAmount': this.temp.oilAmount,
            'eqId': this.temp.eqId,
            'eqCode': this.temp.eqCode,
            'departmentId': this.temp.departmentId,
            'note': this.temp.note,
            'nowPrice': this.temp.price * this.temp.oilAmount,
            'oilcardId': this.temp.oilcardId,
            'cardNumber': this.temp.cardNumber,
            'price': this.temp.price,
            'empId': this.temp.empId,
            'inputId': this.temp.inputId
          }}

          this.postDataPramas.data[1] = { 'name': 'updateOilCardExecData', 'type': 'e',
            'parammaps': {
              'id': this.temp.oilcardId,
              'nowPrice': this.temp.price * this.temp.oilAmount
            }}

          ExecDataByConfig(this.postDataPramas).then(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)
            }
          })
        }
      })
    },

    form_edit(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['temp'].clearValidate()
      })
    },

    // 修改加油信息
    edit_dialog_save() {
      this.$refs['temp'].validate(valid => {
        if (valid) {
          this.postDataPramas.common = { 'returnmap': '0' }
          this.postDataPramas.data = []
          this.postDataPramas.data[0] = { 'name': 'updateDieselExecData', 'type': 'e', 'parammaps': {
            'id': this.temp.id,
            'oilAmount': this.temp.oilAmount,
            'note': this.temp.note,
            'nowPrice': this.temp.price * this.temp.oilAmount,
            'price': this.temp.price
          }}

          this.postDataPramas.data[1] = { 'name': 'updateOilCardLAExecData', 'type': 'e',
            'parammaps': {
              'id': this.temp.oilcardId,
              'nowPrice': this.temp.price * this.temp.oilAmount
            }}

          ExecDataByConfig(this.postDataPramas).then(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
              })
            }
          })
        }
      })
    },
    handleDieselUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.eqCode = this.temp.assetNumber
      this.temp.deptName = this.temp.departName
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['temp'].clearValidate()
      })
    },
    // 删除加油信息
    handleDieselDel(row) {
      MessageBox.confirm('是否确认删除此条加油信息？', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.requestParam.name = 'deleteDiesel'
          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: '已取消删除'
          })
        })
    },
    handleDosageRecord(row) {
      this.dialogStatus = 'DosageRecord'
      this.dialogFormDosageRecord = true
      this.dosageRecordTemp = Object(row, {})
      this.getDosageRecordList()
    },
    form_delete() {
      this.deleteTemp = {}
      this.dialogStatus = 'delete'
      this.dialogFormDelete = true
    },
    deleteData() {
      this.$refs['deleteTemp'].validate(valid => {
        if (valid) {
          this.requestParam.name = 'deletedatastem'
          this.requestParam.parammaps = {}
          this.requestParam.parammaps.pastureName = this.getdataListParm.parammaps.pastureName
          this.requestParam.parammaps.codeType = 3
          this.requestParam.parammaps.startTime = this.deleteTemp.startTime
          this.requestParam.parammaps.stopTime = this.deleteTemp.startTime
          PostDataByName(this.requestParam).then(response => {
            if (response.msg == 'fail') {
              this.$notify({ title: '保存失败', message: response.data, type: 'warning', duration: 2000 })
            } else {
              this.$notify({ title: '成功', message: '删除成功', type: 'success', duration: 2000 })
              this.dialogFormDelete = false
              this.getList()
            }
          })
        }
      })
    },
    getDosageRecordList() {
      this.listLoadingDosageRecord = true
      this.getDosageRecordListParm.parammaps.id = this.dosageRecordTemp.oilcardId
      GetDataByName(this.getDosageRecordListParm).then(response => {
        this.listDosageRecord = response.data.list
        this.pageNumDosageRecord = response.data.pageNum
        this.pageSizeDosageRecord = response.data.pageSize
        if (response.data.total) {
          this.totalDosageRecord = response.data.total
        }
        setTimeout(() => {
          this.listLoadingDosageRecord = false
        }, 100)
      })
    }

  }
}
</script>
