<template>
  <a-card size="small" :bordered="false" class="intelligentReplenishmentList-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <!-- 操作按钮 -->
      <div ref="tableSearch" class="table-operator">
        <a-button v-if="$hasPermissions('B_intelligentReplenishment_add')" id="intelligentReplenishmentList-add" type="primary" class="button-error" @click="handleEdit()">新增</a-button>
        <a-button v-if="$hasPermissions('B_intelligentReplenishment_set')" id="intelligentReplenishmentList-set" type="primary" class="button-warning" @click="handleSet">基础信息设置</a-button>
      </div>
      <a-alert type="info" style="margin-bottom:10px">
        <div slot="message">为保证系统性能，仅保留最近10次的预测结果</div>
      </a-alert>
      <!-- 列表 -->
      <s-table
        class="sTable fixPagination"
        ref="table"
        :style="{ height: tableHeight+84.5+'px' }"
        size="small"
        :rowKey="(record) => record.id"
        :columns="columns"
        :data="loadData"
        :scroll="{ y: tableHeight }"
        :showPagination="false"
        :defaultLoadData="false"
        bordered>
        <!-- 操作 -->
        <template slot="action" slot-scope="text, record">
          <a-button
            size="small"
            type="link"
            class="button-info"
            v-if="record.state == 'WAIT' && $hasPermissions('B_intelligentReplenishment_edit')"
            @click="handleEdit(record)"
            id="intelligentReplenishmentList-edit-btn">编辑</a-button>
          <a-button
            size="small"
            type="link"
            class="button-error"
            v-if="record.state == 'WAIT' && $hasPermissions('B_intelligentReplenishment_del')"
            @click="handleDel(record)"
            id="intelligentReplenishmentList-del-btn">删除</a-button>
          <a-button
            size="small"
            type="link"
            class="button-success"
            v-if="record.state != 'WAIT' && $hasPermissions('B_intelligentReplenishment_detail')"
            @click="handleDetail(record)"
            id="customerManagementList-detail-btn">详情</a-button>
          <a-button
            size="small"
            type="link"
            class="button-warning"
            v-if="record.state == 'FINISH' && $hasPermissions('B_intelligentReplenishment_down')"
            @click="handleDownload(record)"
            id="chainTransferInList-download-btn">结果下载</a-button>
          <span v-if="!(record.state == 'WAIT' && $hasPermissions('B_intelligentReplenishment_edit'))&&!(record.state == 'WAIT' && $hasPermissions('B_intelligentReplenishment_del'))&&!(record.state != 'WAIT' && $hasPermissions('B_intelligentReplenishment_detail'))&&!(record.state == 'FINISH' && $hasPermissions('B_intelligentReplenishment_down'))">--</span>
        </template>
      </s-table>
    </a-spin>
    <!-- 详情 -->
    <intelligent-replenishment-detail-modal v-drag :openModal="openDetailModal" :itemSn="itemSn" @close="closeModal" />
  </a-card>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import moment from 'moment'
import { STable, VSelect } from '@/components'
import intelligentReplenishmentDetailModal from './detailModal.vue'
import { predictList, predictSave, predictDel, predictstockPredictExport } from '@/api/predict'
export default {
  name: 'IntelligentReplenishmentList',
  mixins: [commonMixin],
  components: { STable, VSelect, intelligentReplenishmentDetailModal },
  data () {
    return {
      spinning: false,
      tableHeight: 0,
      columns: [
        { title: '序号', dataIndex: 'no', width: '5%', align: 'center' },
        { title: '创建时间', dataIndex: 'createDate', width: '15%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '创建人', dataIndex: 'creatorName', width: '45%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '状态', dataIndex: 'stateDictValue', width: '15%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '20%', align: 'center' }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.spinning = true
        return predictList({}).then(res => {
          let data
          if (res.status == 200) {
            data = res.data
            for (var i = 0; i < data.length; i++) {
              data[i].no = i + 1
            }
          }
          this.spinning = false
          return data
        })
      },
      itemSn: '', //  当前sn
      openDetailModal: false
    }
  },
  methods: {
    //  新增/编辑
    handleEdit (row) {
      if (row) { //  编辑
        this.$router.push({ path: `/inventoryManagement/intelligentReplenishment/edit/${row.stockPredictSn}` })
      } else { //  新增
        this.spinning = true
        predictSave({}).then(res => {
          this.spinning = false
          if (res.status == 200) {
            this.$router.push({ path: `/inventoryManagement/intelligentReplenishment/add/${res.data.stockPredictSn}` })
          }
        })
      }
    },
    //  详情
    handleDetail (row) {
      this.itemSn = row ? row.stockPredictSn : null
      this.openDetailModal = true
    },
    // 设置
    handleSet () {
      this.$router.push({ path: `/inventoryManagement/intelligentReplenishment/set` })
    },
    // 删除
    handleDel (row) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '删除后不可恢复，确定要进行删除吗？',
        centered: true,
        onOk () {
          _this.spinning = true
          predictDel({ sn: row.stockPredictSn }).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.$refs.table.refresh()
              _this.spinning = false
            } else {
              _this.spinning = false
            }
          })
        }
      })
    },
    //  关闭弹框
    closeModal () {
      this.itemSn = ''
      this.openDetailModal = false
      this.$refs.table.refresh(true)
    },
    //  结果下载
    handleDownload (row) {
      const _this = this
      _this.spinning = true
      predictstockPredictExport({ sn: row.stockPredictSn }).then(res => {
        _this.spinning = false
        if (res.type == 'application/json') {
          var reader = new FileReader()
          reader.addEventListener('loadend', function () {
            const obj = JSON.parse(reader.result)
            _this.$notification.error({
              message: '提示',
              description: obj.message
            })
          })
          reader.readAsText(res)
        } else {
          this.download(res)
        }
      })
    },
    download (data) {
      if (!data) { return }
      const url = window.URL.createObjectURL(new Blob([data]))
      const link = document.createElement('a')
      link.style.display = 'none'
      link.href = url
      const a = moment().format('YYYYMMDDHHmmss')
      const fname = '智能补货' + a
      link.setAttribute('download', fname + '.xlsx')
      document.body.appendChild(link)
      link.click()
    },
    pageInit () {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    },
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 233
    }
  },
  watch: {
    '$store.state.app.winHeight' (newValue, oldValue) { //  窗口变更时，需同时更改表格高度
      this.setTableH()
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.pageInit()
      this.$refs.table.refresh(true)
    }
  },
  activated () {
    // 如果是新页签打开，则重置当前页面
    if (this.$store.state.app.isNewTab) {
      this.pageInit()
      this.$refs.table.refresh(true)
    }
    // 仅刷新列表，不重置页面
    if (this.$store.state.app.updateList) {
      this.pageInit()
      this.$refs.table.refresh()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>
