<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="table.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="table.getdataListParm.parammaps.departName" clearable placeholder="部门" class="filter-item">
        <el-option v-for="item in findAllDepart" :key="item.id" :label="item.name" :value="item.name" />
      </el-select>
      <el-select v-model="table.getdataListParm.parammaps.departName" clearable placeholder="能源类型" class="filter-item">
        <el-option v-for="item in energyTypeList" :key="item.id" :label="item.name" :value="item.name" />
      </el-select>
      <el-date-picker v-model="table.getdataListParm.parammaps.createDate" type="date" placeholder="日期" style="width:140px;top:-3px;" format="yyyy-MM-dd" value-format="yyyy-MM-dd" />
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="form_search">搜索</el-button>
    </div>
    <div class="operation">
      <el-button v-if="isGenerationAdd" class="filter-item" type="primary" icon="el-icon-edit" @click="form_add">新增</el-button>
      <el-button v-if="isGenerationExport" 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="isGenerationImport" 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 class="table">
      <el-table
        :key="table.tableKey"
        v-loading="table.listLoading"
        element-loading-text="给我一点时间"
        :data="table.list"
        border
        fit
        highlight-current-row
        style="width: 100%;"
        :row-style="rowStyle"
        :cell-style="cellStyle"
        class="elTable"
      >
        <el-table-column label="序号" align="center" type="index" width="50px">
          <template slot-scope="scope">
            <span>{{ scope.$index + (table.pageNum-1) * table.pageSize + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="牧场" min-width="90px" align="center" prop="pastureName" />
        <el-table-column label="部门" min-width="90px" align="center" prop="departName" />
        <el-table-column label="能源类型"min- width="90px" align="center" prop="energyType" />
        <el-table-column label="预算" min-width="90px" align="center" prop="budget" />
        <el-table-column label="实际" min-width="90px" align="center" prop="actual" />
        <el-table-column label="同期" min-width="90px" align="center" prop="contemporaneous" />
        <el-table-column label="VS同期" min-width="90px" align="center" prop="vsContemporaneous" />
        <el-table-column label="VS预算" min-width="90px" align="center" prop="vsBudget" />
        <el-table-column label="预算达成率" min-width="90px" align="center" prop="budgetAchievementRate" />
        <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width" fixed="right">
          <template slot-scope="{row}">
            <el-button v-if="isGenerationEdit" type="success" size="mini" @click="form_edit(row)">编辑</el-button>
            <el-button type="danger" size="mini" @click="handleRowDelete()(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="table.total>0" :total="table.total" :page.sync="table.getdataListParm.offset" :limit.sync="table.getdataListParm.pagecount" @pagination="get_table_data" />
    </div>
    <el-dialog :title="textMap[create.dialogStatus]" :visible.sync="create.dialogFormVisible" :close-on-click-modal="false">
      <el-form ref="temp" :rules="create.rules" :model="create.temp" label-position="right" label-width="110px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="牧场:" prop="pastureId">
              <el-select v-model="create.temp.pastureId" placeholder="牧场" class="filter-item" style="width:100%" @change="changePastureName">
                <el-option v-for="item in findAllPasture" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="部门:" prop="departmentId">
              <el-select v-model="create.temp.departmentId" placeholder="部门" class="filter-item" style="width:100%" :disabled="create.dialogStatus=='update'">
                <el-option v-for="item in createDepartList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="能源类型:" prop="formNumber">
              <el-select v-model="create.temp.employeId" placeholder="能源类型" class="filter-item" style="width:100%" :disabled="create.dialogStatus=='update'">
                <el-option v-for="item in energyTypeList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="用量:" prop="formNumber">
              <el-input ref="price1" v-model="create.temp.price1" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="总价:" prop="formNumber">
              <el-input ref="price1" v-model="create.temp.price1" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="记录人:" prop="formNumber">
              <el-select v-model="create.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-row>
          <el-col :span="8">
            <el-form-item label="录入日期:" prop="DATE">
              <el-date-picker v-model="create.temp.DATE" type="date" placeholder="录入日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd" style="width:100%;" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="备注:" prop="note">
              <el-input ref="note" v-model="create.temp.note" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="create.dialogStatus==='create'" ref="createb" type="success" :disabled="isokDisable" @click="add_dialog_save_again()">保存并新增</el-button>
        <el-button type="primary" :disabled="isokDisable" @click="create.dialogStatus==='create'?add_dialog_save():edit_dialog_save()">保存并关闭</el-button>
        <el-button @click="create.dialogFormVisible = false;get_table_data()">取消并关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 引入
import { GetDataByName, GetDataByNames, PostDataByName, checkButtons, ExecDataByConfig, GetAccount } from '@/api/common'
import waves from '@/directive/waves'
import { parseTime, sortChange } from '@/utils/index.js'
import Pagination from '@/components/Pagination'
import { MessageBox } from 'element-ui'
import { getToken } from '@/utils/auth'
import Cookies from 'js-cookie'
export default {
  name: 'Generation',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      isGenerationAdd: [], isGenerationExport: [], isGenerationImport: [], isGenerationEdit: [],
      table: {
        tableKey: 0, list: [], total: 0, listLoading: true,
        getdataListParm: {
          name: 'getElecList', page: 1, offset: 1, pagecount: 10, returntype: 'Map',
          parammaps: {
            formName: '', formNumber: '', formType: '', pastureName: Cookies.get('pasturename'), departName: ''
          }
        }
      },
      energyTypeList: [], findAllPasture: [], findAllDepart: [], findAllEmploye: [], createDepartList: [],
      requestParams: [
        { name: 'findAllPasture', offset: 0, pagecount: 0, returntype: 'Map', parammaps: { 'id': 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') }
      },
      textMap: { update: '编辑', create: '新增', delete: '删除' },
      create: {
        dialogFormVisible: false,
        dialogStatus: '',
        temp: {},
        rules: {}
      },

      isokDisable: false,
      isPercentage: false,
      rowStyle: { maxHeight: 50 + 'px', height: 45 + 'px' },
      cellStyle: { padding: 0 + 'px' },
      buttons: [],
      percentage: 1,
      edit: 0
    }
  },
  computed: {
    // 设置请求头
    headers() {
      return {
        // 设置token
        token: getToken()
      }
    },
    uploadData() {
      return {
        name: 'insertElecsMeasure',
        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 GenerationAdd = 'cost:generation:add'
      const isGenerationAdd = checkButtons(this.$store.state.user.buttons, GenerationAdd)
      this.isGenerationAdd = isGenerationAdd
      // 导出
      const GenerationExport = 'cost:generation:export'
      const isGenerationExport = checkButtons(this.$store.state.user.buttons, GenerationExport)
      this.isGenerationExport = isGenerationExport
      // 导入
      const GenerationImport = 'cost:generation:import'
      const isGenerationImport = checkButtons(this.$store.state.user.buttons, GenerationImport)
      this.isGenerationImport = isGenerationImport
      // 编辑
      const GenerationEdit = 'cost:generation:edit'
      const isGenerationEdit = checkButtons(this.$store.state.user.buttons, GenerationEdit)
      this.isGenerationEdit = isGenerationEdit
    },
    get_table_data() {
      this.table.listLoading = true
      GetDataByName(this.table.getdataListParm).then(response => {
        if (response.data.list == null) {
          this.table.list = []
        } else {
          this.table.list = response.data.list
          this.table.pageNum = response.data.pageNum
          this.table.pageSize = response.data.pageSize
        }
        setTimeout(() => {
          this.table.listLoading = false
        }, 100)
      })
    },
    form_search() {
      this.get_table_data()
    },
    get_select_list() {
      GetDataByNames(this.requestParams).then(response => {
        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()
    },
    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 })
      }
    },
    beforeImportExcel(file) {
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('上传文件大小不能超过 2MB!')
      }
      return isLt2M
    },
    form_reset() {
      this.create.temp.pastureId = parseInt(Cookies.get('pastureid'))
      this.create.temp.departmentId = ''
      this.create.temp.employeId = Cookies.get('employeid')
    },
    form_add() {
      this.form_reset()
      this.edit = 1
      this.create.dialogStatus = 'create'
      this.create.dialogFormVisible = true
      this.getDepartParam.parammaps.pastureId = this.create.temp.pastureId
      this.getCreateDepartDownList()
    },
    add_dialog_save_again() {},
    form_edit(row) {
      this.create.dialogStatus = 'update'
      this.create.dialogFormVisible = true
      this.edit = 0
      this.getDepartParam.parammaps.pastureId = row.pastureId
      this.getCreateDepartDownList()
    },
    getCreateDepartDownList() {
      GetDataByName(this.getDepartParam).then(response => {
        this.createDepartList = response.data.list
        if (this.edit == 1) {
          if (this.createDepartList.find(obj => obj.id == Cookies.get('departmentid'))) {
            this.create.temp.departmentId = parseInt(Cookies.get('departmentid'))
            this.create.temp.departmentName = this.createDepartList.find(obj => obj.id == Cookies.get('departmentid')).name
          } else {
            this.create.temp.departmentId = response.data.list[0].id
            this.create.temp.departmentId = response.data.list[0].id
          }
        }
      })
    },
    handleRowDelete() {},
    edit_dialog_save() {},
    handleDownload() {},
    form_delete() {}
  }
}
</script>
<style lang="scss" scoped>
  .operation{margin-bottom: 10px;}
</style>
