<template>
  <div class="app-container">
    <div class="table1">
      <div class="search">
        <el-select v-model="table1.parammaps.pastureid" filterable placeholder="全部牧场" class="filter-item" style="width: 150px;" clearable>
          <el-option v-for="item in table1.pastureList" :key="item.pastureid" :label="item.pasturename" :value="item.pastureid" />
        </el-select>
        <el-date-picker v-model="table1.parammaps.inputDatetime" type="daterange"  class="filter-item" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" />
        <el-select v-model="table1.parammaps.genre" filterable placeholder="类型" class="filter-item" style="float: left;width: 150px;" clearable>
          <el-option v-for="item in table1.typeList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
        <el-button class="successBorder" @click="handleSearch1">查询</el-button>
        <el-button class="successBorder" @click="handleRefresh1">重置</el-button>
        <el-button class="filter-item import" style="display:inline-block;" icon="el-icon-download" @click="handleImport">导入</el-button>
        <el-button class="filter-item export" icon="el-icon-upload2" @click="handleDownload()" style="display:inline-block;">导出</el-button>
        <el-button class="filter-item export" icon="el-icon-upload2" @click="handleDownloadTemp()" style="display:inline-block;">导入模板下载</el-button>
      </div>
      <div class="table">
        <el-table
          :key="table1.tableKey"
          v-loading="table1.listLoading"
          element-loading-text="给我一点时间"
          :data="table1.list"
          border
          fit
          highlight-current-row
          style="width: 100%;"
          :row-style="rowStyle"
          :cell-style="cellStyle"
          class="elTable table-fixed"
        >
          <el-table-column label="序号" align="center" type="index" width="50px">
            <template slot-scope="scope">
              <span v-if="table1.pageNum">{{ scope.$index + (table1.pageNum-1) * table1.pageSize + 1 }}</span>
              <span v-else>1</span>
            </template>
          </el-table-column>
          <el-table-column label="牧场名称" min-width="60px" align="center" prop="pasturename" />
          <el-table-column label="数量" min-width="60px" align="center" prop="count">
            <template slot-scope="{row}">
              <a @click="clickQuantity(row)" style="text-decoration: underline;color: #0000FF;">{{row.count}}</a>
            </template>
          </el-table-column>
          <el-table-column label="类型" min-width="60px" align="center">
            <template slot-scope="{row}">
              <span v-if="row.genre == 0">售卖</span>
              <span v-else-if="row.genre == 1">返厂</span>
              <span v-else>置换</span>
            </template>
          </el-table-column>
          <el-table-column label="导入时间" min-width="60px" align="center" prop="importdate" />
        </el-table>
        <pagination v-show="table1.total>0" :total="table1.total" :page.sync="table1.offset" :limit.sync="table1.pagecount" @pagination="getList1" />
      </div>
    </div>
    <el-dialog  :title="textMap[importPasture.dialogStatus]"  :visible.sync="importPasture.dialogFormVisible" :close-on-click-modal="false" width="50%">
      <div class="import1" style="height: 300px;">
        <el-form ref="temp" :model="importPasture.temp" label-position="right" label-width="150px" style="width: 100%;margin:0 auto 50px">
          <el-row>
            <el-col :span="16">
              <el-form-item label="牧场:" prop="pastureid">
                <el-select v-model="importPasture.temp.pastureid" filterable placeholder="牧场名称" class="filter-item" style="width: 100%;" @change="changePasture">
                  <el-option v-for="item in table1.pastureList" :key="item.pastureid" :label="item.pasturename" :value="item.pastureid" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div style="display: flex;justify-content: center;margin-top: 20px;height: 100px;" >
          <el-upload v-if="importPasture.temp.pastureid !== ''" :headers="headers" :data="uploadData" :action="uploadExcelUrl" :show-file-list="false" :before-upload="beforeImport" :on-success="handleImportSuccess">
            <el-button class="save" :disabled="importPasture.temp.pastureid==''">选择导入文件</el-button>
          </el-upload>
          <el-button class="save" v-else @click="clickImpotFile()">选择导入文件</el-button>
        </div>
      </div>
      <div slot="footer" class="dialog-footer" style="bottom: 10px;">
        <el-button class="cancelClose1" @click="importPasture.dialogFormVisible = false;">关闭</el-button>
      </div>
    </el-dialog>
    <!-- 数量 -->
    <el-dialog  :visible.sync="quantity.dialogFormVisible" :close-on-click-modal="false" width="50%">
      <template slot="title">
        <div class="avue-crud__dialog__header">
          <span class="el-dialog__title">
            <span style="display:inline-block;width:3px;height:20px;margin-right:5px; float: left;margin-top:2px" />
            {{ textMap[quantity.dialogStatus] }}
          </span>
          <span style="margin-right: 100px;">导入时间:{{quantity.temp.importdate}}</span>
        </div>
      </template>
      <div class="quantity">
        <el-table
          :key="quantity.table1.tableKey"
          v-loading="quantity.table1.listLoading"
          element-loading-text="给我一点时间"
          :data="quantity.table1.list"
          border
          fit
          highlight-current-row
          style="width: 100%;"
          :row-style="rowStyle"
          :cell-style="cellStyle"
          class="elTable table-fixed"
        >
          <el-table-column label="序号" align="center" type="index" width="50px">
            <template slot-scope="scope">
              <span v-if="quantity.table1.pageNum">{{ scope.$index + (quantity.table1.pageNum-1) * quantity.table1.pageSize + 1 }}</span>
              <span v-else>1</span>
            </template>
          </el-table-column>
          <el-table-column label="脖环号" min-width="60px" align="center" prop="code" />
          <el-table-column label="日期" min-width="60px" align="center" prop="date" />
        </el-table>
        <pagination v-show="table1.total>0" :total="table1.total" :page.sync="table1.offset" :limit.sync="table1.pagecount" @pagination="getList1" />
      </div>
      <div slot="footer" class="dialog-footer" style="bottom: 10px;">
        <el-button class="cancelClose1" @click="quantity.dialogFormVisible = false; ">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import Pagination from '@/components/Pagination'
  import { postJson,getJson } from '@/api/common'
  import { parseTime,json2excel } from '@/utils/index.js'
  import Cookies from 'js-cookie'
  import axios from 'axios'
  import { getToken } from '@/utils/auth'
  import xlsx from 'xlsx'
  import { upload } from '@/utils/index.js'
  export default {
    name: 'NeckRing',
    components: { Pagination },
    data() {
      return {
        table1:{
          pastureList:[],
          typeList:[{id:0,name:'售卖'},{id:1,name:'返厂'},{id:2,name:'置换'}],
          page: 1, offset: 1, pagecount: parseInt(Cookies.get('pageCount')),
          parammaps: { pastureid: '', genre:'',inputDatetime:'' },
          tableKey: 0, list: [], total: 0, listLoading: true
        },
        // 数量
        quantity:{
          dialogStatus: '',
          dialogFormVisible: false,
          rules:{},
          temp:{},
          table1:{
            page: 1, offset: 1, pagecount: parseInt(Cookies.get('pageCount')),
            parammaps: { pastureid: '', date:'' },
            tableKey: 0, list: [], total: 0, listLoading: true
          }
        },
        importPasture:{
          dialogStatus: '',
          dialogFormVisible: false,
          temp:{
            pastureid:''
          }
        },
        isokDisable:false,
        textMap: {
          quantityTxt: '数量',
          importTxt:'选择牧场'
        },
        rowStyle: { maxHeight: 30 + 'px', height: 30 + 'px' },
        cellStyle: { padding: 0 + 'px' }
      }
    },
    computed: {
      // 设置请求头
      headers() {
        return {
          token: getToken()
        }
      },
      uploadData() {
        return {}
      },
      // 设置上传地址
      uploadExcelUrl() {
        return process.env.VUE_APP_BASE_API + 'management/add'
      }
    },
    created() {
      this.getList1()
      this.getPastureList()
    },
    methods: {
      getPastureList(){
        let data = 'index=' + 1
        + '&pagesize=' + ''
        let url = 'public/pasture?'
        getJson(url,data).then(response => {
          if (response.code == 200) {
            this.table1.pastureList = response.data.list
          } else {
            this.table1.pastureList = []
          }
        })
      },
      getList1() {
        this.table1.listLoading = true
        let genre = ''
        if(this.table1.parammaps.genre == '' || this.table1.parammaps.genre == null){
          genre = -1
        }else{
          genre = this.table1.parammaps.genre
        }
        let startdate = ''
        let enddate = ''
        if(this.table1.parammaps.inputDatetime !== '' && this.table1.parammaps.inputDatetime !== null){
          startdate = parseTime(this.table1.parammaps.inputDatetime[0],'{y}-{m}-{d}')
          enddate = parseTime(this.table1.parammaps.inputDatetime[1],'{y}-{m}-{d}')
        }else{
          startdate = ''
          enddate = ''
        }
        let data = 'index=' + this.table1.offset
        + '&pagesize=' + this.table1.pagecount
        + '&genre=' + genre
        + '&pastureid=' + this.table1.parammaps.pastureid
        + '&startdate=' + startdate
        + '&enddate=' + enddate

        let url = 'management/list?'
        getJson(url,data).then(response => {
          if (response.code == 200) {
            this.table1.list = response.data.list
            this.table1.pageNum = this.table1.offset
            this.table1.pageSize = this.table1.pagecount
          } else {
            this.table1.list = []
          }
          this.table1.total = response.data.total
          setTimeout(() => {
            this.table1.listLoading = false
          }, 100)
        })
      },
      handleSearch1(){
        this.table1.offset = 1
        this.getList1()
      },
      handleRefresh1(){
        this.table1.offset = 1
        this.table1.parammaps.pastureid = ''
        this.table1.parammaps.inputDatetime = ''
        this.table1.parammaps.genre = ''
        this.getList1()
      },
      clickQuantity(row){
        console.log('数量')
        this.quantity.temp = Object.assign({}, row)
        this.quantity.dialogFormVisible = true
        this.quantity.dialogStatus = 'quantityTxt'
        this.getQuantityList1()
      },
      getQuantityList1() {
        this.quantity.table1.listLoading = true
        let data = 'index=' + this.quantity.table1.offset
        + '&pagesize=' + this.quantity.table1.pagecount
        + '&managementid=' + this.quantity.temp.id
        let url = 'managementbh/list?'
        getJson(url,data).then(response => {
          if (response.code == 200) {
            this.quantity.table1.list = response.data.list
            this.quantity.table1.pageNum = this.quantity.table1.offset
            this.quantity.table1.pageSize = this.quantity.table1.pagecount
          } else {
            this.quantity.table1.list = []
          }
          this.quantity.table1.total = response.data.total
          setTimeout(() => {
            this.quantity.table1.listLoading = false
          }, 100)
        })
      },
      clickhandleData(){
         console.log('处理确认')
      },
      handleDownload(){
        console.log('导出')
        let genre = ''
        if(this.table1.parammaps.genre == '' || this.table1.parammaps.genre == null){
          genre = -1
        }else{
          genre = this.table1.parammaps.genre
        }
        let startdate = ''
        let enddate = ''
        if(this.table1.parammaps.inputDatetime !== '' && this.table1.parammaps.inputDatetime !== null){
          startdate = parseTime(this.table1.parammaps.inputDatetime[0],'{y}-{m}-{d}')
          enddate = parseTime(this.table1.parammaps.inputDatetime[1],'{y}-{m}-{d}')
        }else{
          startdate = ''
          enddate = ''
        }
        let data = 'index=' + 1
        + '&pagesize=' + ''
        + '&genre=' + genre
        + '&pastureid=' + this.table1.parammaps.pastureid
        + '&startdate=' + startdate
        + '&enddate=' + enddate

        let url = 'management/list?'
        var downList = []
        getJson(url,data).then(response => {
          if (response.code == 200) {
            response.data.list.forEach((ele)=> {
              if(ele.genre == 0){
                ele.genre = '售卖'
              }else if(ele.genre == 1){
                ele.genre = '返厂'
              }else{
                ele.genre = '置换'
              }
            });
            downList = response.data.list
          } else {
            downList = []
          }
          var excelDatas = [{
            tHeader: ['牧场名称','数量','类型','导入时间'],
            filterVal: ['pasturename','count','genre','importdate'],
            tableDatas: downList,
            sheetName: 'sheet'
          }]
          json2excel(excelDatas, '脖环管理', true, 'xlsx')
        })
      },
      handleDownloadTemp(){
        const requestParam = {}
        const url = process.env.VUE_APP_BASE_API + 'download?filename=脖环管理.xlsx' // 请求下载文件的地址
        console.log(url)
        axios({
          method: 'GET',
          url: url,
          data: requestParam,
          headers: { token: getToken(), optname: 'insertcustomdoc' },
          responseType: 'blob'
        }).then(res => {
          if (!res) return
          this.percentage = 99
          setTimeout(() => {
            this.isPercentage = false
          }, 2000)
          const blob = new Blob([res.data], {
            type: 'application/octet-stream;charset=utf-8'
          })
          const url = window.URL.createObjectURL(blob)
          const aLink = document.createElement('a')
          aLink.style.display = 'none'
          aLink.href = url
          const docname = '脖环管理导入模板下载.xlsx'
          aLink.setAttribute('download', docname) // 下载的文件
          document.body.appendChild(aLink)
          aLink.click()
          document.body.removeChild(aLink)
          window.URL.revokeObjectURL(url)
        })
      },
      handleImport(){
        this.importPasture.dialogFormVisible = true
        this.importPasture.dialogStatus = 'importTxt'
        this.importPasture.temp.pastureid = ''
      },
      clickImpotFile(){
        this.$message.warning('请选择牧场')
      },
      changePasture(item){
        this.uploadData.pastureid = item
      },
      beforeImport(file) {
        const isLt2M = file.size / 1024 / 1024 < 2
        if (!isLt2M) {
          this.$message.error('上传文件大小不能超过 2MB!')
        }
        return isLt2M
      },
      handleImportSuccess(res, file) {
        if (res.msg === 'ok') {
          this.$message({ title: '成功', message: '导入成功', type: 'success', duration: 2000 })
          this.importPasture.dialogFormVisible = false
          this.getList1()
        } else {
          this.$notify({ title: '失败', message: '上传失败', type: 'danger', duration: 2000 })
        }
      },

      formatJson(filterVal, jsonData) {
        return jsonData.map(v =>
          filterVal.map(j => {
            if (j === 'timestamp') {
              return parseTime(v[j])
            } else {
              return v[j]
            }
          })
        )
      }
    }
  }
</script>

<style>
</style>
