<template>
  <div class="app-container" style="position: relative;">
    <div v-if="activeName=='first'" class="operation" style="position: absolute;top: -5px;right: 10px;z-index:1;">
      <el-button class="import" icon="el-icon-upload2" @click="handleExport('tab1')">导出</el-button>
    </div>
    <div v-if="activeName=='second'" class="operation" style="position: absolute;top: -5px;right: 10px;z-index:1;">
      <el-button class="import" icon="el-icon-upload2" @click="handleExport('tab2')">导出</el-button>
    </div>
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="预混记录" name="first">
        <div class="table">
          <el-table
            :key="tab1.tableKey"
            v-loading="tab1.listLoading"
            element-loading-text="给我一点时间"
            :data="tab1.list"
            border
            fit
            highlight-current-row
            style="width: 100%;"
            :row-style="rowStyle"
            :cell-style="cellStyle"
            class="elTable table-fixed"
            :max-height="myHeight"
          >
            <el-table-column label="序号" align="center" type="index" width="50px" />
            <el-table-column label="预混配方" min-width="130px" align="center" prop="pftname" />
            <el-table-column label="当前剩余量" min-width="110px" align="center">
              <template slot-scope="scope">
                <span v-if="scope.row.NoEdit">{{ scope.row.stockweight }}</span>
                <el-input v-if="scope.row.Edit" v-model="scope.row.stockweight" type="number" style="width:95%;padding:10px 0;" />
              </template>
            </el-table-column>
            <el-table-column label="预计使用天数" min-width="130px" align="center" prop="days" />
            <el-table-column label="操作" align="center" width="80" class-name="small-padding fixed-width" fixed="right">
              <template slot-scope="{row}">
                <a v-if="row.isUpdate && isRoleEdit" class="correcting" @click="handleUpdate(row)">校正</a>
                <el-button v-if="row.isUpdateSave && isRoleEdit" :disabled="isokDisable" class="miniSuccess" icon="el-icon-folder-checked" @click="updateData(row)" />
                <span v-if="row.isUpdateSave && isRoleEdit" class="centerSpan">|</span>
                <el-button v-if="row.isUpdateSave && isRoleEdit" class="minCancel" icon="el-icon-close" @click="updateCancel(row)" />
              </template>
            </el-table-column>
          </el-table>
          <span v-if="tab1.listLoading == false" style="margin-right: 30px;margin-top: 10px;font-size: 14px;">共{{ tab1.total }}条</span>
        </div>
      </el-tab-pane>
      <el-tab-pane label="库存预警" name="second">
        <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%;"
            :cell-style="cellStyle"
            class="elTable table-fixed"
            :row-style="rowStyle"
          >
            <el-table-column label="序号" align="center" type="index" width="50px" />
            <el-table-column label="饲料名称" min-width="130px" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.feedname }}</span>
              </template>
            </el-table-column>
            <el-table-column label="库存量（kg）" min-width="130px" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.stockweight }}</span>
              </template>
            </el-table-column>
            <el-table-column label="近七天平均计划量（kg）" min-width="110px" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.avgweight }}</span>
              </template>
            </el-table-column>
            <el-table-column label="剩余使用天数" min-width="110px" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.ldays }}</span>
              </template>
            </el-table-column>
            <el-table-column label="最近预警日期" min-width="110px" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.lastdate }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="50" class-name="small-padding fixed-width" fixed="right">
              <template slot-scope="{row}">
                <el-button class="miniSuccess" :disabled="isokDisable" icon="el-icon-search" @click="form_see(row)" />
              </template>
            </el-table-column>
          </el-table>
          <span v-if="table.listLoading == false" style="margin-right: 30px;margin-top: 10px;font-size: 14px;">共{{ table.total }}条</span>
        </div>
      </el-tab-pane>
    </el-tabs>

    <el-dialog :fullscreen="dialogFull" :visible.sync="see.dialogFormVisible" :close-on-click-modal="false" width="90%">
      <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[see.dialogStatus] }}
          </span>
          <div class="avue-crud__dialog__menu" @click="dialogFull? dialogFull=false: dialogFull=true">
            <svg-icon v-if="dialogFull" icon-class="exit-fullscreen" />
            <svg-icon v-else icon-class="fullscreen" />
          </div>
        </div>
      </template>
      <div class="app-see">
        <el-form ref="temp" :rules="see.rules" :model="see.temp" label-position="right" label-width="110px" style="width: 100%;margin:0 auto">
          <el-row>
            <el-col :span="8">
              <el-form-item label="饲料名称:" prop="feedname">
                <span> {{ see.temp.feedname }}</span>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <el-table
          :key="see.tableKey"
          v-loading="see.listLoading"
          element-loading-text="给我一点时间"
          :data="see.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>{{ scope.$index + (see.pageNum-1) * see.pageSize + 1 }}</span>
            </template>
          </el-table-column>
          <el-table-column label="库存量" min-width="130px" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.stockweight }}</span>
            </template>
          </el-table-column>
          <el-table-column label="近七天平均计划量（kg）" min-width="130px" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.avgweight }}</span>
            </template>
          </el-table-column>
          <el-table-column label="剩余使用天数" min-width="110px" align="center">
            <template slot-scope="scope">
              <span> {{ scope.row.ldays }}</span>
            </template>
          </el-table-column>
          <el-table-column label="预警日期" min-width="110px" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.date }}</span>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="see.total>=0" style="margin-bottom: 50px;" :total="see.total" :page.sync="see.getdataListParm.offset" :limit.sync="see.getdataListParm.pagecount" @pagination="getSeeList" />
        <div slot="footer" class="dialog-footer">
          <el-button class="cancelClose cancelClose1" @click="see.dialogFormVisible = false; ">关闭</el-button>
        </div>
      </div>
    </el-dialog>
  </div>

</template>

<script>
import { GetDataByName, PostDataByName, failproccess, checkButtons } from '@/api/common'
import Pagination from '@/components/Pagination'
import Cookies from 'js-cookie'
import { json2excel } from '@/utils/index.js'
export default {
  name: 'Warning',
  components: { Pagination },
  data() {
    return {
      dialogFull: false,
      isRoleEdit: [],
      activeName: 'first',
      tab1: {
        getdataListParm: {
          name: 'getPreMixStorageLsit',
          page: 1,
          offset: 1,
          pagecount: '',
          returntype: 'Map',
          parammaps: {
            pastureid: Cookies.get('pastureid')
          }
        },
        tableKey: 0,
        list: [],
        total: 0,
        listLoading: true
      },
      table: {
        getdataListParm: {
          name: 'getFsWarnList',
          page: 1,
          offset: 1,
          pagecount: '',
          returntype: 'Map',
          parammaps: {
            pastureid: Cookies.get('pastureid')
          }
        },
        tableKey: 0,
        list: [],
        total: 0,
        listLoading: true
      },
      textMap: {
        see: '库存预警记录'
      },
      see: {
        dialogFormVisible: false,
        dialogStatus: '',
        temp: {},
        rules: {},
        getdataListParm: {
          name: 'getFsWarnListdate',
          page: 1,
          offset: 1,
          pagecount: 10,
          returntype: 'Map',
          parammaps: {
            pastureid: Cookies.get('pastureid'),
            feedid: ''
          }
        },
        tableKey: 0,
        list: [],
        total: 0,
        listLoading: true
      },
      download: {
        getdataListParm: {
          name: '',
          page: 1,
          offset: 1,
          pagecount: 0,
          returntype: 'Map',
          parammaps: {
            pastureid: Cookies.get('pastureid')
          }
        },
        list: []
      },
      requestParam: {},
      isokDisable: false,
      rowStyle: { maxHeight: 30 + 'px', height: 30 + 'px' },
      cellStyle: { padding: 0 + 'px' },
      myHeight:document.documentElement.clientHeight - 85- 110
    }
  },

  created() {
    this.getButtons()
    if (this.$route.params.jmp == undefined) {
      this.getTab1List()
    } else {
      this.activeName = 'second'
      this.getTab2List()
    }
  },

  methods: {
    getButtons() {
      const Edit = 'Warning'
      const isRoleEdit = checkButtons(JSON.parse(sessionStorage.getItem('buttons')), Edit)
      this.isRoleEdit = isRoleEdit
    },
    handleClick(item) {
      console.log(item)
      if (item.name == 'first') {
        this.getTab1List()
      } else {
        this.getTab2List()
      }
    },
    getTab1List() {
      this.tab1.listLoading = true
      GetDataByName(this.tab1.getdataListParm).then(response => {
        if (response.data.list !== null) {
          console.log('table数据111', response.data.list)
          for (let i = 0; i < response.data.list.length; i++) {
            this.$set(response.data.list[i], 'Edit', false) // 编辑
            this.$set(response.data.list[i], 'NoEdit', true) // 不可编辑/输入
            this.$set(response.data.list[i], 'isCreate', false) // 新增操作
            this.$set(response.data.list[i], 'isUpdate', true) // 编辑操作
            this.$set(response.data.list[i], 'isUpdateSave', false) // 编辑保存
          }
          this.tab1.list = response.data.list
          this.tab1.pageNum = response.data.pageNum
          this.tab1.pageSize = response.data.pageSize
          this.tab1.total = response.data.total
        } else {
          this.tab1.list = []
        }
        setTimeout(() => {
          this.tab1.listLoading = false
        }, 100)
      })
    },
    handleUpdate(row) {
      for (let i = 0; i < this.table.list.length; i++) {
        if (this.table.list[i].Edit == true) {
          this.$message({ type: 'error', message: '当前内容未保存，请点击取消或保存继续进行操作', duration: 2000 })
          return false
        }
      }
      // 编辑true,不可编辑false
      row.Edit = true
      row.NoEdit = false
      // 新增false,编辑false,编辑保存true
      row.isCreate = false
      row.isUpdate = false
      row.isUpdateSave = true
    },
    updateData(row) {
      this.isokDisable = true
      setTimeout(() => {
        this.isokDisable = false
      }, 1000)
      if (row.stockweight == '') {
        this.$message({ type: 'error', message: '当前配方剩余重量不能为空', duration: 2000 })
        return false
      }
      const keepTwoNum = /^\d+(\.\d{1,2})?$/
      // 当前配方剩余重量
      if (!keepTwoNum.test(parseFloat(row.stockweight))) {
        this.$message({ type: 'error', message: '当前配方剩余重量请输入自然数并保留两位小数', duration: 2000 })
        return false
      }
      this.requestParam.name = 'updatePreMixStorage'
      this.requestParam.parammaps = {}
      this.requestParam.parammaps.pastureid = row.pastureid
      this.requestParam.parammaps.id = row.id
      this.requestParam.parammaps.stockweight = row.stockweight
      PostDataByName(this.requestParam).then(response => {
        console.log('编辑保存发送参数', this.requestParam)
        if (response.msg !== 'fail') {
          this.$notify({ title: '成功', message: '保存成功', type: 'success', duration: 2000 })
          this.getTab1List()
        } else {
          this.$notify({ title: '保存失败', message: response.data, type: 'warning', duration: 2000 })
        }
      })
    },
    updateCancel(row) {
      console.log('点击了编辑取消')
      // 编辑false,不可编辑true
      row.Edit = false
      row.NoEdit = true
      // 新增false,编辑true,编辑保存false
      row.isCreate = false
      row.isUpdate = true
      row.isUpdateSave = false
      this.getTab1List()
    },
    getTab2List() {
      this.table.listLoading = true
      GetDataByName(this.table.getdataListParm).then(response => {
        if (response.data.list !== null) {
          console.log('table数据22', response.data.list)
          this.table.list = response.data.list
          // this.table.pageNum = response.data.pageNum
          // this.table.pageSize = response.data.pageSize
        } else {
          this.table.list = []
        }
        this.table.total = response.data.total
        setTimeout(() => {
          this.table.listLoading = false
        }, 100)
      })
    },
    form_see(row) {
      this.see.dialogStatus = 'see'
      this.dialogFull = false
      this.see.dialogFormVisible = true
      this.see.temp = Object.assign({}, row)
      this.see.list = []
      this.see.getdataListParm.offset = 1
      this.see.getdataListParm.parammaps.feedid = row.feedid
      this.getSeeList()
    },
    getSeeList() {
      this.see.listLoading = true
      GetDataByName(this.see.getdataListParm).then(response => {
        if (response.data.list !== null) {
          console.log('table数据', response.data.list)
          this.see.list = response.data.list
          this.see.pageNum = response.data.pageNum
          this.see.pageSize = response.data.pageSize
          this.see.total = response.data.total
        } else {
          this.see.list = []
        }
        setTimeout(() => {
          this.see.listLoading = false
        }, 100)
      })
    },
    handleExport(item) {
      console.log('导出')
      if (item == 'tab1') {
        var excelDatas = [
          {
            tHeader: ['预混配方', '当前剩余量', '预计使用天数'],
            filterVal: ['pftname', 'stockweight', 'days'],
            tableDatas: this.tab1.list,
            sheetName: 'Sheet1'
          }
        ]
        json2excel(excelDatas, '预混记录', true, 'xlsx')
      } else {
        this.download.getdataListParm.name = 'getFsWarnList'
        GetDataByName(this.download.getdataListParm).then(response => {
          if (response.data.list !== null) {
            this.download.list = response.data.list
          } else {
            this.download.list = []
          }
          var excelDatas = [
            {
              tHeader: ['饲料名称', '库存量（kg）', '近七天平均计划量（kg）', '剩余使用天数', '最新预警日期'],
              filterVal: ['feedname', 'stockweight', 'avgweight', 'ldays', 'lastdate'],
              tableDatas: this.download.list,
              sheetName: 'Sheet1'
            }
          ]
          json2excel(excelDatas, '库存预警', true, 'xlsx')
        })
      }
    }

  }
}
</script>
