<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-date-picker v-model="getdataListParm.parammaps.praseTime" :clearable="false" type="date" style="width: 250px;top:-3px;" placeholder="选择日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd" />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="form_search">搜索</el-button>
      <el-button class="filter-item" style="position:absolute;right:10px" type="success" icon="el-icon-edit" @click="handleDownload">导出</el-button>
      <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="tableCellStyle"
        class="elTable table-fixed"
      >
        <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="牧场" align="center" min-width="150px">
          <template slot-scope="scope">
            <span>{{ scope.row.pastureName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="总数" min-width="130px" align="center">
          <template slot-scope="{row}">
            <a @click="clickTotal(row)">{{ row.PRSum }}</a>
          </template>
        </el-table-column>
        <el-table-column label="安全数" min-width="130px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.PRAQ }}</span><br>
          </template>
        </el-table-column>
        <el-table-column label="高于最高库存" align="center" min-width="150px">
          <template slot-scope="scope">
            <span>{{ scope.row.PRMAX }}</span>
          </template>
        </el-table-column>
        <el-table-column label="低于最低库存" min-width="130px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.PRMIN }}</span><br>
          </template>
        </el-table-column>
        <el-table-column label="安全性" min-width="130px" align="center">
          <template slot-scope="scope">
            <span>{{ (scope.row.PRAQ / scope.row.PRSum)*100 | keepTwoNum }}%</span><br>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total>0" :total="total" :page.sync="getdataListParm.offset" :limit.sync="getdataListParm.pagecount" @pagination="getList" />
    </div>
  </div>
</template>
<script>
// 引入
import { GetDataByName, GetDataByNames, GetAccount } from '@/api/common'
import Pagination from '@/components/Pagination'
import { parseTime } from '@/utils/index.js'
import waves from '@/directive/waves' // waves directive
import Cookies from 'js-cookie'
import { json2excel } from '@/utils/index.js'
export default {
  name: 'SparePartsSafety',
  components: { Pagination },
  directives: { waves },
  filters: {
    keepTwoNum(value) {
      value = Number(value)
      return value.toFixed(2)
    }
  },
  data() {
    return {
      rowStyle: { maxHeight: 50 + 'px', height: 45 + 'px' },
      cellStyle: { padding: 0 + 'px' },
      rules: {},
      findAllPasture: [],
      requestParams: [
        { name: 'findAllPasture', offset: 0, pagecount: 0, returntype: 'Map', parammaps: { 'id': Cookies.get('pastureid') }}
      ],
      getdataListParm: {
        name: 'getprsafetyList',
        page: 1,
        offset: 1,
        pagecount: 10,
        returntype: 'Map',
        parammaps: {
          praseTime: parseTime(new Date().getTime() - 24 * 60 * 60 * 1000, '{y}-{m}-{d}')
        }
      },
      listLoading: false,
      total: 0,
      tableKey: 0,
      list: [],
      downLoadParm: {},
      downLoadList: [],
      isPercentage: false,
      percentage: 1
    }
  },
  created() {
    this.get_select_list()
    this.getList()
  },
  methods: {
    get_select_list() {
      GetDataByNames(this.requestParams).then(response => {
        this.findAllPasture = response.data.findAllPasture.list
      })
    },
    getList() {
      this.listLoading = true
      GetDataByName(this.getdataListParm).then(response => {
        console.log('table数据', response.data.list)
        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() {
      console.log('点击了table搜索')
      this.getdataListParm.offset = 1
      this.getList()
    },
    handleDownload() {
      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.downLoadParm.name = 'getprsafetyList'
      this.downLoadParm.returntype = 'Map'
      this.downLoadParm.parammaps = this.getdataListParm.parammaps
      GetAccount(this.downLoadParm).then(response => {
        if (response.data.list !== '') {
          this.percentage = 99
          setTimeout(() => {
            this.isPercentage = false
          }, 2000)
        }
        this.$nextTick(() => {
          this.downLoadList = response.data.list
          this.downLoadList = response.data.list
          console.log(this.downLoadList)
          if (response.data.list.length > 0) {
            for (var i = 0; i < response.data.list.length; i++) {
              this.downLoadList[i].AQX = ((parseFloat(response.data.list[i].PRAQ) / parseFloat(response.data.list[i].PRSum)) * 100).toFixed(2) + '%'
            }
          }
          console.log(this.downLoadList)
          const ExcelDatas = [
            {
              tHeader: ['牧场', '总数', '安全数', '高于最高库存', '低于最低库存', '安全性'],
              filterVal: ['pastureName', 'PRSum', 'PRAQ', 'PRMAX', 'PRMIN', 'AQX'],
              tableDatas: this.downLoadList,
              sheetName: '备件安全库存'
            }
          ]
          json2excel(ExcelDatas, '备件安全库存', true, 'xlsx')
        })
      })
    },
    tableCellStyle({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 2) {
        return {
          textDecoration: 'underline'
        }
      }
      return {
        textDecoration: 'none'
      }
    },
    clickTotal(row) {
      console.log('跳转了')
      if (Cookies.get('pasturename') !== '现代牧业') {
        if (row.pastureName == Cookies.get('pasturename')) {
          this.$router.push({ path: '/customs/custom', query: { pastureName: row.pastureName }})
          this.getdataListParm.parammaps.pastureName = row.pastureName
        } else {
          this.$message({ type: 'error', message: '请联系管理员开通相关牧场数据权限' })
        }
      } else {
        this.$router.push({ path: '/customs/custom', query: { pastureName: row.pastureName }})
        this.getdataListParm.parammaps.pastureName = row.pastureName
      }
    }
  }
}
</script>
