<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.month" type="month" style="width: 250px;top:-3px;" placeholder="选择月份" format="yyyy-MM" value-format="yyyy-MM" />
      <el-select v-model="getdataListParm.parammaps.pastureName" style="width: 140px;" placeholder="牧场" 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>
      <el-button class="filter-item" type="success" icon="el-icon-edit" @click="handleDownload">导出</el-button>
    </div>
    <!-- <h3>备件台账</h3> -->
    <el-table slot="reference" v-loading="listLoading" border :data="list" header-align="center" :row-style="rowStyle" :cell-style="cellStyle" :max-height="myHeight">
      <template v-for="(item,index) in tablelist">
        <el-table-column :key="index" show-overflow-tooltip sortable :prop="item.column_name" :label="item.label" :width="item.width" />
      </template>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="getdataListParm.offset" :limit.sync="getdataListParm.pagecount" @pagination="get_table_data" />

  </div>
</template>

<script>
// 引入
import { GetAccount, GetDataByNames } from '@/api/common'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination'
import { parseTime } from '@/utils/index.js'
import Cookies from 'js-cookie'
import { json2excel } from '@/utils/index.js'
import { MessageBox } from 'element-ui'
export default {
  name: 'StandingBook',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      // ----------------------------------------------------
      visible: false,
      disabled: false,
      findAllPasture: [],
      requestParams: [
        { name: 'findAllPasture', offset: 0, pagecount: 0, returntype: 'Map', parammaps: { 'id': Cookies.get('pastureid') }}
      ],
      rowStyle: { maxHeight: 30 + 'px', height: 25 + 'px' },
      cellStyle: { padding: 0 + 'px' },
      total: 0,
      tableKey: 0,
      listLoading: true,
      list: [],
      listTest: {},
      tablelist: [],
      getdataListParm: {
        name: 'getPartrepertryAccount',
        page: 1,
        offset: 1,
        pagecount: 10,
        returntype: 'Map',
        parammaps: {
          pastureName: Cookies.get('pasturename'),
          month: parseTime(new Date(), '{y}-{m}')
        }

      },
      dialogStatus: '',
      dialogFormVisible: false,
      isokDisable: false,
      rules: { },
      textMap: { },
      months: [],
      month: [],
      downLoadParm: {},
      downLoadList: [],
      isPercentage: false,
      percentage: 1,
      myHeight:document.documentElement.clientHeight - 85- 150
    }
  },
  computed: {

  },
  created() {
    this.get_table_data()
    this.get_select_list()
    // this.getMonths()
  },
  methods: {
    forDight(_num, _x) {
      var n = 1
      for (var i = 0; i < _x; i++) {
        n = n * 10
      }
      return Math.round(_num * n) / n
    },
    get_select_list() {
      GetDataByNames(this.requestParams).then(response => {
        this.findAllPasture = response.data.findAllPasture.list
      })
    },
    get_table_data() {
      this.listLoading = true
      // this.getdataListParm.month = parseTime(new Date(), '{y}-{m}') // 更改为请求的月份
      // this.getdataListParm.month = '2020-03' // 更改为请求的月份
      // this.getdataListParm.timeout = 80000
      GetAccount(this.getdataListParm).then(response => {
        console.log('table数据', response.data.list)
        if (response.data.list !== null) {
          this.list = response.data.list
        } else {
          this.list = []
        }
        this.pageNum = response.data.pageNum
        this.pageSize = response.data.pageSize
        if (response.data.total) {
          this.total = response.data.total
        }
        var temp = this.getdataListParm.parammaps.month.split('-')
        var year = temp[0]
        var month = temp[1]
        var d = new Date(year, month, 0)
        var table = [{ 'label': '序号', 'column_name': 'i' }, { 'label': '牧场', 'column_name': 'pastureName' }, { 'label': '月份', 'column_name': 'month' }, { 'label': '备件编号', 'column_name': 'partCode', 'width': '120' }, { 'label': '备件名称', 'column_name': 'partName' }, { 'label': '备件规格', 'column_name': 'specification' }, { 'label': '单位', 'column_name': 'unit' }, { 'label': '品牌', 'column_name': 'brandName' }, { 'label': '供应商', 'column_name': 'providerName' }, { 'label': '单价', 'column_name': 'price' }, { 'label': '期初数量', 'column_name': 'startSum' }, { 'label': '期初金额', 'column_name': 'startPrice' }]
        for (let index = 1; index <= d.getDate(); index++) {
          // eslint-disable-next-line no-undef
          index = JSON.stringify(index)
          const index1 = '入库数量' + index + '日'
          const index2 = '入库金额' + index + '日'
          const m1 = { 'label': index1, 'column_name': 'laid' + index, 'width': '80' }
          const m2 = { 'label': index2, 'column_name': 'laidPrice' + index, 'width': '80' }

          table.push(m1)
          table.push(m2)
        }
        const m3 = { 'label': '合计入库数量', 'column_name': 'Sumlaid', 'width': '120' }
        const m4 = { 'label': '合计入库金额', 'column_name': 'SumlaidPrice', 'width': '120' }
        table.push(m3)
        table.push(m4)
        console.log(d.getDate(), '----------')
        for (let index = 1; index <= d.getDate(); index++) {
          // eslint-disable-next-line no-undef
          index = JSON.stringify(index)
          const index5 = '出库数量' + index + '日'
          const index6 = '出库金额' + index + '日'
          const m5 = { 'label': index5, 'column_name': 'use' + index, 'width': '80' }
          const m6 = { 'label': index6, 'column_name': 'usePrice' + index, 'width': '80' }

          table.push(m5)
          table.push(m6)
        }
        const m7 = { 'label': '合计出库数量', 'column_name': 'Sumuse', 'width': '120' }
        const m8 = { 'label': '合计出库金额', 'column_name': 'SumusePrice', 'width': '120' }
        const m9 = { 'label': '退货数量', 'column_name': 'THsum', 'width': '120' }
        const m10 = { 'label': '退货金额', 'column_name': 'THsumPrice', 'width': '120' }
        const m11 = { 'label': '期末数量', 'column_name': 'endSum', 'width': '120' }
        const m12 = { 'label': '期末金额', 'column_name': 'endSumPrice', 'width': '120' }
        table.push(m7)
        table.push(m8)
        table.push(m9)
        table.push(m10)
        table.push(m11)
        table.push(m12)
        this.tablelist = table
        if (this.list !== null) {
          for (var i = 0; i < this.list.length; i++) {
            this.list[i].i = i + 1
            console.log(this.list[i])
            this.$set(this.list[i], 'startPrice', this.forDight((parseFloat(this.list[i].startSum) * parseFloat(this.list[i].price)), 3)) // 期初金额
            this.$set(this.list[i], 'SumlaidPrice', this.forDight((parseFloat(this.list[i].Sumlaid) * parseFloat(this.list[i].price)), 3)) // 合计入库金额
            this.$set(this.list[i], 'SumusePrice', this.forDight((parseFloat(this.list[i].Sumuse) * parseFloat(this.list[i].price)), 3)) // 合计出库金额
            this.$set(this.list[i], 'THsumPrice', this.forDight((parseFloat(this.list[i].THsum) * parseFloat(this.list[i].price)), 3)) // 退货金额
            this.$set(this.list[i], 'endSumPrice', this.forDight((parseFloat(this.list[i].endSum) * parseFloat(this.list[i].price)), 3)) // 期末金额

            for (let index = 1; index <= d.getDate(); index++) {
              index = JSON.stringify(index)
              console.log('laid' + index)
              const laid = 'laid' + index
              const use = 'use' + index
              console.log(this.list[i][laid]) // underfind

              this.$set(this.list[i], 'laidPrice' + index, this.forDight((parseFloat(this.list[i][laid]) * parseFloat(this.list[i].price)), 3)) // 入库金额
              this.$set(this.list[i], 'usePrice' + index, this.forDight((parseFloat(this.list[i][use]) * parseFloat(this.list[i].price)), 3)) // 出库金额
            }
          }
        }
        console.log('table数据', this.list)
        console.log('表头数据', this.tablelist)
        this.$forceUpdate()
        setTimeout(() => {
          this.listLoading = false
        }, 100)
      })
    },
    form_search() {
      this.listLoading = true
      this.getdataListParm.offset = 1
      this.get_table_data()
    },

    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 = 'getPartrepertryAccount'
      this.downLoadParm.returntype = 'Map'
      // this.downLoadParm.timeout = 80000
      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
          if (response.data.list !== null) {
            const temp = this.getdataListParm.parammaps.month.split('-')
            const year = temp[0]
            const month = temp[1]
            const d = new Date(year, month, 0)
            for (let i = 0; i < response.data.list.length; i++) {
              this.$set(response.data.list[i], 'startPrice', this.forDight((parseFloat(response.data.list[i].startSum) * parseFloat(response.data.list[i].price)), 3)) // 期初金额
              this.$set(response.data.list[i], 'SumlaidPrice', this.forDight((parseFloat(response.data.list[i].Sumlaid) * parseFloat(response.data.list[i].price)), 3)) // 合计入库金额
              this.$set(response.data.list[i], 'SumusePrice', this.forDight((parseFloat(response.data.list[i].Sumuse) * parseFloat(response.data.list[i].price)), 3)) // 合计出库金额
              this.$set(response.data.list[i], 'THsumPrice', this.forDight((parseFloat(response.data.list[i].THsum) * parseFloat(response.data.list[i].price)), 3)) // 退货金额
              this.$set(response.data.list[i], 'endSumPrice', this.forDight((parseFloat(response.data.list[i].endSum) * parseFloat(response.data.list[i].price)), 3)) // 期末金额
              for (let index = 1; index <= d.getDate(); index++) {
                index = JSON.stringify(index)
                console.log('laid' + index)
                const laid = 'laid' + index
                const use = 'use' + index
                console.log(response.data.list[i][laid]) // underfind

                this.$set(response.data.list[i], 'laidPrice' + index, this.forDight((parseFloat(response.data.list[i][laid]) * parseFloat(response.data.list[i].price)), 3)) // 入库金额
                this.$set(response.data.list[i], 'usePrice' + index, this.forDight((parseFloat(response.data.list[i][use]) * parseFloat(response.data.list[i].price)), 3)) // 出库金额
              }
            }
          }
          console.log(this.tablelist)
          const tHeader = []
          const filterVal = []
          for (let i = 1; i < this.tablelist.length; i++) {
            tHeader.push(this.tablelist[i].label)
            filterVal.push(this.tablelist[i].column_name)
          }
          console.log(tHeader, filterVal)
          const ExcelDatas = [
            {
              tHeader: tHeader,
              filterVal: filterVal,
              tableDatas: this.downLoadList,
              sheetName: '备件台账'
            }
          ]
          json2excel(ExcelDatas, '备件台账', true, 'xlsx')
        })
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.el-input--small .el-input__inner{
  height: 38px !important;
}
.el-table .cell.el-tooltip{
  text-align: center;
}
.el-table th>.cell{
  text-align: center;
}
.el-table .cell.el-tooltip{
  white-space:pre-wrap;
}
</style>
