<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: 140px;" 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.departName" placeholder="部门" style="width: 140px;" 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.formNumber" placeholder="编号" clearable class="filter-item" style="width: 130px" />
      <el-input v-model="getdataListParm.parammaps.formName" placeholder="表名称" style="width: 140px;" class="filter-item" />
      <el-select v-model="getdataListParm.parammaps.formType" clearable placeholder="表结构" class="filter-item">
        <el-option v-for="item in useTypes" :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>
      <div>
        <el-button v-if="isSteamAdd" class="filter-item" type="primary" icon="el-icon-edit" @click="form_add">新增</el-button>
        <el-button v-if="isSteamExport" v-waves class="filter-item" type="success" icon="el-icon-download" @click="handleDownload">导出</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="isSteamImport" v-waves class="filter-item" type="warning" icon="el-icon-upload2" @click="form_search">导入</el-button>
        </el-upload>
        <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"
      :max-height="myHeight"
    >
      <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="编号" width="90px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.steamNumber }}</span>
        </template>
      </el-table-column>
      <el-table-column label="名称" width="80px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.steamName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="表结构" width="80px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.useType }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="上次值" width="90px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.lastAmount }}</span>
        </template>
      </el-table-column>
      <el-table-column label="本次值" width="80px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.endAmount }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="当天用气量" sortable prop="steamConsumption" width="80px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.steamConsumption }}</span>
        </template>
      </el-table-column>
      <el-table-column label="单价" sortable prop="price" width="80px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.price }}</span>
        </template>
      </el-table-column>
      <el-table-column label="倍率" sortable prop="rate" width="80px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.rate }}</span>
        </template>
      </el-table-column>
      <el-table-column label="当天费用" sortable prop="sumPrice" width="80px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.sumPrice }}</span>
        </template>
      </el-table-column>
      <el-table-column label="记录人" min-width="110px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.putName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="日期" min-width="110px" align="center" sortable prop="dateFormat" />
      <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="200" class-name="small-padding fixed-width" fixed="right">
        <template slot-scope="{row}">
          <el-button v-if="isSteamModify" type="success" size="mini" @click="form_edit(row)">编辑</el-button>
          <el-button type="primary" size="mini" style="width:70px" @click="handleDosageRecord(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="get_table_data" />
    <!-- 弹出层新增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="105px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="蒸汽表编号：" prop="formNumber">
              <el-autocomplete ref="formNumber" v-model="temp.formNumber" value-key="formNumber" class="inline-input" :fetch-suggestions="formNumberSearch" placeholder="请输入内容" :disabled="dialogStatus==='update'" style="width:100%;" @select="handleformNumberSelect" @blur="blurSelect" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="蒸汽表名称：" prop="formName">
              <el-autocomplete ref="formName" v-model="temp.formName" value-key="formName" class="inline-input" :fetch-suggestions="formNameSearch" placeholder="请输入内容" :disabled="dialogStatus==='update'" style="width:100%;" @select="handleformNameSelect" @blur="blurSelect" />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="6">
            <el-form-item label="上次值(m³)：" prop="aAmount">
              <el-input ref="aAmount" v-model="temp.aAmount" disabled />
            </el-form-item>
          </el-col> -->
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="蒸汽类型：">
              <span>{{ temp.useType }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="牧场：">
              <span>{{ temp.pastureName }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="部门：">
              <span>{{ temp.departName }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="责任人：">
              <span>{{ temp.employeName1 }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="用量：" prop="consumption">
              <el-input ref="consumption" v-model="temp.consumption" @blur="handleBlurConsumption" />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="8">
              <el-form-item label="当前值(m³)：" prop="endAmount">
                <el-input ref="endAmount" v-model="temp.endAmount" @blur="handleBlurEndAmount" />
              </el-form-item>
            </el-col> -->
          <el-col :span="8">
            <el-form-item label="单价(元)：" prop="price1">
              <el-input ref="price" v-model="temp.price1" :disabled="dialogStatus==='update'" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="倍率：" prop="rate">
              <el-input ref="rate" v-model="temp.rate" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="备注：" prop="note">
              <el-input ref="note" v-model="temp.note" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="当前时间：" prop="DATE">
              <el-date-picker v-model="temp.DATE" type="date" placeholder="当前时间" format="yyyy-MM-dd" value-format="yyyy-MM-dd" disabled style="width:100%;" />
            </el-form-item>
          </el-col>
          <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-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="dialogStatus==='create'" ref="createb" type="success" :disabled="isokDisable" @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;get_table_data()">取消并关闭</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"
        >
          <!-- table表格 -->
          <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="上次值" min-width="110px" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.lastAmount }}</span>
            </template>
          </el-table-column>
          <el-table-column label="本次值" 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;get_table_data()">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 引入
require('script-loader!file-saver')
import { GetDataByName, GetDataByNames, PostDataByName, checkButtons, ExecDataByConfig, GetAccount } from '@/api/common'
// import {  DownloadExcel, GetDataByNameXlsx } from '@/api/common'
import waves from '@/directive/waves' // waves directive
// eslint-disable-next-line no-unused-vars
// import { isIntegerZero } from '@/utils/validate.js'
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: 'Steam',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      myHeight:document.documentElement.clientHeight - 85- 200,
      isokDisable: false,
      isSteamAdd: [],
      isSteamExport: [],
      isSteamImport: [],
      isSteamModify: [],
      formNumberSearchList: [],
      formNameSearchList: [],
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      requestParam: {
        name: 'insertSteam',
        offset: 0,
        pagecount: 0,
        parammaps: {}
      },
      postDataPramas: {

      },
      // 1-2:table&搜索传参
      getdataListParm: {
        name: 'getSteamList',
        page: 1,
        offset: 1,
        pagecount: 10,
        returntype: 'Map',
        parammaps: {
          formName: '',
          formNumber: '',
          formType: '',
          pastureName: Cookies.get('pasturename'),
          departName: ''
        }
      },
      // 2-3：下拉框请求后数据加入[]
      useTypes: [{ id: 0, name: '1级表' }, { id: 1, name: '2级表' }, { id: 2, name: '3级表' }],
      getDictByName: [],
      findAllAssetType: [],
      findAllPasture: [],
      findAllDepart: [],
      findAllEmploye: [],
      // 2-1.请求下拉框接口
      requestParams: [
        { name: 'getDictByName', offset: 0, pagecount: 0, params: ['ZQ流量计类型'] },
        { 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: 'getSteamList',
        page: 1,
        offset: 1,
        pagecount: 10,
        returntype: 'Map',
        parammaps: {}
      },

      temp: {
        consumption: '',
        pastureName: '',
        useType: '',
        departName: '',
        aAmount: '',
        employeName1: '',
        formName: '',
        formNumber: '',
        measureId: '',
        endAmount: '',
        employeName: '',
        price1: '',
        note: '',
        inputDatetime: parseTime(new Date(), '{y}-{m}-{d}'),
        typeName: '',
        assTypeId: '',
        employeId: this.$store.state.user.employeid,
        departmentId: this.$store.state.user.departmentid,
        pastureId: this.$store.state.user.pastureid
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新增',
        DosageRecord: '用量记录',
        delete: '删除'
      },
      dialogFormDosageRecord: false,
      totalDosageRecord: 0,
      listDosageRecord: [],
      listLoadingDosageRecord: false,
      getDosageRecordListParm: {
        name: 'getAllMeasureTypeList',
        page: 1,
        offset: 1,
        pagecount: 10,
        returntype: 'Map',
        parammaps: {}
      },
      dosageRecordTemp: {},
      // 校验规则
      rules: {
        endAmount: [{ type: 'number', required: true, validator: (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' }],
        price1: [{ required: true, message: '必填', trigger: 'blur' }],
        consumption: [{ 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: 'insertSteamsMeasure',
        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.get_auto_buttons()
    })
    this.get_select_list()
    this.get_table_data()
  },

  methods: {
    tableSort1(column) {
      sortChange(column, this.list)
    },
    tableSort2(column) {
      sortChange(column, this.listDosageRecord)
    },
    get_auto_buttons() {
      // 新增
      const SteamAdd = 'cost:steam:add'
      const isSteamAdd = checkButtons(this.$store.state.user.buttons, SteamAdd)
      this.isSteamAdd = isSteamAdd
      // 导出
      // eslint-disable-next-line no-redeclare
      const SteamExport = 'cost:steam:export'
      const isSteamExport = checkButtons(this.$store.state.user.buttons, SteamExport)
      this.isSteamcExport = isSteamExport
      // 导入
      // eslint-disable-next-line no-redeclare
      const SteamImport = 'cost:steam:import'
      const isSteamImport = checkButtons(this.$store.state.user.buttons, SteamImport)
      this.isSteamImport = isSteamImport
      // 编辑
      // eslint-disable-next-line no-redeclare
      const SteamModify = 'cost:steam:modify'
      const isSteamModify = checkButtons(this.$store.state.user.buttons, SteamModify)
      this.isSteamModify = isSteamModify
    },

    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)
    },
    handleDownload() {
      /*       this.requestParam.name = 'meteringOutfit'
      this.requestParam.returntype = 'xlsx'
      this.requestParam.parammaps.formType = 'ZQ流量计'
      GetDataByNameXlsx(this.requestParam).then(response => {
        this.$nextTick(() => {
          DownloadExcel(response, this.requestParam.parammaps.formType)
        }) */
      this.$alert('ZQ流量计正在导出中，请勿刷新或离开本页面，若导出时间过长，建议缩小导出数据范围重新导出', {})
      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 = 'meteringOutfit'
      this.requestParam.parammaps.formType = 'ZQ流量计'
      this.requestParam.parammaps.pastureName = this.getdataListParm.parammaps.pastureName
      this.requestParam.parammaps.departName = this.getdataListParm.parammaps.departName
      this.requestParam.parammaps.formName = this.getdataListParm.parammaps.formName
      this.requestParam.parammaps.formNumber = this.getdataListParm.parammaps.formNumber
      this.requestParam.parammaps.useType = this.getdataListParm.parammaps.formType
      GetAccount(this.requestParam).then(response => {
        this.$nextTick(() => {
          import('@/vendor/Export2Excel').then(excel => {
            const list1 = response.data.list
            if (response.data.list !== '') {
              this.percentage = 99
              setTimeout(() => {
                this.isPercentage = false
              }, 2000)
            }
            const tHeader = [
              '编号', '牧场', '表名称', '表编号', '抄表日期', '用量', '单价', '录入人', '备注'
            ]
            const filterVal = [
              '编号', '牧场', '表名称', '表编号', '抄表日期2', '用量', '单价2', '录入人', '备注2'
            ]
            const data1 = this.formatJson(filterVal, list1)
            excel.export_json_to_excel({
              header: tHeader,
              data: data1,
              filename: this.requestParam.parammaps.formType,
              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) {
      this.get_table_data()
      //  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 = [
               '编号', '牧场', '表名称', '表编号', '抄表日期', '用量', '单价', '录入人', '备注', '错误信息'
             ]
             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
        })
      }
    },
    formNumberSearch(queryString, cb) {
      this.requestFilterParams.name = 'getMeasureListbyfilter'
      this.requestFilterParams.parammaps['formType'] = 'ZQ流量计'
      this.requestFilterParams.parammaps['pastureId'] = Cookies.get('pastureid')
      this.requestFilterParams.parammaps['formNumber'] = queryString
      this.requestFilterParams.parammaps['formName'] = ''
      GetDataByName(this.requestFilterParams).then(response => {
        if (response.data.list === null) {
          this.formNumberSearchList = []
        } else {
          this.formNumberSearchList = response.data.list
        }
        var results = queryString ? this.formNumberSearchList.filter(this.createFilter(queryString)) : this.formNumberSearchList
        cb(results)
      })
    },
    createFilter(queryString) {
      return returnValue => {
        return (
          returnValue.formNumber.toLowerCase().indexOf(queryString.toLowerCase()) >= 0
        )
      }
    },
    formNameSearch(queryString, cb) {
      this.requestFilterParams.name = 'getMeasureListbyfilter'
      this.requestFilterParams.parammaps['formType'] = 'ZQ流量计'
      this.requestFilterParams.parammaps['pastureId'] = Cookies.get('pastureid')
      this.requestFilterParams.parammaps['formNumber'] = ''
      this.requestFilterParams.parammaps['formName'] = queryString
      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.formName.toLowerCase().indexOf(queryString.toLowerCase()) >= 0
        )
      }
    },
    handleformNumberSelect() {
      this.requestFilterParams.name = 'findByNMeasureSteam'
      this.requestFilterParams.parammaps['formNumber'] = this.temp.formNumber
      this.requestFilterParams.parammaps['formName'] = ''
      GetDataByName(this.requestFilterParams).then(response => {
        this.$nextTick(() => {
          if (response.data.list.length > 0) {
            this.temp.pastureName = response.data.list[0].pastureName
            this.temp.useType = response.data.list[0].useType
            this.temp.departName = response.data.list[0].departName
            this.temp.aAmount = response.data.list[0].aAmount
            this.temp.employeName1 = response.data.list[0].employeName
            this.temp.formName = response.data.list[0].formName
            this.temp.measureId = response.data.list[0].measureId
            this.temp.pastureId = response.data.list[0].pastureId
            this.temp.price1 = response.data.list[0].price
            this.temp.rate = response.data.list[0].rate
            this.$forceUpdate()
          }
        })
      })
    },
    handleformNameSelect() {
      this.requestFilterParams.name = 'findByNMeasureSteam'
      this.requestFilterParams.parammaps['formNumber'] = ''
      this.requestFilterParams.parammaps['formName'] = this.temp.formName
      GetDataByName(this.requestFilterParams).then(response => {
        this.$nextTick(() => {
          if (response.data.list.length > 0) {
            this.temp.pastureName = response.data.list[0].pastureName
            this.temp.useType = response.data.list[0].useType
            this.temp.departName = response.data.list[0].departName
            this.temp.aAmount = response.data.list[0].aAmount
            this.temp.employeName1 = response.data.list[0].employeName
            this.temp.formNumber = response.data.list[0].formNumber
            this.temp.measureId = response.data.list[0].measureId
            this.temp.pastureId = response.data.list[0].pastureId
            this.temp.price1 = response.data.list[0].price
            this.temp.rate = response.data.list[0].rate
            this.$forceUpdate()
          }
        })
      })
    },
    blurSelect(item) {
      this.temp.pastureName = ''
      this.temp.useType = ''
      this.temp.departName = ''
      this.temp.aAmount = ''
      this.temp.employeName1 = ''
      this.temp.formName = ''
      this.temp.formNumber = ''
      this.temp.measureId = ''
      this.temp.pastureId = ''
    },
    // 1-1: table&搜索
    get_table_data() {
      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.departName = ''
      this.getDepartDownList()
    },
    form_search() {
      this.listLoading = true
      this.getdataListParm.offset = 1
      this.get_table_data()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作成功',
        type: 'success'
      })
      row.status = status
    },
    form_reset() {
      this.temp.consumption = ''
      this.temp.pastureName = ''
      this.temp.useType = ''
      this.temp.departName = ''
      this.temp.aAmount = ''
      this.temp.employeName1 = ''
      this.temp.formName = ''
      this.temp.formNumber = ''
      this.temp.measureId = ''
      this.temp.pastureId = ''
      this.temp.endAmount = ''
      this.temp.price1 = ''
      this.temp.note = ''
      this.temp.employeId = ''
      this.temp.employeName = ''
      this.temp.DATE = parseTime(new Date(), '{y}-{m}-{d}')
      this.temp.typeName = ''
      this.temp.assTypeId = ''
      this.temp.employeId = this.$store.state.user.employeid
      this.temp.departmentId = this.$store.state.user.departmentid
      this.temp.pastureId = this.$store.state.user.pastureid
    },
    form_add() {
      this.form_reset()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['temp'].clearValidate()
      })
    },
    // 用量
    handleBlurConsumption() {
      if (this.dialogStatus == 'create') {
        if (this.temp.aAmount !== '' && this.temp.consumption !== undefined && this.temp.consumption !== '' && this.temp.consumption !== null) {
          this.temp.endAmount = parseFloat(this.temp.aAmount) + parseFloat(this.temp.consumption)
        }
      } else {
        this.$set(this.temp, 'endAmount', parseFloat(this.temp.aAmount) + parseFloat(this.temp.consumption))
        this.$forceUpdate()
      }
    },
    // 当前值
    handleBlurEndAmount() {
      if (this.dialogStatus == 'create') {
        if (this.temp.endAmount !== 'undefined' && this.temp.endAmount !== '' && this.temp.endAmount !== null && this.temp.aAmount !== '') {
          this.temp.consumption = parseFloat(this.temp.endAmount) - parseFloat(this.temp.aAmount)
        }
      } else {
        this.$set(this.temp, 'consumption', parseFloat(this.temp.endAmount) - parseFloat(this.temp.aAmount))
        this.$forceUpdate()
      }
    },
    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': 'checkMeasure', 'type': 'v', 'parammaps': { 'endAmount': this.temp.endAmount,
            'checkdate': this.temp.inputDatetime, 'measureId': this.temp.measureId }}

          this.postDataPramas.data[1] = { 'name': 'insertSteamExecData', 'type': 'e', 'parammaps': {

            'endAmount': this.temp.endAmount,
            'measureId': this.temp.measureId,
            // 'data': this.temp.inputDatetime,
            'id': this.temp.id,
            'employeId': this.temp.employeId,
            'formNumber': this.temp.formNumber,
            'formName': this.temp.formName,
            'price': this.temp.price1,
            'rate': this.temp.rate,
            'pastureId': this.temp.pastureId,
            'note': this.temp.note,
            'consumption': this.temp.consumption
          }}

          this.postDataPramas.data[2] = { 'name': 'updateMeasureExecData', 'type': 'e',
            'parammaps': {
              'endAmount': this.temp.endAmount,
              'measureId': this.temp.measureId,
              'endDate': this.temp.inputDatetime,
              'lastRecodeId': '@insertSteamExecData.LastInsertId'
            }}

          ExecDataByConfig(this.postDataPramas).then(response => {
            console.log('保存发送参数', this.postDataPramas)
            if (response.msg === 'fail') {
              this.$notify({
                title: '保存失败',
                message: response.data,
                type: 'warning',
                duration: 2000
              })
            } else {
              this.get_table_data()
              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': 'checkMeasure', 'type': 'v', 'parammaps': { 'endAmount': this.temp.endAmount,
            'checkdate': this.temp.inputDatetime, 'measureId': this.temp.measureId }}

          this.postDataPramas.data[1] = { 'name': 'insertSteamExecData', 'type': 'e', 'parammaps': {

            'endAmount': this.temp.endAmount,
            'measureId': this.temp.measureId,
            // 'data': this.temp.inputDatetime,
            'id': this.temp.id,
            'employeId': this.temp.employeId,
            'formNumber': this.temp.formNumber,
            'formName': this.temp.formName,
            'price': this.temp.price1,
            'rate': this.temp.rate,
            'pastureId': this.temp.pastureId,
            'note': this.temp.note,
            'consumption': this.temp.consumption
          }}

          this.postDataPramas.data[2] = { 'name': 'updateMeasureExecData', 'type': 'e',
            'parammaps': {
              'endAmount': this.temp.endAmount,
              'measureId': this.temp.measureId,
              'endDate': this.temp.inputDatetime,
              'lastRecodeId': '@insertSteamExecData.LastInsertId'
            }}

          ExecDataByConfig(this.postDataPramas).then(response => {
            console.log('保存发送参数', this.postDataPramas)
            if (response.msg === 'fail') {
              this.$notify({
                title: '保存失败',
                message: response.data,
                type: 'warning',
                duration: 2000
              })
            } else {
              this.form_reset()
              this.$notify({
                title: '',
                message: '保存成功',
                type: 'success',
                duration: 2000
              })
            }
          })
        }
      })
    },
    form_edit(row) {
      this.temp = Object.assign({}, row) // copy obj
      // if (this.temp.endAmount !== '' && this.temp.endAmount !== undefined && this.temp.endAmount !== null && this.temp.aAmount !== '' && this.temp.aAmount !== undefined && this.temp.aAmount !== null) {
      //   this.$set(this.temp, 'consumption', parseFloat(this.temp.endAmount) - parseFloat(this.temp.aAmount))
      // }
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['temp'].clearValidate()
      })
    },
    edit_dialog_save() {
      this.$refs['temp'].validate(valid => {
        if (valid) {
          // this.requestParam.name = 'updatSteam'
          // 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.get_table_data()
          //     this.dialogFormVisible = false
          //     this.$notify({
          //       title: '成功',
          //       message: '修改成功',
          //       type: 'success',
          //       duration: 2000
          //     })
          //   }
          // })

          this.temp.date = parseTime(new Date(), '{y}-{m}-{d}')
          this.postDataPramas.common = { 'returnmap': '0' }
          this.postDataPramas.data = []
          this.postDataPramas.data[0] = { 'name': 'checkMeasureUpdate', 'type': 'v', 'parammaps': { 'endAmount': this.temp.endAmount,
            'checkdate': this.temp.date, 'measureId': this.temp.measureId }}

          this.postDataPramas.data[1] = { 'name': 'updateSteam', 'type': 'e', 'parammaps': {
            'endAmount': this.temp.endAmount,
            'measureId': this.temp.measureId,
            // 'data': this.temp.inputDatetime,
            'rate': this.temp.rate,
            'id': this.temp.id,
            'note': this.temp.note,
            'employeId': this.temp.employeId,
            'consumption': this.temp.consumption
          }}

          this.postDataPramas.data[2] = { 'name': 'updateMeasureSteam', 'type': 'e',
            'parammaps': {
              'endAmount': this.temp.endAmount,
              'measureId': this.temp.measureId,
              'endDate': this.temp.date,
              'lastRecodeId': this.temp.id
            }}

          ExecDataByConfig(this.postDataPramas).then(response => {
            if (response.msg === 'fail') {
              this.$notify({
                title: '保存失败',
                message: response.data,
                type: 'warning',
                duration: 2000
              })
            } else {
              this.get_table_data()
              this.dialogFormVisible = false
              this.$notify({
                title: '',
                message: '保存成功',
                type: 'success',
                duration: 2000
              })
            }
          })
        }
      })
    },
    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 = 4
          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.get_table_data()
            }
          })
        }
      })
    },
    handleDosageRecord(row) {
      this.dialogStatus = 'DosageRecord'
      this.dialogFormDosageRecord = true
      this.dosageRecordTemp = Object(row, {})
      this.getDosageRecordList()
    },
    getDosageRecordList() {
      this.listLoadingDosageRecord = true
      this.getDosageRecordListParm.parammaps.id = this.dosageRecordTemp.measureId
      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>
