<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-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="form_search">搜索</el-button>
    </div>
    <div class="app-btn" style="height:50px">
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="form_add">新增</el-button>
      <el-button 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-waves class="filter-item" type="warning" icon="el-icon-upload2">导入</el-button>
      </el-upload>
      <el-button class="filter-item" style="margin-left: 10px;" type="success" icon="el-icon-edit" @click="handleDownload">导出</el-button>
    </div>
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      element-loading-text="给我一点时间"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      :row-style="rowStyle"
      :cell-style="cellStyle"
      class="elTable"
      @sort-change="tableSort"
    >
      <!-- 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="牧场" min-width="150px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.pastureName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="时间" min-width="150px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.feedDay }}</span>
        </template>
      </el-table-column>
      <el-table-column label="牛头数" sortable prop="cowNum" min-width="150px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.cowNum }}</span>
        </template>
      </el-table-column>
      <el-table-column label="泌乳牛牛头数" sortable prop="cowNumM" min-width="150px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.cowNumM }}</span>
        </template>
      </el-table-column>
      <el-table-column label="日销奶量（吨）" sortable prop="saleNum" min-width="150px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.saleNum }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width" fixed="right">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" @click="form_see(row)">查看</el-button>
          <el-button type="success" size="mini" @click="form_edit(row)">编辑</el-button>
          <el-button type="danger" size="mini" @click="form_delete(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="getList" />
    <!-- 弹出层新增or修改 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
      <el-form ref="createTemp" :rules="rules" :model="createTemp" label-position="right" label-width="140px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="牧场" prop="pastureId">
              <el-select v-model="createTemp.pastureId" placeholder="牧场" class="filter-item" style="width:100%" :disabled="dialogStatus==='see'||dialogStatus==='update'">
                <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="feedDay">
              <div class="block">
                <el-date-picker v-model="createTemp.feedDay" type="date" placeholder="日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd" style="width:100%" :disabled="dialogStatus==='see'||dialogStatus==='update'" />
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="牛头数：" prop="cowNum">
              <el-input ref="cowNum" v-model="createTemp.cowNum" :disabled="dialogStatus==='see'" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="泌乳牛牛头数:" prop="cowNumM">
              <el-input ref="cowNumM" v-model="createTemp.cowNumM" :disabled="dialogStatus==='see'" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="日销奶量（吨）：" prop="saleNum">
              <el-input ref="saleNum" v-model="createTemp.saleNum" :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" @click="add_dialog_save_again()">保存并新增</el-button>
        <el-button v-if="dialogStatus==='create' || dialogStatus==='update'" type="primary" @click="dialogStatus==='create'?add_dialog_save():edit_dialog_save()">保存并关闭</el-button>
        <el-button @click="dialogFormVisible = false;getList()">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 引入
require('script-loader!file-saver')
import { GetDataByName, GetDataByNames, PostDataByName, failproccess, GetAccount } from '@/api/common'
import waves from '@/directive/waves'
import { parseTime, json2excel, sortChange } from '@/utils/index.js'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { MessageBox } from 'element-ui'
import { getToken } from '@/utils/auth'
import Cookies from 'js-cookie'
export default {
  name: 'Feedings',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      // 校验规则
      rules: {
        pastureId: [{ required: true, message: '必填', trigger: 'blur' }],
        feedDay: [{ required: true, message: '必填', trigger: 'blur' }],
        saleNum: [{ type: 'number', required: true, validator: (rule, value, callback) => {
          if (!value) {
            callback(new Error('不能为空'))
          }
          setTimeout(() => {
            const re = /(^[1-9](\d+)?(\.\d{1,3})?$)|(^\d\.\d{1,2}$)/
            const rsCheck = re.test(value)
            if (!rsCheck) {
              callback(new Error('请输入正数,且最多保留两位小数'))
            } else {
              callback()
            }
          }, 0)
        }, trigger: 'blur' }],
        cowNumM: [{ type: 'number', required: true, validator: (rule, value, callback) => {
          if (!value) {
            callback(new Error('不能为空'))
          }
          setTimeout(() => {
            const re = /^[0-9]*[1-9][0-9]*$/
            const rsCheck = re.test(value)
            if (!rsCheck) {
              callback(new Error('请输入正整数'))
            } else {
              callback()
            }
          }, 0)
        }, trigger: 'blur' }],
        cowNum: [{ type: 'number', required: true, validator: (rule, value, callback) => {
          if (!value) {
            callback(new Error('不能为空'))
          }
          setTimeout(() => {
            const re = /^[0-9]*[1-9][0-9]*$/
            const rsCheck = re.test(value)
            if (!rsCheck) {
              callback(new Error('请输入正整数'))
            } else {
              callback()
            }
          }, 0)
        }, trigger: 'blur' }]
      },
      textMap: {
        update: '编辑',
        create: '新增',
        see: '查看详情'
      },
      rowStyle: { maxHeight: 50 + 'px', height: 45 + 'px' },
      cellStyle: { padding: 0 + 'px' },
      findAllPasture: [],
      requestParams: [
        { name: 'findAllPasture', offset: 0, pagecount: 0, returntype: 'Map', parammaps: { 'id': Cookies.get('pastureid') }}
      ],
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      getdataListParm: {
        name: 'getFeedsumlist',
        page: 1,
        offset: 1,
        pagecount: 10,
        returntype: 'Map',
        parammaps: {
          pastureName: Cookies.get('pasturename')
        }
      },
      dialogFormVisible: false,
      dialogStatus: '',
      createTemp: {
        pastureId: this.$store.state.user.pastureid,
        cowNum: '',
        feedDay: parseTime(new Date(), '{y}-{m}-{d}'),
        saleNum: '',
        cowNumM: ''
      },
      requestParam: {},
      downloadParam: {},
      isPercentage: false,
      percentage: 1
    }
  },

  computed: {
    // 设置请求头
    headers() {
      return {
        // 设置token
        token: getToken()
      }
    },
    uploadData() {
      return {
        name: 'uploadfeedsum',
        importParams: '牧场,时间,牛头数,泌乳牛牛头数,日销奶量（吨）',
        sheetname: 'SheetJS'
      }
    },
    // 设置上传地址
    uploadExcelUrl() {
      // process.env.VUE_APP_BASE_API是服务器的路径，也是axios的基本路径
      return process.env.VUE_APP_BASE_API + 'authdata/ImportExcel'
    }
  },
  created() {
    this.get_select_list()
    this.getList()
  },

  methods: {
    tableSort(column) {
      sortChange(column, this.list)
    },
    get_select_list() {
      GetDataByNames(this.requestParams).then(response => {
        this.findAllPasture = response.data.findAllPasture.list
      })
    },
    getList() {
      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)
      })
    },
    form_search() {
      this.listLoading = true
      this.getdataListParm.offset = 1
      this.getList()
    },
    resetCreateTemp() {
      this.createTemp.pastureId = this.$store.state.user.pastureid
      this.createTemp.cowNum = ''
      this.createTemp.feedDay = parseTime(new Date(), '{y}-{m}-{d}')
      this.createTemp.saleNum = ''
      this.createTemp.cowNumM = ''
    },
    form_add() {
      this.resetCreateTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['createTemp'].clearValidate()
      })
    },
    add_dialog_save() {
      this.$refs['createTemp'].validate(valid => {
        if (valid) {
          this.requestParam.name = 'insertFeedsum'
          this.requestParam.parammaps = this.createTemp
          PostDataByName(this.requestParam).then(response => {
            console.log('新增保存发送参数', this.requestParam)
            if (response.msg !== 'fail') {
              this.getList()
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '新增成功',
                type: 'success',
                duration: 2000
              })
            } else {
              var pmonth = new RegExp('pmonth')
              if (pmonth.test(response.data)) {
                this.$notify({
                  title: '',
                  message: '日期不可重复添加',
                  type: 'warning',
                  duration: 2000
                })
              } else {
                failproccess(response, this.$notify)
              }
            }
          })
        }
      })
    },
    add_dialog_save_again() {
      this.$refs['createTemp'].validate(valid => {
        if (valid) {
          this.requestParam.name = 'insertFeedsum'
          this.requestParam.parammaps = this.createTemp
          PostDataByName(this.requestParam).then(response => {
            console.log('新增保存发送参数', this.requestParam)
            if (response.msg !== 'fail') {
              // this.getList()
              // this.dialogFormVisible = false
              this.resetCreateTemp()
              this.$notify({
                title: '成功',
                message: '新增成功',
                type: 'success',
                duration: 2000
              })
            } else {
              var pmonth = new RegExp('pmonth')
              if (pmonth.test(response.data)) {
                this.$notify({
                  title: '',
                  message: '日期不可重复添加',
                  type: 'warning',
                  duration: 2000
                })
              } else {
                failproccess(response, this.$notify)
              }
            }
          })
        }
      })
    },
    form_edit(row) {
      this.createTemp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['createTemp'].clearValidate()
      })
    },
    edit_dialog_save() {
      this.$refs['createTemp'].validate(valid => {
        if (valid) {
          this.requestParam.name = 'updateFeedsum'
          this.requestParam.parammaps = this.createTemp
          PostDataByName(this.requestParam).then(response => {
            console.log('新增保存发送参数', this.requestParam)
            if (response.msg !== 'fail') {
              this.getList()
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '新增成功',
                type: 'success',
                duration: 2000
              })
            } else {
              var pmonth = new RegExp('pmonth')
              if (pmonth.test(response.data)) {
                this.$notify({
                  title: '',
                  message: '该类型当前日期已存在',
                  type: 'warning',
                  duration: 2000
                })
              } else {
                failproccess(response, this.$notify)
              }
            }
          })
        }
      })
    },
    form_see(row) {
      this.createTemp = Object.assign({}, row)
      this.dialogStatus = 'see'
      this.dialogFormVisible = true
    },
    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'
            })
          })
        })
      })
    },
    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 < 10
      if (!isLt2M) {
        this.$message.error('上传文件大小不能超过 10MB!')
      }
      return isLt2M
    },
    handleImportExcelSuccess(res, file) {
      this.getList()
      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
        })
      }
    },

    handleDownload() {
      console.log('点击了导出')
      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)
      this.downloadParam.name = 'getFeedsumlist'
      this.downloadParam.parammaps = this.getdataListParm.parammaps
      GetAccount(this.downloadParam).then(response => {
        if (response.data.list !== '') {
          this.percentage = 99
          setTimeout(() => {
            this.isPercentage = false
          }, 2000)
        }
        this.$nextTick(() => {
          const ExcelDatas = [
            {
              tHeader: ['牧场', '时间', '牛头数', '泌乳牛牛头数', '日销奶量（吨）'],
              filterVal: ['pastureName', 'feedDay', 'cowNum', 'cowNumM', 'saleNum'],
              tableDatas: response.data.list,
              sheetName: '饲养数'
            }
          ]
          json2excel(ExcelDatas, '饲养数', true, 'xlsx')
        })
      })
    },
    form_delete(row) {
      MessageBox.confirm('是否删除此条信息?', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.requestParam.name = 'deleteFeedsum'
          this.requestParam.parammaps = {}
          this.requestParam.parammaps['id'] = row.id
          PostDataByName(this.requestParam).then(() => {
            this.getList()
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    }
  }
}
</script>

