<template>
  <div class="app-container">
    <div v-if="isPercentage" class="percentage" style="width: 210px;height: 90px;background: #fff;position: fixed;bottom: 0;left: 0;z-index: 9999999999999;">
      <h4 style="padding-left: 10px;line-height: 0;">导出进度：</h4>
      <el-progress style="padding-left: 10px;" :text-inside="true" :stroke-width="26" :percentage="percentage" />
    </div>
    <div class="filter-container">
      <el-select
        v-model="getdataListParm.parammaps.pastureName"
        placeholder="牧场"
        style="width: 120px;"
        class="filter-item"
      >
        <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: 120px;"
        class="filter-item"
        clearable
      >
        <el-option
          v-for="item in findAllDepart"
          :key="item.id"
          :label="item.name"
          :value="item.name"
        />
      </el-select>
      <el-input
        v-model="getdataListParm.parammaps.formNumber"
        placeholder="类型"
        clearable
        class="filter-item"
        style="width: 120px"
      />
      <el-select
        v-model="getdataListParm.parammaps.empName"
        clearable
        placeholder="记录人"
        class="filter-item"
        style="width:120px"
      >
        <el-option
          v-for="item in findAllEmploye"
          :key="item.id"
          :label="item.name"
          :value="item.name"
        />
      </el-select>
      <el-date-picker
        v-model="getdataListParm.parammaps.logTime"
        type="date"
        placeholder="记录时间"
        style="width:120px;top:-3px;"
        format="yyyy-MM-dd"
        value-format="yyyy-MM-dd"
      />
      <!-- <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="isRetreatAdd"
          class="filter-item"
          type="primary"
          icon="el-icon-edit"
          @click="form_add"
        >新增</el-button>
        <!-- <el-button
          v-if="isRetreatExport"
          v-waves
          class="filter-item"
          type="primary"
          icon="el-icon-download"
          @click="handleDownload"
        >导出</el-button> -->
        <el-button
          v-if="isRetreatMuban"
          v-waves
          class="filter-item"
          type="info"
          icon="el-icon-download"
          @click="handleDownloadTemp"
        >模板</el-button>
        <el-upload
          style="display: inline-block;"
          :headers="headers"
          :data="uploadData"
          :action="uploadExcelUrl"
          :show-file-list="false"
          :before-upload="beforeImportExcel"
          :on-success="handleImportExcelSuccess"
        >
          <el-button
            v-if="isRetreatImport"
            v-waves
            class="filter-item"
            type="warning"
            icon="el-icon-upload2"
            @click="form_search"
          >导入</el-button>
        </el-upload>
      </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="110px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.pastureName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="部门" width="110px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.deptName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="类型" width="110px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.classes }}</span>
        </template>
      </el-table-column>
      <el-table-column label="单位" width="110px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.unit }}</span>
        </template>
      </el-table-column>
      <el-table-column label="单价" min-width="110px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.price }}</span>
        </template>
      </el-table-column>
      <el-table-column label="数量" min-width="110px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.amount }}</span>
        </template>
      </el-table-column>
      <el-table-column label="总价" min-width="110px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.sumPrice }}</span>
        </template>
      </el-table-column>
      <el-table-column label="记录人" width="110px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.empName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="记录时间" min-width="110px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.logTime }}</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="录入人" min-width="110px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.inputName }}</span>
        </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"
    />
  </div>
</template>

<script>
// 引入
require('script-loader!file-saver')
import { GetDataByName, GetDataByNames, 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: 'Water',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      isRetreatAdd: [],
      isRetreatMuban: [],
      isRetreatExport: [],
      isRetreatImport: [],
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      temp: {},
      // 1-2:table&搜索传参
      getdataListParm: {
        name: 'getImportCostOtherList',
        page: 1,
        offset: 1,
        pagecount: 10,
        returntype: 'Map',
        parammaps: {
          pastureName: Cookies.get('pasturename'),
          deptName: '',
          classes: '',
          empName: '',
          logTime: ''
        }
      },
      // 2-3：下拉框请求后数据加入[]
      getDictByName: [],
      findAllAssetType: [],
      findAllPasture: [],
      findAllDepart: [],
      findAllEmploye: [],

      requestParam: {
        name: 'insertAsset',
        offset: 0,
        pagecount: 0,
        parammaps: {}
      },
      // 2-1.请求下拉框接口
      requestParams: [
        {
          name: 'getDictByName',
          offset: 0,
          pagecount: 0,
          params: ['水表类型']
        },
        { name: 'findAllAssetType', offset: 0, pagecount: 0, params: [] },
        { name: 'findAllPasture', offset: 0, pagecount: 0, returntype: 'Map', parammaps: { 'id': Cookies.get('pastureid') }},
        { name: 'findAllDepart', offset: 0, pagecount: 0, parammaps: { 'pastureId': Cookies.get('pastureid') }},
        { name: 'findAllEmploye', offset: 0, pagecount: 0, parammaps: { 'pastureId': Cookies.get('pastureid') }}
      ],
      requestFilterParams: {
        name: 'getWaterList',
        page: 1,
        offset: 1,
        pagecount: 10,
        returntype: 'Map',
        parammaps: {}
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新增'
      },
      dialogPvVisible: false,
      MeasureListbyfilter: [],
      rowStyle: { maxHeight: 50 + 'px', height: 45 + 'px' },
      cellStyle: { padding: 0 + 'px' },
      isPercentage: false,
      percentage: 1
    }
  },

  computed: {
    // 设置请求头
    headers() {
      return {
        // 设置token
        token: getToken()
      }
    },
    uploadData() {
      return {
        name: 'importCostOther',
        importParams: '牧场,部门,类型,单位,单价,数量,总价,记录人,记录时间,备注,jwt_username',
        sheetname: 'SheetJS'
      }
    },
    // 设置上传地址
    uploadExcelUrl() {
      // process.env.VUE_APP_BASE_API是服务器的路径，也是axios的基本路径
      return process.env.VUE_APP_BASE_API + 'authdata/ImportExcel'
    }
  },

  created() {
    this.get_table_data()
    this.get_select_list()
  },

  methods: {
    // 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_add() {
      this.form_reset()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.temp.employeId = this.$store.state.user.employeid
    },

    // 导出模板
    handleDownloadTemp() {
      this.requestParam.name = 'costOtherDownTemp'
      GetDataByName(this.requestParam).then(response => {
        this.$nextTick(() => {
          import('@/vendor/Export2Excel').then(excel => {
            const list1 = response.data.list
            const tHeader = [
              '牧场', '部门', '类型', '单位', '单价', '数量', '总价', '记录人', '记录时间', '备注']
            const filterVal = [
              '牧场', '部门', '类型', '单位', '单价', '数量', '总价', '记录人', '记录时间', '备注']
            const data1 = this.formatJsonTemp(filterVal, list1)
            excel.export_json_to_excel({
              header: tHeader,
              data: data1,
              filename: '其它成本模板',
              autoWidth: true,
              bookType: 'xlsx'
            })
          })
        })
      })
    },
    formatJsonTemp(filterVal, jsonData) {
      return jsonData.map(v =>
        filterVal.map(j => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        })
      )
    },

    // 导出
    handleDownload() {
      this.requestParam.name = 'stockQuitDown'
      this.requestParam.parammaps.useForm = this.getdataListParm.parammaps.useForm
      this.requestParam.parammaps.createTime = this.getdataListParm.parammaps.createTime
      this.$alert('退库时间正在导出中，请勿刷新或离开本页面，若导出时间过长，建议缩小导出数据范围重新导出', {})
      this.isPercentage = true
      this.percentage = 1
      var timer = setInterval(() => {
        this.percentage += 5
        if (this.percentage > 95) {
          this.percentage = 99
          clearInterval(timer)
        }
        this.percentage = this.percentage
      }, 1000)
      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 = [
              '领用单号', '类型', '牧场名称', '部门名称', '退库时间', '退库人', '备件编号', '备件名称', '规格', '退库数量', '备注'
            ]
            const data1 = this.formatJson(filterVal, list1)
            excel.export_json_to_excel({
              header: tHeader,
              data: data1,
              filename: '退库时间：' + this.getdataListParm.parammaps.createTime,
              autoWidth: true,
              bookType: 'xlsx'
            })
          })
        })
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v =>
        filterVal.map(j => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        })
      )
    },
    // 导入
    beforeImportExcel(file) {
      /*   const isExcel =
        file.type ===
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' */
      const isLt2M = file.size / 1024 / 1024 < 2
      /*  if (!isExcel) {
        this.$message.error(
          '上传文件必须是Xlsx格式!建议先导出，再修改导出文件再导入！'
        )
      }*/
      if (!isLt2M) {
        this.$message.error('上传文件大小不能超过 2MB!')
      }
      return isLt2M
    },
    handleImportExcelSuccess(res, file) {
    //  if (res.msg === 'ok') {
      if (res.msg === 'ok') {
        this.$message({
          title: '成功',
          message: '导入成功:' + res.data.success + '条!',
          type: 'success',
          duration: 2000
        })
        if (res.data.err_count > 0) {
          this.$notify({
            title: '失败',
            message: '导入失败:' + res.data.err_count + '条!',
            type: 'danger',
            duration: 2000
          })
        }
      } else {
        this.$notify({
          title: '失败',
          message: '上传失败',
          type: 'danger',
          duration: 2000
        })
      }
    },

    form_search() {
      this.listLoading = true
      this.getdataListParm.offset = 1
      this.get_table_data()
    },
    form_reset() {}
  }
}
</script>

