<template>
  <a-card size="small" :bordered="false" class="jg-page-wrap purchaseOutOfStock-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" :value="time" @change="dateChange" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="采购单号">
                <a-input id="outOfStockList-purchaseBillNo" v-model.trim="queryParam.purchaseBillNo" placeholder="请输入采购单号" allowClear />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="供应商名称">
                <a-select
                  id="outOfStockList-purchaseTargetSn"
                  placeholder="请选择供应商"
                  allowClear
                  v-model="queryParam.purchaseTargetSn"
                  :showSearch="true"
                  option-filter-prop="children"
                  :filter-option="filterOption"
                  @change="tragetTypeChange">
                  <a-select-option v-for="item in supplierList" :pyCode="item.pyCode" :key="item.purchaseTargetSn" :value="item.purchaseTargetSn">{{ item.purchaseTargetName }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24" style="margin-bottom: 10px;">
              <a-button type="primary" @click="$refs.table.refresh(true)" :disabled="disabled" id="purchaseOutOfStock-refresh">查询</a-button>
              <a-button style="margin-left: 8px" @click="resetSearchForm" :disabled="disabled" id="purchaseOutOfStock-reset">重置</a-button>
              <a-button
                type="primary"
                style="margin-left: 5px"
                @click="handleExport"
                :disabled="disabled"
                :loading="exportLoading"
                v-if="$hasPermissions('B_isExport')"
                class="button-warning"
                id="inventoryWarningList-export-btn">导出</a-button>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <!-- 合计 -->
      <a-alert type="info" style="margin-bottom:10px" v-if="countData">
        <div class="ftext" slot="message">
          缺货总款数：<strong>{{ countData.totalCount || countData.totalCount==0 ? countData.totalCount : '--' }}</strong>；
          缺货总数量：<strong>{{ countData.totalQty || countData.totalQty==0 ? countData.totalQty : '--' }}</strong>；
          <div style="display: inline-block;" v-if="$hasPermissions('M_ShowAllCost')">
            缺货总金额：<strong>{{ countData.totalAmount || countData.totalAmount==0 ? toThousands(countData.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>
        <!-- 操作 -->
        <template slot="action" slot-scope="text, record">
          <a-button
            size="small"
            type="link"
            class="button-success"
            v-if="$hasPermissions('B_purchaseOutOfStockDetail')"
            @click="handleDetail(record)"
            id="purchaseOutOfStock-edit-btn">详情</a-button>
        </template>
      </s-table>
    </a-spin>
    <!-- 查看详情 -->
    <detail-modal ref="outOfStockDetail" v-drag :openModal="openModal" :objItem="detailObj" @close="closeModal" />
  </a-card>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { STable, VSelect } from '@/components'
import rangeDate from '@/views/common/rangeDate.vue'
import { outOfStockList, outOfStockExportDetail, outOfStockQueryCount } from '@/api/oos'
import custList from '@/views/common/custList.vue'
import detailModal from './detailModal.vue'
import { downloadExcel } from '@/libs/JGPrint.js'
import { queryReturnSupplierList } from '@/api/purchaseReturn'
export default {
  name: 'PurchaseOutOfStock',
  components: { STable, VSelect, rangeDate, custList, detailModal },
  mixins: [commonMixin],
  data () {
    return {
      spinning: false,
      queryParam: { //  查询条件
        beginDate: undefined,
        endDate: undefined,
        purchaseTargetSn: undefined,
        purchaseTargetType: undefined,
        purchaseBillNo: ''
      },
      supplierList: [],
      detailObj: undefined, // 详情统计内容
      openModal: false,
      disabled: false, //  查询、重置按钮是否可操作
      tableHeight: 0,
      time: [],
      countData: null,
      exportLoading: false, // 导出loading
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        const params = Object.assign(parameter, this.queryParam)
        return outOfStockList(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.getCount(params)
            this.disabled = false
          }
          this.spinning = false
          return data
        })
      }
    }
  },
  computed: {
    columns () {
      const _this = this
      const arr = [
        { title: '序号', dataIndex: 'no', width: '4%', align: 'center' },
        { title: '创建时间', dataIndex: 'createDate', width: '14%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '采购单号', dataIndex: 'purchaseBillNo', width: '14%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '供应商', dataIndex: 'purchaseTargetName', width: '18%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '缺货款数', dataIndex: 'totalCategory', width: '8%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '缺货数量', dataIndex: 'totalQty', width: '8%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '缺货金额', dataIndex: 'totalAmount', width: '8%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text, 2) : '--') } },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '13%', align: 'center' }
      ]
      return arr
    }
  },
  methods: {
    // 获取供应商数据
    getSupperList () {
      queryReturnSupplierList({}).then(res => {
        if (res.status == 200) {
          this.supplierList = res.data
        } else {
          this.supplierList = []
        }
      })
    },
    // 供应商change
    tragetTypeChange (val) {
      const ind = this.supplierList.findIndex(item => item.purchaseTargetSn == val)
      if (ind != -1) {
        this.queryParam.purchaseTargetType = this.supplierList[ind].purchaseTargetType
      } else {
        this.queryParam.purchaseTargetSn = undefined
        this.queryParam.purchaseTargetType = undefined
      }
    },
    filterOption (input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },
    // 统计
    getCount (params) {
      outOfStockQueryCount(params).then(res => {
        if (res.status == 200) {
          this.countData = res.data
        } else {
          this.countData = null
        }
      })
    },
    // 导出
    handleExport () {
      const _this = this
      _this.exportLoading = true
      outOfStockExportDetail(_this.queryParam).then(res => {
        downloadExcel(res, '采购缺货列表')
        _this.exportLoading = false
      })
    },
    // 关闭详情弹窗
    closeModal () {
      this.openModal = false
      this.detailObj = undefined
    },
    //  时间  change
    dateChange (date) {
      this.queryParam.beginDate = date[0]
      this.queryParam.endDate = date[1]
    },
    //  重置
    resetSearchForm () {
      this.$refs.rangeDate.resetDate(this.time)
      this.queryParam.beginDate = undefined
      this.queryParam.endDate = undefined
      this.queryParam.purchaseTargetSn = undefined
      this.queryParam.purchaseTargetType = undefined
      this.queryParam.purchaseBillNo = ''
      this.$refs.table.refresh(true)
    },
    //  详情
    handleDetail (row) {
      this.openModal = true
      this.detailObj = row
      const _this = this
      _this.$nextTick(() => {
        _this.$refs.outOfStockDetail.pageInit()
      })
    },
    pageInit () {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
      _this.resetSearchForm()
      _this.getSupperList()
    },
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 235
    }
  },
  watch: {
    advanced (newValue, oldValue) {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    },
    '$store.state.app.winHeight' (newValue, oldValue) { //  窗口变更时，需同时更改表格高度
      this.setTableH()
    }
  },
  activated () {
    this.pageInit()
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>
