<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="tableObj.parammaps.pastureName" placeholder="牧场" style="width: 140px;" class="filter-item" @change="change_pasture1">
        <el-option v-for="item in pastureList" :key="item.id" :label="item.name" :value="item.name" />
      </el-select>
     
    
      <el-date-picker v-model="tableObj.parammaps.date" type="monthrange" range-separator="至"
      start-placeholder="开始月份"
      end-placeholder="结束月份" style="width:240px;top:-3px;"  />

      

      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="form_search">搜索</el-button>
      <div>
        <el-button v-if="isElecAdd" class="filter-item" type="primary" icon="el-icon-edit" @click="form_add">新增</el-button>
        <el-button v-if="isElecAdd2" v-waves class="filter-item" type="info" icon="el-icon-tickets"  @click="handleDownloadTemp">模板</el-button>
        <el-button v-if="isElecExport" v-waves class="filter-item" type="success" icon="el-icon-download" @click="form_export">导出</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="isElecImport" v-waves class="filter-item" type="warning" icon="el-icon-upload2" @click="form_search">导入</el-button>
        </el-upload>
         
      </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"
      :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="中心"  min-width="110px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.center   }}</span>
        </template>
      </el-table-column>
      <el-table-column label="能源消耗统计（牧场）"  min-width="110px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.pastureName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="月份" min-width="140px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.date }}</span>
        </template>
      </el-table-column>
 
      <el-table-column label="全群饲养头日"  min-width="110px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.firstday }}</span>
        </template>
      </el-table-column>
      <el-table-column label="牧场外购电量（度）"  min-width="110px"align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.mcwgdl   }}</span>
        </template>
      </el-table-column>
      <el-table-column label="沼气发电量（度）" min-width="110px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.zqfdl   }}</span>
        </template>
      </el-table-column>
      <el-table-column label="牧场外购水量（吨）" min-width="110px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.mcwgsl  }}</span>
        </template>
      </el-table-column>
      <el-table-column label="牧场自备井取水量（吨）" min-width="110px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.mczbjqsl   }}</span>
        </template>
      </el-table-column>
      <el-table-column label="牧场柴油用量（升）" min-width="110px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.mccyyl  }}</span>
        </template>
      </el-table-column>
      <el-table-column label="牧场煤炭用量（吨）" min-width="110px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.mcmtyl  }}</span>
        </template>
      </el-table-column>
      <el-table-column label="生物质颗粒用量（吨）" min-width="110px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.swzklyl   }}</span>
        </template>
      </el-table-column>

      <el-table-column label="牧场天然气用量（方）" min-width="110px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.mctrqyl   }}</span>
        </template>
      </el-table-column>
      <el-table-column label="牧场总用电量（度）" min-width="110px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.mczydl    }}</span>
        </template>
      </el-table-column>
      <el-table-column label="牧场总用水量（吨）" min-width="110px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.mczysl     }}</span>
        </template>
      </el-table-column>
      <el-table-column label="牧场电费单价（元/度）" min-width="110px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.mcdfdj  }}</span>
        </template>
      </el-table-column>
      <el-table-column label="牧场水费单价（元/吨）" min-width="110px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.mcsfdj     }}</span>
        </template>
      </el-table-column>

      <el-table-column label="牧场柴油单价（元/升）" min-width="110px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.mccydj  }}</span>
        </template>
      </el-table-column>
   
      <el-table-column label="牧场煤炭单价（元/吨）" min-width="110px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.mcmtdj     }}</span>
        </template>
      </el-table-column>
      <el-table-column label="牧场天然气单价（元/吨）" min-width="110px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.mctrqdj      }}</span>
        </template>
      </el-table-column>
      <el-table-column label="生物质颗粒单价（元/吨）" min-width="110px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.swzkldj       }}</span>
        </template>
      </el-table-column>
      <el-table-column label="单头牛用电量(度/头日)" min-width="110px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.dtnydl        }}</span>
        </template>
      </el-table-column>
      <el-table-column label="单头牛用水量(吨/头日)" min-width="110px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.dtnysl       }}</span>
        </template>
      </el-table-column>
      <el-table-column label="单头牛用油量(升/头日)" min-width="110px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.dtnyyl      }}</span>
        </template>
      </el-table-column>
 
    
      </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="isElecModify" type="success" size="mini" @click="form_edit(row)">编辑</el-button>
   
          <el-button v-if="isElecModify" size="mini" type="danger" @click="form_delete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <pagination v-show="total>0" :total="total" :page.sync="tableObj.offset" :limit.sync="tableObj.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="110px">
        
        <el-row>
           
          <el-col :span="8">

            <el-form-item label="能源消耗统计（牧场）：" prop="pastureId" v-show="dialogStatus==='create'">
                <el-select v-model="temp.pastureId" placeholder="牧场"   class="filter-item" @change="change_pasture2" style="width:100%">
                  <el-option v-for="item in pastureList" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
            </el-form-item>

            <el-form-item label="能源消耗统计（牧场）：" prop="pastureId" v-show="dialogStatus==='update'">
                <el-input ref="pastureName" v-model="temp.pastureName"  disabled />
            </el-form-item>


          </el-col>
          

          <el-col :span="8">
            <el-form-item label="录入时间：" prop="date">
              <el-date-picker v-model="temp.date" type="month" placeholder="录入时间"  style="width:100%;" />
            </el-form-item>
          </el-col>

  

          <el-col :span="8">
            <el-form-item label="全群饲养头日：" prop="firstday">
              <el-input ref="firstday" v-model="temp.firstday" :disabled="dialogStatus==='see'"  />
            </el-form-item>
          </el-col>
 

           
        </el-row>
        <el-row>
          
          
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="牧场外购电量（度）：" prop="mcwgdl">
              <el-input ref="mcwgdl" v-model="temp.mcwgdl"  :disabled="dialogStatus==='see'" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="沼气发电量（度）：" prop="zqfdl">
              <el-input ref="zqfdl" v-model="temp.zqfdl"  :disabled="dialogStatus==='see'" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="牧场外购水量（吨）：" prop="mcwgsl">
              <el-input ref="mcwgsl" v-model="temp.mcwgsl" :disabled="dialogStatus==='see'"  />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="牧场自备井取水量（度）：" prop="mczbjqsl">
              <el-input ref="mczbjqsl" v-model="temp.mczbjqsl"  :disabled="dialogStatus==='see'" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="牧场柴油用量（升）：" prop="mccyyl">
              <el-input ref="mccyyl" v-model="temp.mccyyl"  :disabled="dialogStatus==='see'" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="牧场煤炭用量（吨）：" prop="mcmtyl">
              <el-input ref="mcmtyl" v-model="temp.mcmtyl" :disabled="dialogStatus==='see'"  />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="生物质颗粒用量（吨）：" prop="swzklyl">
              <el-input ref="swzklyl" v-model="temp.swzklyl"  :disabled="dialogStatus==='see'" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="牧场天然气用量（方）：" prop="mctrqyl">
              <el-input ref="mctrqyl" v-model="temp.mctrqyl"  :disabled="dialogStatus==='see'" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="牧场总电量（吨）：" prop="mczydl">
              <el-input ref="mczydl" v-model="temp.mczydl" :disabled="dialogStatus==='see'"  />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="牧场总用水量（吨）：" prop="mczysl">
              <el-input ref="mczysl" v-model="temp.mczysl"  :disabled="dialogStatus==='see'" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="牧场电费单价（元/度）：" prop="mcdfdj ">
              <el-input ref="mcdfdj " v-model="temp.mcdfdj "  :disabled="dialogStatus==='see'" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="牧场水费单价（元/吨）：" prop="mcsfdj">
              <el-input ref="mcsfdj" v-model="temp.mcsfdj" :disabled="dialogStatus==='see'"  />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="牧场柴油单价量（元/升）：" prop="mccydj">
              <el-input ref="mccydj" v-model="temp.mccydj"  :disabled="dialogStatus==='see'" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="牧场煤炭单价（元/吨）：" prop="mcmtdj">
              <el-input ref="mcmtdj" v-model="temp.mcmtdj"  :disabled="dialogStatus==='see'" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="牧场天然气单价（元/方）：" prop="mctrqdj">
              <el-input ref="mctrqdj" v-model="temp.mctrqdj" :disabled="dialogStatus==='see'"  />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="生物质颗粒单价（元/吨）：" prop="swzkldj">
              <el-input ref="swzkldj" v-model="temp.swzkldj"  :disabled="dialogStatus==='see'" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单头牛用电量价（度/头日）：" prop="dtnydl">
              <el-input ref="dtnydl" v-model="temp.dtnydl"  :disabled="dialogStatus==='see'" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单头牛用水量价（吨/头日）：" prop="dtnysl">
              <el-input ref="dtnysl" v-model="temp.dtnysl" :disabled="dialogStatus==='see'"  />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="单头牛用油量（升/头日）：" prop="dtnyyl">
              <el-input ref="dtnyyl" v-model="temp.dtnyyl" :disabled="dialogStatus==='see'"  />
            </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>
    
   
  </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, json2excel } 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: 'EnergyConsum',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      isokDisable: false,
      isElecAdd: [],
      isElecAdd2: [],
      isElecExport: [],
      isElecImport: [],
      isElecModify: [],
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
 
   
      requestParam: {
        name: 'insertElectricity',
        offset: 0,
        pagecount: 0,
        parammaps: {}
      },
      postDataPramas: {

      },
      // 1-2:table&搜索传参
      tableObj: {
        name: 'getEnergyList',
        page: 1,
        offset: 1,
        pagecount: 10,
        returntype: 'Map',
        parammaps: {
            pastureName: Cookies.get('pasturename'),  date: '',  startdate: '',  enddate: '',  
        }
      },
      downLoadObj: {
        name: 'getEnergyList',
        page: 1,
        offset: 1,
        pagecount: 0,
        returntype: 'Map',
        parammaps: {
            pastureName: Cookies.get('pasturename'),  date: '',  startdate: '',  enddate: '',  
        }
      },
      downLoadList:[],
      // 2-3：下拉框请求后数据加入[]
      useTypes: [{ id: 0, name: '1级表' }, { id: 1, name: '2级表' }, { id: 2, name: '3级表' }],
      getDictByName: [],
      findAllAssetType: [],
     
 
      pastureList: [],
      departList1:[],
      departList2:[],
      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: 'findAllEmploye', offset: 0, pagecount: 0, parammaps: { 'pastureId': Cookies.get('pastureid') }}
      ],
      getDepartParam1: {
        name: 'findAllDepart', offset: 0, pagecount: 0, parammaps: { 'pastureId': Cookies.get('pastureid') }
      },
      getDepartParam2: {
        name: 'findAllDepart', offset: 0, pagecount: 0, parammaps: { 'pastureId': Cookies.get('pastureid') }
      },
      requestFilterParams: {
        name: 'getElecList',
        page: 1,
        offset: 1,
        pagecount: 10,
        returntype: 'Map',
        parammaps: { }
      },

      temp: { 
        "pastureName": '',
        "pastureId": '',
        "date": parseTime(new Date(), '{y}-{m}'),
        "firstday": "","mcwgdl": "","zqfdl": "","mcwgsl": "","mczbjqsl": "","mccyyl": "","mcmtyl": "","swzklyl": "","mctrqyl": "","mczydl": "","mczysl": "","mcdfdj": "0","mcsfdj": "","mccydj": "","mcmtdj": "","mctrqdj": "","swzkldj": "","dtnydl": "","dtnysl": "0","dtnyyl": ""
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新增',
        DosageRecord: '用量记录',
        delete: '删除'
      },
      dialogFormDosageRecord: false,
      totalDosageRecord: 0,
      listDosageRecord: [],
    
      getDosageRecordListParm: {
        name: 'getBiomassList',
        page: 1,
        offset: 1,
        pagecount: 10,
        returntype: 'Map',
        parammaps: { "departmentId": ""}
      },
      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' }],
      
        // startTime: [{ required: true, message: '必填', trigger: 'blur' }]
      },
    
      rowStyle: { maxHeight: 50 + 'px', height: 45 + 'px' },
      cellStyle: { padding: 0 + 'px' },
      buttons: [],
      isPercentage: false,
      percentage: 1,
      dialogFormDelete: false,
      deleteTemp: {},
      myHeight:document.documentElement.clientHeight - 85- 150
    }
  },

  computed: {
    // 设置请求头
    headers() {
      return {
        // 设置token
        token: getToken()
      }
    },
    uploadData() {
      return {
        name: 'importEnergy',
        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 ElecAdd = 'energyConsum:add' 
      const isElecAdd = checkButtons(this.$store.state.user.buttons, ElecAdd)
      this.isElecAdd = isElecAdd

      const ElecAdd2 = 'energyConsum:moban' 
      const isElecAdd2 = checkButtons(this.$store.state.user.buttons, ElecAdd2)
      this.isElecAdd2 = isElecAdd2
      // 导出
      const ElecExport = 'energyConsum:daochu'
      const isElecExport = checkButtons(this.$store.state.user.buttons, ElecExport)
      this.isElecExport = isElecExport
      // 导入
      const ElecImport = 'energyConsum:daoru'
      const isElecImport = checkButtons(this.$store.state.user.buttons, ElecImport)
      this.isElecImport = isElecImport
      // 编辑
      const ElecModify = 'energyConsum:edit'
      const isElecModify = checkButtons(this.$store.state.user.buttons, ElecModify)
      this.isElecModify = isElecModify
    },
    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)
    },
   
    form_export() {
      this.downLoadObj.parammaps = this.tableObj.parammaps
      GetDataByName(this.downLoadObj).then(response => {
        if (response.data.list !== null) {
          this.downLoadList = response.data.list
        } else {
          this.downLoadList = []
        }

        var excelDatasTabChart1 = [
          {
            tHeader: [
              '能源消耗统计(牧场)', '月份', '全群饲养头日', '牧场外购电量(度)', '沼气发电量(度)', '牧场外购水量(吨)', '牧场自备井取水量(吨)', '牧场柴油用量(升)', '牧场煤炭用量(吨)', '生物质颗粒用量(吨)', '牧场天然气用量(方)', '牧场总用电量(度)', '牧场总用水量(吨)', '牧场电费单价(元/度)', '牧场水费单价(元/吨)', '牧场柴油单价(元/升)', '牧场煤炭单价(元/吨)', '牧场天然气单价(元/方)', '生物质颗粒单价(元/吨)', '单头牛用电量(度/头日)', '单头牛用水量(吨/头日)', '单头牛用油量(升/头日)'
            ],
            filterVal: ['pastureName', 'date', 'firstday', 'mcwgdl', 'zqfdl', 'mcwgsl', 'mczbjqsl', 'mccyyl', 'mcmtyl', 'swzklyl', 'mctrqyl', 'mczydl', 'mczysl', 'mcdfdj', 'mcsfdj', 'mccydj', 'mcmtdj', 'mctrqdj', 'swzkldj', 'dtnydl', 'dtnysl', 'dtnyyl'  ],
            tableDatas: this.downLoadList,
            sheetName: 'SheetJS'
          }
        ]
        json2excel(excelDatasTabChart1, '能源消耗统计', true, '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 isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('上传文件大小不能超过 2MB!')
      }
      return isLt2M
    },
    handleImportExcelSuccess(res, file) {
      this.get_table_data()
      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 })
      }
    },
   
  
   
  
    // 1-1: table&搜索
    get_table_data() {
      if(this.tableObj.parammaps.pastureName == '现代牧业'){
        this.tableObj.parammaps.pastureName =''
      }
      this.listLoading = true
      GetDataByName(this.tableObj).then(response => {
        if (response.data.list == null) {
          this.list = []
           this.total = 0
        } 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.pastureList = response.data.findAllPasture.list
        this.findAllEmploye = response.data.findAllEmploye.list
        this.get_departList1()
        this.get_departList2()
      })
    },
    
    change_pasture1(item) {
      this.getDepartParam1.parammaps.pastureId = this.pastureList.find(obj => obj.name == item).id
      this.tableObj.parammaps.departName = ''
      this.get_departList1()
    },
    get_departList1() {
      GetDataByName(this.getDepartParam1).then(response => {
        this.departList1 = response.data.list
      })
    },


    change_pasture2(item) {
      this.getDepartParam2.parammaps.pastureId = item
      this.temp.departmentId = ''
      this.get_departList2()
    },
    get_departList2() {
      GetDataByName(this.getDepartParam2).then(response => {
        this.departList2 = response.data.list
      })
    },

    form_search() {
      this.listLoading = true
      this.tableObj.offset = 1
      if(this.tableObj.parammaps.date == null || this.tableObj.parammaps.date == ""){
        this.tableObj.parammaps.date =''
        this.tableObj.parammaps.startdate =''
        this.tableObj.parammaps.enddate =''
      } else {
        this.tableObj.parammaps.startdate =parseTime(this.tableObj.parammaps.date[0], '{y}-{m}')
        this.tableObj.parammaps.enddate =parseTime(this.tableObj.parammaps.date[1], '{y}-{m}')

        
      }
      console.log(this.tableObj.parammaps)

 
    
      this.get_table_data()
    },


    change_emp(item){
      console.log('记录人', item)
      this.$set(this.temp, 'inputid', item)
      this.$forceUpdate()
    },
   
    form_reset() {

    
 
      this.temp = { 
        "pastureName": '',
        "pastureId": '',
        "date": parseTime(new Date(), '{y}-{m}'),
        "firstday": "","mcwgdl": "","zqfdl": "","mcwgsl": "","mczbjqsl": "","mccyyl": "","mcmtyl": "","swzklyl": "","mctrqyl": "","mczydl": "","mczysl": "","mcdfdj": "","mcsfdj": "","mccydj": "","mcmtdj": "","mctrqdj": "","swzkldj": "","dtnydl": "","dtnysl": "","dtnyyl": ""
      }


      
    },
    form_add() {
      this.form_reset()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
       
      this.$nextTick(() => {
        this.$refs['temp'].clearValidate()
      })
 
    },
   
    
    add_dialog_save() {
      console.log("this.temp=====>",this.temp)
      this.isokDisable = true
      setTimeout(() => {
        this.isokDisable = false
      }, 1000)
      this.$refs['temp'].validate(valid => {
        if (valid) {



          this.temp.date =   parseTime(this.temp.date, '{y}-{m}') 
          var send_data = {
            "common": {  "returnmap": "0"  },
            "data": [
               {
                  "name": "insertEnergy",   "type": "e",
                  "parammaps": this.temp
                }
            ]
          }

          
          
          ExecDataByConfig(send_data).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
              })
            }
          })
        }
      })
    },
    // 继续新增
    add_dialog_save_again() {
      this.isokDisable = true
      setTimeout(() => {
        this.isokDisable = false
      }, 1000)
      this.$refs['temp'].validate(valid => {
        if (valid) {

          this.temp.date =   parseTime(this.temp.date, '{y}-{m}') 
          var send_data = {
            "common": {  "returnmap": "0"  },
            "data": [
               {
                  "name": "insertEnergy",   "type": "e",
                  "parammaps": this.temp
                }
            ]
          }
          
          ExecDataByConfig(send_data).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) {

      console.log("row=======",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.temp.date =   parseTime(this.temp.date, '{y}-{m}') 
          var send_data = {
            "common": {  "returnmap": "0"  },
            "data": [
               {
                  "name": "editEnergyList",   "type": "e",
                  "parammaps": this.temp
                }
            ]
          }
          
          ExecDataByConfig(send_data).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(row) {
      MessageBox.confirm('是否确认删除？', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          
          var send_data = {
              "common": {  "returnmap": "0"  },
              "data": [
                 {
                 "name": "deleteEnergy", "type": "e",
                  "parammaps": { "id":row.id  }
                 }
              ]
          }
          ExecDataByConfig(send_data).then(() => {
            this.get_table_data()
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
     
    // 导出模板
    handleDownloadTemp() {
      this.requestParam.name = 'pStockDownTemp'
      GetDataByName(this.requestParam).then(response => {
        this.$nextTick(() => {
          import('@/vendor/Export2Excel').then(excel => {
            const list1 = response.data.list
            const tHeader = [
            '能源消耗统计(牧场)', '月份', '全群饲养头日', '牧场外购电量(度)', '沼气发电量(度)', '牧场外购水量(吨)', '牧场自备井取水量(吨)', '牧场柴油用量(升)', '牧场煤炭用量(吨)', '生物质颗粒用量(吨)', '牧场天然气用量(方)', '牧场总用电量(度)', '牧场总用水量(吨)', '牧场电费单价(元/度)', '牧场水费单价(元/吨)', '牧场柴油单价(元/升)', '牧场煤炭单价(元/吨)', '牧场天然气单价(元/方)', '生物质颗粒单价(元/吨)', '单头牛用电量(度/头日)', '单头牛用水量(吨/头日)', '单头牛用油量(升/头日)'
            ]
            const filterVal = [
            '能源消耗统计(牧场)', '月份', '全群饲养头日', '牧场外购电量(度)', '沼气发电量(度)', '牧场外购水量(吨)', '牧场自备井取水量(吨)', '牧场柴油用量(升)', '牧场煤炭用量(吨)', '生物质颗粒用量(吨)', '牧场天然气用量(方)', '牧场总用电量(度)', '牧场总用水量(吨)', '牧场电费单价(元/度)', '牧场水费单价(元/吨)', '牧场柴油单价(元/升)', '牧场煤炭单价(元/吨)', '牧场天然气单价(元/方)', '生物质颗粒单价(元/吨)', '单头牛用电量(度/头日)', '单头牛用水量(吨/头日)', '单头牛用油量(升/头日)'
            ]
            const data1 = this.formatJson(filterVal, list1)
            excel.export_json_to_excel({
              header: tHeader,
              data: data1,
              filename: '模板',
          
              autoWidth: true,
              bookType: 'xlsx'
            })
          })
        })
      })
    },
  

  }
}
</script>
