<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"
      >
        <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"
        placeholder="沼气类型"
        style="width: 140px;"
        class="filter-item"
        clearable
      >
        <el-option
          v-for="item in getDictByName"
          :key="item.id"
          :label="item.label"
          :value="item.value"
        />
      </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="isMethaneAdd"
          class="filter-item"
          type="primary"
          icon="el-icon-edit"
          @click="form_add"
        >新增</el-button>
        <el-button
          v-if="isMethaneExport"
          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="isMethaneImport"
            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"
    >
      <!-- table表格 -->
      <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.methaneNumber }}</span>
        </template>
      </el-table-column>
      <el-table-column label="名称" width="80px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.methaneName }}</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="当天用气量" width="80px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.methaneConsumption }}</span>
        </template>
      </el-table-column>
      <el-table-column label="单价" width="80px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.price }}</span>
        </template>
      </el-table-column>
      <el-table-column label="当天费用" 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">
        <template slot-scope="scope">
          <span>{{ scope.row.dateFormat }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" min-width="110px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.note }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width" fixed="right">
        <template slot-scope="{row}">
          <el-button
            v-if="isMethaneModify"
            type="success"
            size="mini"
            @click="form_edit(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'"
                @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'"
                @select="handleformNameSelect"
                @blur="blurSelect"
              />
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="上次值(m³)：" prop="aAmount">
              <el-input
                ref="aAmount"
                v-model="temp.aAmount"
                disabled
              />
            </el-form-item>
          </el-col>
          <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-col :span="8">
            <el-form-item label="当前值(m³)：" prop="endAmount">
              <el-input
                ref="endAmount"
                v-model="temp.endAmount"
              />
            </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-col :span="8">
            <el-form-item label="备注：" prop="note">
              <el-input
                ref="note"
                v-model="temp.note"
              />
            </el-form-item>
          </el-col>
          <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">
                <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>
  </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 } 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: 'Methane',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      isokDisable: false,
      isMethaneAdd: [],
      isMethaneExport: [],
      isMethaneImport: [],
      isMethaneModify: [],
      formNumberSearchList: [],
      formNameSearchList: [],
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,

      requestParam: {
        name: 'insertMethane',
        offset: 0,
        pagecount: 0,
        parammaps: {}
      },
      postDataPramas: {

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

      temp: { pastureName: '',
        measureId: '',
        useType: '',
        departName: '',
        aAmount: '',
        employeName1: '',
        formName: '',
        formNumber: '',
        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: '新增'
      },
      dialogPvVisible: false,
      // 校验规则
      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' }]
      },
      MeasureListbyfilter: [],
      rowStyle: { maxHeight: 50 + 'px', height: 45 + 'px' },
      cellStyle: { padding: 0 + 'px' },
      buttons: [],
      isPercentage: false,
      percentage: 1
    }
  },

  computed: {
    // 设置请求头
    headers() {
      return {
        // 设置token
        token: getToken()
      }
    },
    uploadData() {
      return {
        name: 'insertMethanesMeasure',
        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: {
    get_auto_buttons() {
      // 新增
      const MethaneAdd = 'cost:methane:add'
      const isMethaneAdd = checkButtons(this.$store.state.user.buttons, MethaneAdd)
      this.isMethaneAdd = isMethaneAdd
      // 导出
      // eslint-disable-next-line no-redeclare
      const MethaneExport = 'cost:methane:export'
      const isMethaneExport = checkButtons(this.$store.state.user.buttons, MethaneExport)
      this.isMethaneExport = isMethaneExport
      // 导入
      // eslint-disable-next-line no-redeclare
      const MethaneImport = 'cost:methane:import'
      const isMethaneImport = checkButtons(this.$store.state.user.buttons, MethaneImport)
      this.isMethaneImport = isMethaneImport
      // 编辑
      // eslint-disable-next-line no-redeclare
      const MethaneModify = 'cost:methane:modify'
      const isMethaneModify = checkButtons(this.$store.state.user.buttons, MethaneModify)
      this.isMethaneModify = isMethaneModify
    },

    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 = 'ZZ流量计类型'
      GetDataByNameXlsx(this.requestParam).then(response => {
        this.$nextTick(() => {
          DownloadExcel(response, this.requestParam.parammaps.formType)
        }) */
      this.$alert('ZZ流量计正在导出中，请勿刷新或离开本页面，若导出时间过长，建议缩小导出数据范围重新导出', {})
      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 = 'ZZ流量计'
      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 => {
        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 = [
              '编号', '牧场', '表名称', '表编号', '抄表日期', '本次值', '抄表日期2', '本次值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: this.requestParam.parammaps.formType,
               autoWidth: true,
               bookType: 'xlsx'
             })
           })
        }
      } else {
        this.$notify({
          title: '失败',
          message: '上传失败',
          type: 'danger',
          duration: 2000
        })
      }
    },
    formNumberSearch(queryString, cb) {
      this.requestFilterParams.name = 'getMeasureListbyfilter'
      this.requestFilterParams.parammaps['formType'] = 'ZZ流量计'
      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'] = 'ZZ流量计'
      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 = 'findByNMeasureMethane'
      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
          }
        })
      })
    },
    handleformNameSelect() {
      this.requestFilterParams.name = 'findByNMeasureMethane'
      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
          }
        })
      })
    },
    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 => {
        this.list = response.data.list
        this.pageNum = response.data.pageNum
        this.pageSize = response.data.pageSize
        if (response.data.total) {
          this.total = response.data.total
        }
        // Just to simulate the time of the request
        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.findAllDepart = response.data.findAllDepart.list
        this.findAllEmploye = response.data.findAllEmploye.list
      })
    },
    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.pastureName = ''
      this.temp.useType = ''
      this.temp.departName = ''
      this.temp.aAmount = ''
      this.temp.employeName1 = ''
      this.temp.formName = ''
      this.temp.formNumber = ''
      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()
      })
    },
    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': 'insertMethaneExecData', '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,
            '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': '@insertMethaneExecData.LastInsertId'
            }}

          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
              })
            }
          })
        }
      })
    },
    // 继续新增
    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': 'insertMethaneExecData', '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,
            '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': '@insertMethaneExecData.LastInsertId'
            }}

          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_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.requestParam.name = 'updatMethane'
          // 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': 'updateMethane', 'type': 'e', 'parammaps': {
            'endAmount': this.temp.endAmount,
            'measureId': this.temp.measureId,
            // 'data': this.temp.inputDatetime,
            'id': this.temp.id,
            'note': this.temp.note,
            'employeId': this.temp.employeId,
            'consumption': this.temp.consumption
          }}

          this.postDataPramas.data[2] = { 'name': 'updateMeasureMethane', '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(row) {
      MessageBox.confirm('设备名称：' + row.equipmentName, '确认删除？', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.requestParam.name = 'deleteMethane'
        this.requestParam.parammaps = {}
        this.requestParam.parammaps['id'] = row.id
        PostDataByName(this.requestParam).then(() => {
          this.get_table_data()
          this.dialogFormVisible = false
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }
  }
}
</script>
