<template>
  <a-card size="small" :bordered="false" class="outboundOrderList-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 :xl="6" :lg="6" :md="12" :sm="24">
              <a-form-item label="审核时间">
                <rangeDate ref="rangeDate" :value="time" @change="dateChange" />
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="6" :md="12" :sm="24">
              <a-form-item label="单位名称">
                <a-input id="outboundOrderList-demanderName" v-model.trim="queryParam.demanderName" placeholder="请输入单位名称" allowClear />
              </a-form-item>
            </a-col>
            <a-col :xl="4" :lg="6" :md="6" :sm="8">
              <a-form-item label="出库类型">
                <v-select
                  v-model="queryParam.outBizType"
                  ref="outBizType"
                  id="outboundOrderList-outBizType"
                  code="OUT_STOCK_TYPE"
                  isEnable
                  placeholder="请选择出库类型"
                  allowClear></v-select>
              </a-form-item>
            </a-col>
            <a-col :xl="4" :lg="6" :md="6" :sm="8">
              <a-form-item label="单据状态">
                <v-select
                  v-model="queryParam.state"
                  ref="state"
                  id="outboundOrderList-state"
                  code="OUT_STATE"
                  placeholder="请选择单据状态"
                  allowClear></v-select>
              </a-form-item>
            </a-col>
            <a-col :xl="4" :lg="6" :md="6" :sm="8">
              <a-button type="primary" @click="$refs.table.refresh(true)" :disabled="disabled" id="outboundOrderList-refresh" style="margin-bottom: 10px;">查询</a-button>
              <a-button style="margin-left: 8px" @click="resetSearchForm" :disabled="disabled" id="outboundOrderList-reset">重置</a-button>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <div v-if="$hasPermissions('B_outboundBatchOut')" style="margin-bottom: 10px">
        <a-button type="primary" id="outboundOrderList-export" :loading="loading" @click="handleOutbounds">批量出库</a-button>
        <span style="margin-left: 5px" v-if="$hasPermissions('B_outboundBatchOut')">
          <template v-if="rowSelectionInfo&&rowSelectionInfo.selectedRowKeys.length>0">
            {{ `已选 ${rowSelectionInfo.selectedRowKeys.length} 项` }}
          </template>
        </span>
      </div>
      <!-- 列表 -->
      <s-table
        class="sTable fixPagination"
        ref="table"
        :style="{ height: tableHeight+84.5+'px' }"
        size="small"
        :rowKey="(record) => record.outBizSn"
        rowKeyName="outBizSn"
        :row-selection="$hasPermissions('B_outboundBatchOut') ? { columnWidth: 40, getCheckboxProps: record => ({ props: { disabled: record.state == 'FINISH' } }) } : null"
        @rowSelection="rowSelectionFun"
        :columns="columns"
        :data="loadData"
        :scroll="{ y: tableHeight }"
        :defaultLoadData="false"
        bordered>
        <!-- 操作 -->
        <template slot="action" slot-scope="text, record">
          <a-button
            size="small"
            type="link"
            v-if="record.state=='WAIT'&&$hasPermissions('B_outboundOut')"
            class="button-primary"
            @click="handleOutbound(record)"
            id="outboundOrderList-out-btn">出库</a-button>
          <a-button
            size="small"
            type="link"
            v-if="$hasPermissions('B_outboundOrderDetail')"
            class="button-success"
            @click="handleDetail(record)"
            id="outboundOrderList-detail-btn">详情</a-button>
          <span v-if="!(record.state=='WAIT'&&$hasPermissions('B_outboundOut')) && !($hasPermissions('B_outboundOrderDetail'))">--</span>
        </template>
      </s-table>
    </a-spin>
    <!-- 详情 -->
    <a-modal
      centered
      class="outboundOrderDetail-modal"
      :footer="null"
      :maskClosable="false"
      :bodyStyle="{padding:'12px'}"
      title="详情"
      v-model="openModal"
      v-if="openModal"
      @cancle="cancleModal"
      width="80%">
      <div style="max-height: 700px;overflow-y: scroll;">
        <pushOrderDetailModal v-if="outBizType=='PURCHASE_RETURN'" :outBizSn="orderSn" />
        <salesDetailModal v-if="outBizType=='SALES'" :outBizSn="orderSn" />
        <urgentDetailModal v-if="outBizType=='DISPATCH_DEDUCT'" :outBizSn="orderSn" />
        <storeTransferOutDetailModal v-if="outBizType=='SHOP_CALL_OUT'" :outBizSn="orderSn" />
        <chainTransferOutDetailModal v-if="outBizType=='LINKAGE_CALL_OUT'" :outBizSn="orderSn" />
        <warehouseAllocationDetailModal v-if="outBizType=='WAREHOUSE_CALL_OUT'" :outBizSn="orderSn" />
      </div>
    </a-modal>
  </a-card>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import moment from 'moment'
import { STable, VSelect } from '@/components'
import rangeDate from '@/views/common/rangeDate.vue'
import pushOrderDetailModal from '@/views/purchasingManagement/purchaseReturn/detail.vue'
import salesDetailModal from '@/views/salesManagement/salesQuery/detail.vue'
import urgentDetailModal from '@/views/salesManagement/urgentItemsOffset/detail.vue'
import storeTransferOutDetailModal from '@/views/allocationManagement/storeTransferOut/detail.vue'
import chainTransferOutDetailModal from '@/views/allocationManagement/chainTransferOut/detail.vue'
import warehouseAllocationDetailModal from '@/views/allocationManagement/warehouseAllocation/detail.vue'
import { stockOutList, stockOutOut, stockOutBatchOut } from '@/api/stockOut'
import getDate from '@/libs/getDate.js'
export default {
  name: 'OutboundOrderList',
  components: { STable, VSelect, rangeDate, pushOrderDetailModal, salesDetailModal, urgentDetailModal, storeTransferOutDetailModal, chainTransferOutDetailModal, warehouseAllocationDetailModal },
  mixins: [commonMixin],
  data () {
    return {
      spinning: false,
      advanced: true, // 高级搜索 展开/关闭
      tableHeight: 0, // 表格高度
      time: [
        moment(getDate.getCurrMonthDays().starttime),
        moment(getDate.getCurrMonthDays().endtime)
      ],
      queryParam: { //  查询条件
        beginDate: getDate.getCurrMonthDays().starttime,
        endDate: getDate.getCurrMonthDays().endtime,
        demanderName: undefined, //  单位名称
        outBizType: undefined, //  出库类型
        state: undefined //  状态
      },
      disabled: false, //  查询、重置按钮是否可操作
      columns: [
        { title: '序号', dataIndex: 'no', width: '4%', align: 'center' },
        { title: '关联单号', dataIndex: 'outBizNo', width: '10%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '出库类型', dataIndex: 'outBizTypeDictValue', width: '8%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '单位名称', dataIndex: 'demanderName', width: '20%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '总款数', dataIndex: 'productTotalCategory', width: '6%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '总数量', dataIndex: 'productTotalQty', width: '6%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '总售价', dataIndex: 'productTotalPrice', width: '6%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '审核时间', dataIndex: 'auditTime', width: '11%', align: 'center', customRender: function (text) { return text || '--' }, sorter: true },
        { title: '出库时间', dataIndex: 'outTime', width: '11%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '出库状态', dataIndex: 'stateDictValue', width: '8%', align: 'center', customRender: function (text) { return text || '--' }, sorter: true },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '10%', align: 'center' }
      ],
      loading: false,
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        // 排序
        if (parameter.sortField == 'stateDictValue') {
          parameter.sortField = 'state'
        }
        this.disabled = true
        this.spinning = true
        return stockOutList(Object.assign(parameter, this.queryParam)).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
          return data
        })
      },
      openModal: false,
      orderSn: undefined,
      outBizType: null, //  当前单子类型   SALES销售出库        ALLOCATE调拨出库
      rowSelectionInfo: null
    }
  },
  methods: {
    // 表格选中项
    rowSelectionFun (obj) {
      this.rowSelectionInfo = obj || null
    },
    detailPermissions (row) {
      let state = false
      //  根据出库类型和对应功能权限 判断是否有查看详情的权限
      if ((row.outBizType == 'PURCHASE_RETURN') && this.$hasPermissions('B_purchaseReturnDetail')) { // 采购退货
        state = true
      } else if ((row.outBizType == 'SALES') && this.$hasPermissions('B_salesDetail')) { // 销售
        state = true
      } else if ((row.outBizType == 'DISPATCH_DEDUCT') && this.$hasPermissions('M_urgentDetail')) { // 急件冲减
        state = true
      } else if ((row.outBizType == 'SHOP_CALL_OUT') && this.$hasPermissions('B_storeCallOutDetail')) { // 店内调出
        state = true
      } else if ((row.outBizType == 'LINKAGE_CALL_OUT') && this.$hasPermissions('B_allocLinkageOutDetail')) { // 连锁调出
        state = true
      } else if ((row.outBizType == 'WAREHOUSE_CALL_OUT') && this.$hasPermissions('B_warehouseAllocationDetail')) { // 仓库调出
        state = true
      }
      return state
    },
    //  时间  change
    dateChange (date) {
      this.queryParam.beginDate = date[0]
      this.queryParam.endDate = date[1]
    },
    filterOption (input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },
    //  重置
    resetSearchForm () {
      this.resetData()
      this.$refs.table.refresh(true)
    },
    // 重置数据
    resetData () {
      this.$refs.rangeDate.resetDate(this.time)
      this.queryParam.beginDate = getDate.getCurrMonthDays().starttime
      this.queryParam.endDate = getDate.getCurrMonthDays().endtime
      this.queryParam.demanderName = undefined
      this.queryParam.outBizType = undefined
      this.queryParam.state = undefined
    },
    //  详情
    handleDetail (row) {
      this.outBizType = row.outBizType
      //  根据出库类型跳转对应页面
      if (row.outBizType == 'PURCHASE_RETURN') { // 采购退货
        this.orderSn = row.outBizSn
        this.openModal = true
      } else if (row.outBizType == 'SPARE_PARTS_RETURN') { // 散件退货
        this.$message.warning('该出库类型对应页面未开发')
      } else if (row.outBizType == 'SALES') { // 销售
        this.orderSn = row.outBizSn
        this.openModal = true
      } else if (row.outBizType == 'DISPATCH_DEDUCT') { // 急件冲减
        this.orderSn = row.outBizSn
        this.openModal = true
      } else if (row.outBizType == 'SHOP_CALL_OUT') { // 店内调出
        this.orderSn = row.outBizSn
        this.openModal = true
      } else if (row.outBizType == 'CHECK_ORDER_OUT') { // 库存盘点盘亏
        this.$message.warning('该出库类型对应页面未开发')
      } else if (row.outBizType == 'LINKAGE_CALL_OUT') { // 连锁调出
        this.orderSn = row.outBizSn
        this.openModal = true
      } else if (row.outBizType == 'WAREHOUSE_CALL_OUT') { // 仓库调出
        this.orderSn = row.outBizSn
        this.openModal = true
      } else {
        this.$message.warning('出库类型未知')
      }
    },
    // 关闭弹框
    cancleModal () {
      this.outBizType = null
      this.orderSn = undefined
      this.openModal = false
    },
    // 单个出库
    handleOutbound (row) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '确认要出库吗？',
        centered: true,
        onOk () {
          _this.spinning = true
          stockOutOut({ outBizSn: row.outBizSn, outStockEnum: row.outBizType }).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.$refs.table.refresh()
              _this.spinning = false
            } else {
              _this.spinning = false
            }
          })
        }
      })
    },
    // 批量出库
    handleOutbounds () {
      if (!this.rowSelectionInfo || (this.rowSelectionInfo && this.rowSelectionInfo.selectedRowKeys.length < 1)) {
        this.$message.warning('请在列表勾选后再进行批量操作！')
        return
      }
      this.loading = true
      this.spinning = true
      const params = []
      this.rowSelectionInfo && this.rowSelectionInfo.selectedRows.map(item => {
        params.push({ outBizSn: item.outBizSn, outStockEnum: item.outBizType })
      })
      stockOutBatchOut(params).then(res => {
        this.loading = false
        if (res.status == 200) {
          this.$message.success(res.message)
          this.$refs.table.clearSelected() // 清空表格选中项
          this.$refs.table.refresh()
          this.spinning = false
        } else {
          this.spinning = false
        }
      })
    },
    pageInit () {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
      this.$refs.table.clearSelected() // 清空表格选中项
    },
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 245
    }
  },
  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.resetData()
      if (this.$route.query.pageParams) {
        this.queryParam.state = JSON.parse(this.$route.query.pageParams).state
        this.queryParam.outBizType = JSON.parse(this.$route.query.pageParams).outBizType
      }
      this.pageInit()
      this.$refs.table.refresh(true)
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>
