<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" :value="time" @change="dateChange" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="客户名称">
                <a-input id="outboundOrderList-demanderName" v-model.trim="queryParam.demanderName" allowClear placeholder="请输入客户名称"/>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="出库单号">
                <a-input id="outboundOrderList-stockOutNo" v-model.trim="queryParam.stockOutNo" allowClear placeholder="请输入出库单号"/>
              </a-form-item>
            </a-col>
            <template v-if="advanced">
              <a-col :md="6" :sm="24">
                <a-form-item label="业务单号">
                  <a-input id="outboundOrderList-outBizNo" v-model.trim="queryParam.outBizNo" allowClear placeholder="请输入业务单号"/>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="备货单号">
                  <a-input id="outboundOrderList-outBizSubNo" v-model.trim="queryParam.outBizSubNo" allowClear placeholder="请输入备货单号"/>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="出库类型">
                  <v-select
                    v-model="queryParam.outBizType"
                    ref="outBizType"
                    id="outboundOrderList-outBizType"
                    code="OUT_STOCK_TYPE"
                    placeholder="请选择出库类型"
                    allowClear></v-select>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <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 :md="6" :sm="24">
                <a-form-item label="发货状态">
                  <v-select
                    v-model="queryParam.sendFlag"
                    ref="sendFlag"
                    id="outboundOrderList-sendFlag"
                    code="SEND_FLAG"
                    placeholder="请选择发货状态"
                    allowClear></v-select>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="所在区域">
                  <subarea id="outboundOrderList-subarea" ref="subarea" @change="subareaChange"></subarea>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="地区" prop="shippingAddrProvinceSn">
                  <Area id="outboundOrderList-shippingAddrProvinceSn" v-model="queryParam.shippingAddrProvinceSn" placeholder="请选择省"></Area>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24" v-show="isShowWarehouse">
                <a-form-model-item label="仓库">
                  <chooseWarehouse ref="warehouse" v-model="queryParam.warehouseSn" :isPermission="true"></chooseWarehouse>
                </a-form-model-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 ? (isShowWarehouse&&isShowCustomerSearch ? 24:6) : 6" :sm="24" style="margin-bottom: 10px;" :style="{textAlign: advanced ? (isShowWarehouse&&isShowCustomerSearch ? 'center': 'left') : 'left'}">
              <a-button type="primary" @click="searchTable" :disabled="disabled" id="outboundOrderList-refresh">查询</a-button>
              <a-button style="margin-left: 5px" @click="resetSearchForm" :disabled="disabled" id="outboundOrderList-reset">重置</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="outboundOrderList-wrap">
      <a-spin :spinning="spinning" tip="Loading...">
        <!-- 列表 -->
        <div style="margin-bottom: 10px">
          <a-button
            type="primary"
            v-if="$hasPermissions('B_stockOut')"
            id="outboundOrder-export"
            :loading="loading"
            @click="handleOutbound()">批量出库</a-button>
          <a-button
            type="primary"
            v-if="$hasPermissions('B_stockSend')"
            class="button-info"
            id="outboundOrder-send"
            :loading="loading"
            @click="handleSendGood()">批量发货</a-button>
          <span style="margin-left: 5px">
            <template v-if="rowSelectionInfo && rowSelectionInfo.selectedRowKeys.length>0">{{ `已选 ${rowSelectionInfo.selectedRowKeys.length} 项` }}</template>
          </span>
        </div>
        <s-table
          class="sTable fixPagination"
          ref="table"
          :style="{ height: tableHeight+70+'px' }"
          size="small"
          :rowKey="(record) => record.stockOutSn"
          rowKeyName="stockOutSn"
          :row-selection="($hasPermissions('B_stockOut')||$hasPermissions('B_stockSend'))?{ columnWidth: 40, getCheckboxProps: record => ({ props: { disabled: record.state == 'CANCEL' } }) }:null"
          @rowSelection="rowSelectionFun"
          :columns="columns"
          :data="loadData"
          :scroll="{ y: tableHeight }"
          :defaultLoadData="false"
          bordered>
          <!-- 单号 -->
          <template slot="stockOutNo" slot-scope="text, record">
            <span v-if="record.stockOutNo && detailPermissions(record)" class="link-bule" @click="handleDetail(record)">{{ record.stockOutNo }}</span>
            <span v-else-if="record.stockOutNo && !detailPermissions(record)">{{ record.stockOutNo }}</span>
            <span v-else>--</span>
          </template>
          <!-- 操作 -->
          <template slot="action" slot-scope="text, record">
            <a-button
              size="small"
              type="link"
              v-if="record.state=='WAIT'&&$hasPermissions('B_stockOut')"
              class="button-primary"
              @click="handleOutbound(record)"
              id="outboundOrderList-out-btn">出库</a-button>
            <a-button
              size="small"
              type="link"
              class="button-primary"
              v-if="record.sendFlag==0&&$hasPermissions('B_stockSend')"
              @click="handleSendGood(record)"
              id="outboundOrderList-sendBill">发货</a-button>
            <span v-if="record.sendFlag==1&&record.state=='FINISH'">--</span>
          </template>
        </s-table>
      </a-spin>
      <!-- 详情 -->
      <a-modal
        centered
        v-drag
        class="outboundOrderDetail-modal"
        :footer="null"
        :maskClosable="false"
        title="详情"
        v-model="openModal"
        v-if="openModal"
        @cancel="cancleModal"
        width="70%">
        <div>
          <pushOrderDetailModal v-if="outBizType=='SALES'" :outBizSubSn="orderSn" />
          <allocationDetailModal v-if="outBizType=='ALLOCATE'" :outBizSn="orderSn" />
        </div>
      </a-modal>
      <!-- 发货信息 -->
      <sendGoodModal
        v-drag
        ref="detailModal"
        modalTit="新增发货单"
        :openModal="showDetailModal"
        @ok="sendSuccess"
        @cancel="showDetailModal=false"></sendGoodModal>
    </a-card>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import moment from 'moment'
import rangeDate from '@/views/common/rangeDate.vue'
import getDate from '@/libs/getDate.js'
import subarea from '@/views/common/subarea.js'
import Area from '@/views/common/area.js'
import pushOrderDetailModal from '@/views/salesManagement/pushOrderManagement/detailForOut.vue'
import allocationDetailModal from '@/views/allocationManagement/transferOut/detail.vue'
import sendGoodModal from './sendGoodModal.vue'
import { STable, VSelect } from '@/components'
import chooseWarehouse from '@/views/common/chooseWarehouse'
import customerService from '@/views/common/customerService'
import { stockOutList, stockOutOut } from '@/api/stockOut'
import { getCustomerInfo, validateStockOut } from '@/api/sendBill'
export default {
  name: 'OutboundOrderList',
  mixins: [commonMixin],
  components: { STable, VSelect, rangeDate, pushOrderDetailModal, allocationDetailModal, subarea, Area, sendGoodModal, chooseWarehouse, customerService },
  data () {
    return {
      spinning: false,
      advanced: true, // 高级搜索 展开/关闭
      tableHeight: 0,
      time: [
        moment(getDate.getThreeMonthDays().starttime, 'YYYY-MM-DD'),
        moment(getDate.getCurrMonthDays().endtime, 'YYYY-MM-DD')
      ],
      queryParam: { //  查询条件
        beginDate: getDate.getThreeMonthDays().starttime,
        endDate: getDate.getCurrMonthDays().endtime,
        demanderName: '', //  客户名称
        outBizType: undefined, //  出库类型
        stockOutNo: '',
        outBizNo: '',
        state: undefined, //  状态
        subareaArea: {
          subareaSn: undefined,
          subareaAreaSn: undefined
        },
        shippingAddrProvinceSn: undefined,
        sendFlag: undefined,
        warehouseSn: undefined,
        outBizSubNo: '',
        bizUserSn: undefined
      },
      disabled: false, //  查询、重置按钮是否可操作
      loading: false,
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        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,
      showDetailModal: false
    }
  },
  computed: {
    columns () {
      const arr = [
        { title: '创建时间', dataIndex: 'createDate', width: '8%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '审核时间', dataIndex: 'auditTime', width: '8%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '出库单号', scopedSlots: { customRender: 'stockOutNo' }, width: '10%', align: 'center' },
        { title: '业务单号', dataIndex: 'outBizNo', width: '10%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '备货单号', dataIndex: 'outBizSubNo', 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: '22%', 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: '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: 'outTime', width: '8%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '出库状态', dataIndex: 'stateDictValue', width: '7%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '发货状态', dataIndex: 'sendFlagDictValue', width: '7%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '7%', align: 'center' }
      ]
      if (this.isShowWarehouse) {
        arr.splice(6, 0, { title: '仓库', dataIndex: 'warehouseName', width: '10%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true })
      }
      if (this.$hasPermissions('M_outboundOrderList_salesPrice')) { //  售价权限
        arr.splice(this.isShowWarehouse ? 8 : 7, 0, { title: '售价', dataIndex: 'productTotalPrice', width: '6%', align: 'right', customRender: text => ((text || text == 0) ? this.toThousands(text) : '--') })
      }

      return arr
    }
  },
  methods: {
    // 表格选中项
    rowSelectionFun (obj) {
      this.rowSelectionInfo = obj || null
    },
    detailPermissions (row) {
      let state = false
      //  根据出库类型和对应功能权限 判断是否有查看详情的权限
      if (row.outBizType == 'SALES' && this.$hasPermissions('B_dispatchDetail')) { // 销售出库
        state = true
      } else if (row.outBizType == 'ALLOCATE' && this.$hasPermissions('M_transferOut_detail')) { //  调拨出库
        state = true
      }
      return state
    },
    //  时间  change
    dateChange (date) {
      this.queryParam.beginDate = date[0]
      this.queryParam.endDate = date[1]
    },
    searchTable () {
      this.$refs.table.clearSelected() // 清空表格选中项
      this.$refs.table.refresh(true)
    },
    subareaChange (val) {
      this.queryParam.subareaArea.subareaSn = val[0] ? val[0] : undefined
      this.queryParam.subareaArea.subareaAreaSn = val[1] ? val[1] : undefined
    },
    //  重置
    resetSearchForm () {
      this.$refs.rangeDate.resetDate(this.time)
      this.queryParam.beginDate = getDate.getThreeMonthDays().starttime
      this.queryParam.endDate = getDate.getCurrMonthDays().endtime
      this.queryParam.demanderName = ''
      this.queryParam.outBizType = undefined
      this.queryParam.state = undefined
      this.queryParam.stockOutNo = ''
      this.queryParam.outBizNo = ''
      this.queryParam.subareaArea.subareaSn = undefined
      this.queryParam.subareaArea.subareaAreaSn = undefined
      this.queryParam.shippingAddrProvinceSn = undefined
      this.queryParam.sendFlag = undefined
      this.queryParam.warehouseSn = undefined
      this.queryParam.outBizSubNo = ''
      this.queryParam.bizUserSn = undefined

      if (this.advanced) {
        this.$refs.subarea.clearData()
      }
      this.$refs.table.refresh(true)
    },
    //  详情
    handleDetail (row) {
      this.outBizType = row.outBizType
      //  根据出库类型跳转对应页面
      if (row.outBizType == 'SALES' && this.$hasPermissions('B_dispatchDetail')) { //  销售出库
        this.orderSn = row.outBizSubSn
        this.openModal = true
      } else if (row.outBizType == 'ALLOCATE' && this.$hasPermissions('M_transferOut_detail')) { //  调拨出库
        this.orderSn = row.outBizSn
        this.openModal = true
      } else if (row.outBizType == 'CHECK_ORDER_OUT') { //  库存盘点盘亏

      }
    },
    // 关闭弹框
    cancleModal () {
      this.outBizType = null
      this.orderSn = undefined
      this.openModal = false
    },
    // 出库/批量出库
    handleOutbound (row) {
      const _this = this
      let content = ''
      let params = []
      if (row) { //  单个出库
        content = '确认要出库吗？'
        params = [{
          stockOutSn: row.stockOutSn,
          outBizSn: row.outBizSn,
          outBizSubSn: row.outBizSubSn,
          outBizType: row.outBizType
        }]
      } else { //  批量出库
        content = '确认要批量出库吗？'
        const selectKeys = this.rowSelectionInfo ? this.rowSelectionInfo.selectedRowKeys : []
        if (!this.rowSelectionInfo || (selectKeys.length < 1)) {
          this.$message.warning('请在列表勾选后再进行批量操作！')
          return
        }
        // 判断是否右已出库的
        const list = this.rowSelectionInfo ? this.rowSelectionInfo.selectedRows : []
        const hasOut = list.find(item => item.state == 'FINISH')
        if (hasOut) {
          this.$info({
            title: '操作提示',
            centered: true,
            content: '已出库的数据无需再次出库，请重新选择！'
          })
          return
        }
        params = []
        // 根据审核时间排序
        list.sort(function (a, b) {
          const t1 = new Date(a.auditTime).getTime()
          const t2 = new Date(b.auditTime).getTime()
          return t2 - t1
        })
        list.map(item => {
          params.push({
            stockOutSn: item.stockOutSn,
            outBizSn: item.outBizSn,
            outBizSubSn: item.outBizSubSn,
            outBizType: item.outBizType
          })
        })
      }
      this.$confirm({
        title: '提示',
        content: content,
        centered: true,
        onOk () {
          if (!row) { //  批量出库
            _this.loading = true
          }
          _this.spinning = true
          stockOutOut(params).then(res => {
            _this.loading = false
            if (res.status == 200) {
              if (!row) { //  批量出库
                _this.$refs.table.clearSelected() // 清空表格选中项
              }
              _this.$message.success(res.message)
              _this.$refs.table.refresh()
              _this.spinning = false
            } else {
              _this.spinning = false
            }
          })
        }
      })
    },
    // 获取客户信息
    async getCustome (data, stockOutSnList) {
      this.spinning = true
      const customer = await getCustomerInfo({ stockOutSnList: stockOutSnList })
      const validRet = await validateStockOut({ stockOutSnList, ...customer.data })
      if (validRet.status == 200) {
        this.showDetailModal = true
        this.$refs.detailModal.setData(data, customer.data)
        this.spinning = false
      }
    },
    // 发货/批量发货
    handleSendGood (row) {
      const _this = this
      let stockOutSnList = []
      if (row) { //  单发货
        stockOutSnList = [row.stockOutSn]
        this.getCustome([row], stockOutSnList)
      } else { //  批量发货
        const list = _this.rowSelectionInfo ? _this.rowSelectionInfo.selectedRows : []
        const slen = list.length
        if (!_this.rowSelectionInfo || (_this.rowSelectionInfo && slen < 1)) {
          _this.$message.warning('请在列表勾选后再进行批量操作！')
          return
        }
        // 根据审核时间排序
        list.sort(function (a, b) {
          const t1 = new Date(a.auditTime).getTime()
          const t2 = new Date(b.auditTime).getTime()
          return t2 - t1
        })
        // 判断是否选择相同的客户
        const demanderName = list[0].demanderName
        const haseq = list.filter(item => item.demanderName == demanderName)
        const hasSend = list.find(item => item.sendFlag == 1)
        if (haseq.length == slen && !hasSend) {
          // 获取客户信息
          list.map(item => {
            stockOutSnList.push(item.stockOutSn)
          })
          _this.getCustome(list, stockOutSnList)
        } else {
          this.$info({
            title: '操作提示',
            centered: true,
            content: hasSend ? '已发货的数据不能再次发货，请重新选择' : '您所选择的出库单，不属于同一个客户，无法批量发货，请重新选择。只能针对一个客户的出库单进行批量发货。'
          })
        }
      }
    },
    // 发货成功
    sendSuccess () {
      this.showDetailModal = false
      this.$refs.table.refresh()
      this.$refs.table.clearSelected()
    },
    pageInit () {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
      this.rowSelectionInfo = null
      this.$refs.table.clearSelected()
    },
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 243
    }
  },
  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">
  .outboundOrderList-wrap{
     .sTable{
       margin-top: 8px;
     }
  }
</style>
