<template>
  <div>
    <a-card size="small" :bordered="false" class="searchBoxNormal">
      <!-- 搜索条件 -->
      <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="6" :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="6" :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="6" :sm="24">
                <a-form-item label="原厂编码">
                  <a-input id="shortageStatisticsPList-origCode" v-model.trim="queryParam.origCode" allowClear placeholder="请输入原厂编码"/>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="仓库">
                  <chooseWarehouse ref="warehouse" v-model="queryParam.warehouseSn"></chooseWarehouse>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="产品状态">
                  <v-select code="OOS_PRODUCT_STATE" id="shortageStatisticsPList-state" v-model="queryParam.state" allowClear placeholder="请选择产品状态"></v-select>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="停产状态">
                  <a-select v-model="queryParam.haltProdFlag" placeholder="请选择停产状态" allowClear>
                    <a-select-option value="0">
                      启用
                    </a-select-option>
                    <a-select-option value="1">
                      停产
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24" v-show="isShowCustomerSearch">
                <a-form-item label="客服">
                  <customerService ref="customerName" v-model="queryParam.bizUserSn"></customerService>
                </a-form-item>
              </a-col>
            </template>
            <a-col :md="advanced ? (isShowCustomerSearch?24:6) : 6" :sm="24" style="margin-bottom: 10px;" :style="{textAlign:advanced ? (isShowCustomerSearch?'center':'') : 'left'}">
              <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>
    </a-card>
    <a-card size="small" :bordered="false" class="shortageStatisticsPList-wrap">
      <a-spin :spinning="spinning" tip="Loading...">
        <!-- alert -->
        <div class="tongji-bar">
          <div>
            总缺货数量：<strong>{{ productTotal && (productTotal.totalQty || productTotal.totalQty==0) ? productTotal.totalQty : '--' }}</strong>，
            <span v-if="$hasPermissions('M_shortageStatisticsPList_salesPrice')">
              总缺货金额：<strong>{{ productTotal && (productTotal.totalAmount || productTotal.totalAmount==0) ? toThousands(productTotal.totalAmount) : '--' }}</strong>；
            </span>
            本页缺货数量：<strong>{{ currentTotal && (currentTotal.totalQty || currentTotal.totalQty==0) ? currentTotal.totalQty : '--' }}</strong>，
            <span v-if="$hasPermissions('M_shortageStatisticsPList_salesPrice')">
              本页缺货金额：<strong>{{ currentTotal && (currentTotal.totalAmount || currentTotal.totalAmount==0) ? toThousands(currentTotal.totalAmount) : '--' }}</strong>；
            </span>
          </div>
        </div>
        <!-- 列表 -->
        <v-table
          class="sTable fixPagination"
          ref="table"
          :style="{ height: tableHeight+32+'px' }"
          rowKeyName="no"
          :columns="columns"
          :data="loadData"
          :pagination="{pageSize:30}"
          :scroll="{ y: tableHeight }"
          :defaultLoadData="false"
          bordered>
          <template slot="productCode" slot-scope="text, record">
            <span style="padding-right: 15px;">{{ text }}</span>
            <a-badge count="促" v-if="record.promotionFlag&&record.promotionFlag.indexOf('GIFT')>=0" :number-style="{ backgroundColor: '#52c41a', zoom:'80%' }"></a-badge>
            <a-badge count="特" v-if="record.promotionFlag&&record.promotionFlag.indexOf('DISCOUNT')>=0" :number-style="{ backgroundColor: '#faad14', zoom:'80%' }"></a-badge>
          </template>
        </v-table>
      </a-spin>
    </a-card>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import moment from 'moment'
import getDate from '@/libs/getDate.js'
import { VTable, VSelect } from '@/components'
import rangeDate from '@/views/common/rangeDate.vue'
import chooseWarehouse from '@/views/common/chooseWarehouse'
import customerService from '@/views/common/customerService'
import { oosProductList, oosProductDetailCount, oosProductDetailPageCount, oosDetailExportByProduct } from '@/api/oos'
export default {
  name: 'ShortageStatisticsPList',
  mixins: [commonMixin],
  components: { VTable, VSelect, rangeDate, chooseWarehouse, customerService },
  data () {
    return {
      spinning: false,
      advanced: true, // 高级搜索 展开/关闭
      tableHeight: 0,
      queryParam: { //  查询条件
        beginDate: getDate.getCurrMonthDays().starttime,
        endDate: getDate.getCurrMonthDays().endtime,
        productName: '',
        productCode: '',
        origCode: '',
        warehouseSn: undefined,
        state: undefined,
        haltProdFlag: undefined, // 停产状态
        bizUserSn: undefined
      },
      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: '12%', align: 'left', scopedSlots: { customRender: 'productCode' } },
        { title: '产品名称', dataIndex: 'productName', width: '38%', align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '原厂编码', dataIndex: 'origCode', width: '14%', align: 'left', 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 },
        { title: '仓库', dataIndex: 'warehouseName', width: '10%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '产品状态', dataIndex: 'productShowStateDictValue', width: '8%', align: 'center', customRender: function (text) { return text || '--' } }
      ]
      if (this.$hasPermissions('M_shortageStatisticsPList_costPrice')) { // 成本权限
        arr.splice(6, 0, { title: '缺货成本金额', dataIndex: 'totalShowCostAmount', width: '8%', align: 'right', customRender: text => ((text || text == 0) ? this.toThousands(text) : '--') })
      }
      if (this.$hasPermissions('M_shortageStatisticsPList_salesPrice')) { // 售价权限
        arr.splice(7, 0, { title: '缺货金额', dataIndex: 'totalAmount', width: '8%', align: 'right', customRender: text => ((text || text == 0) ? this.toThousands(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
      _this.$store.state.app.curActionPermission = 'B_oosDetailExportByProduct'
      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) {
      this.$store.state.app.curActionPermission = ''
      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.queryParam.warehouseSn = undefined
      this.queryParam.state = undefined
      this.queryParam.haltProdFlag = undefined
      this.queryParam.bizUserSn = undefined
      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 - 190
    }
  },
  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>
<style lang="less">
  .shortageStatisticsPList-wrap{
     .sTable{
       margin-top: 10px;
     }
  }
</style>
