<template>
  <a-card size="small" :bordered="false" class="shortageStatisticsPList-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <!-- 搜索条件 -->
      <div ref="tableSearch" class="table-page-search-wrapper">
        <a-form layout="inline" @keyup.enter.native="$refs.table.refresh(true)">
          <a-row :gutter="15">
            <a-col :md="6" :sm="24">
              <a-form-item label="创建时间">
                <rangeDate ref="rangeDate" :allowClear="false" :value="time" @change="dateChange" />
              </a-form-item>
            </a-col>
            <a-col :md="4" :sm="24">
              <a-form-item label="产品编码">
                <a-input id="shortageStatisticsPList-productCode" v-model.trim="queryParam.productCode" allowClear placeholder="请输入产品编码"/>
              </a-form-item>
            </a-col>
            <a-col :md="4" :sm="24">
              <a-form-item label="产品名称">
                <a-input id="shortageStatisticsPList-productName" v-model.trim="queryParam.productName" allowClear placeholder="请输入产品名称"/>
              </a-form-item>
            </a-col>
            <template v-if="advanced">
              <a-col :md="4" :sm="24">
                <a-form-item label="原厂编码">
                  <a-input id="shortageStatisticsPList-origCode" v-model.trim="queryParam.origCode" allowClear placeholder="请输入原厂编码"/>
                </a-form-item>
              </a-col>
            </template>
            <a-col :md="6" :sm="24" style="margin-bottom: 10px;">
              <a-button type="primary" @click="$refs.table.refresh(true)" :disabled="disabled" id="shortageStatisticsPList-refresh">查询</a-button>
              <a-button style="margin-left: 5px" @click="resetSearchForm" :disabled="disabled" id="shortageStatisticsPList-reset">重置</a-button>
              <a-button
                style="margin-left: 5px"
                type="primary"
                class="button-warning"
                @click="handleExport"
                :disabled="disabled"
                :loading="exportLoading"
                v-if="$hasPermissions('B_oosDetailExportByProduct')"
                id="shortageStatisticsCList-export">导出</a-button>
              <a @click="advanced=!advanced" style="margin-left: 5px">
                {{ advanced ? '收起' : '展开' }}
                <a-icon :type="advanced ? 'up' : 'down'"/>
              </a>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <!-- alert -->
      <a-alert type="info" style="margin-bottom:10px">
        <div slot="message">
          <div>
            总缺货数量：<strong>{{ productTotal && (productTotal.totalQty || productTotal.totalQty==0) ? productTotal.totalQty : '--' }}</strong>，
            总缺货金额(￥)：<strong>{{ productTotal && (productTotal.totalAmount || productTotal.totalAmount==0) ? productTotal.totalAmount : '--' }}</strong>
          </div>
          <div>
            本页缺货数量：<strong>{{ currentTotal && (currentTotal.totalQty || currentTotal.totalQty==0) ? currentTotal.totalQty : '--' }}</strong>，
            本页缺货金额(￥)：<strong>{{ currentTotal && (currentTotal.totalAmount || currentTotal.totalAmount==0) ? currentTotal.totalAmount : '--' }}</strong>
          </div>
        </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 }"
        :defaultLoadData="false"
        bordered>
      </s-table>
    </a-spin>
  </a-card>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import moment from 'moment'
import getDate from '@/libs/getDate.js'
import { STable, VSelect } from '@/components'
import rangeDate from '@/views/common/rangeDate.vue'
import { oosProductList, oosProductDetailCount, oosProductDetailPageCount, oosDetailExportByProduct } from '@/api/oos'
export default {
  name: 'ShortageStatisticsPList',
  mixins: [commonMixin],
  components: { STable, VSelect, rangeDate },
  data () {
    return {
      spinning: false,
      advanced: true, // 高级搜索 展开/关闭
      tableHeight: 0,
      queryParam: { //  查询条件
        beginDate: getDate.getCurrMonthDays().starttime,
        endDate: getDate.getCurrMonthDays().endtime,
        productName: '',
        productCode: '',
        origCode: ''
      },
      disabled: false, //  查询、重置按钮是否可操作
      exportLoading: false, // 导出loading
      time: [
        getDate.getCurrMonthDays().starttime,
        getDate.getCurrMonthDays().endtime
      ], //  创建时间
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        const paramsPage = Object.assign(this.queryParam, { pageNo: parameter.pageNo, pageSize: parameter.pageSize }) //  有分页
        const params = Object.assign(parameter, this.queryParam) //  无分页
        return oosProductList(params).then(res => {
          let data
          if (res.status == 200) {
            data = res.data
            const no = (data.pageNo - 1) * data.pageSize
            for (var i = 0; i < data.list.length; i++) {
              data.list[i].no = no + i + 1
            }
            this.disabled = false
            this.spinning = false
            this.getCount(params)
            this.getCurrentCount(paramsPage)
          }
          return data
        })
      },
      productType: [],
      productTypeList: [], //  分类下拉数据
      productTotal: null,
      currentTotal: null
    }
  },
  computed: {
    columns () {
      const arr = [
        { title: '序号', dataIndex: 'no', width: '4%', align: 'center' },
        { title: '产品编码', dataIndex: 'productCode', width: '20%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '产品名称', dataIndex: 'productName', width: '20%', align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '原厂编码', dataIndex: 'origCode', width: '16%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '单位', dataIndex: 'unit', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '缺货数量', dataIndex: 'qty', width: '8%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        // { title: '缺货金额', dataIndex: 'totalAmount', width: '8%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '客户名称', dataIndex: 'buyerName', width: '18%', align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true }
      ]
      if (this.$hasPermissions('B_isShowPrice')) { //  售价权限
        arr.splice(6, 0, { title: '缺货金额', dataIndex: 'totalAmount', width: '8%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } })
      }
      return arr
    }
  },
  methods: {
    //  创建时间  change
    dateChange (date) {
      this.queryParam.beginDate = date[0]
      this.queryParam.endDate = date[1]
    },
    // 合计
    getCount (params) {
      oosProductDetailCount(params).then(res => {
        if (res.status == 200) {
          this.productTotal = res.data
        } else {
          this.productTotal = null
        }
      })
    },
    // 本页合计
    getCurrentCount (params) {
      oosProductDetailPageCount(params).then(res => {
        if (res.status == 200) {
          this.currentTotal = res.data
        } else {
          this.currentTotal = null
        }
      })
    },
    //  导出
    handleExport () {
      const _this = this
      const params = this.queryParam
      this.exportLoading = true
      _this.spinning = true
      oosDetailExportByProduct(params).then(res => {
        this.exportLoading = false
        _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()
    },
    //  重置
    resetSearchForm () {
      this.$refs.rangeDate.resetDate(this.time)
      this.queryParam.beginDate = getDate.getCurrMonthDays().starttime
      this.queryParam.endDate = getDate.getCurrMonthDays().endtime
      this.queryParam.productName = ''
      this.queryParam.productCode = ''
      this.queryParam.origCode = ''
      this.$refs.table.refresh(true)
    },
    pageInit () {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    },
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 250
    }
  },
  watch: {
    advanced (newValue, oldValue) {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    },
    '$store.state.app.winHeight' (newValue, oldValue) { //  窗口变更时，需同时更改表格高度
      this.setTableH()
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.pageInit()
      this.resetSearchForm()
    }
  },
  activated () {
    // 如果是新页签打开，则重置当前页面
    if (this.$store.state.app.isNewTab) {
      this.pageInit()
      this.resetSearchForm()
    }
    // 仅刷新列表，不重置页面
    if (this.$store.state.app.updateList) {
      this.pageInit()
      this.$refs.table.refresh()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>
