<template>
  <a-card size="small" :bordered="false" class="replenishmentManagementList-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <!-- 搜索条件 -->
      <div ref="tableSearch" class="table-page-search-wrapper">
        <!-- 标签页 -->
        <a-tabs type="card" v-model="queryParam.bizType" @change="handleTabChange" class="replenishmentManagementList-tabs">
          <a-tab-pane v-for="item in tabPaneData" :key="item.bizType">
            <p slot="tab">{{ item.bizName }}<span v-if="item.countNum && item.bizName!='全部'&&item.bizName!='已完成'&&item.bizName!='已取消'" style="color: red;">({{ item.countNum }})</span></p>
          </a-tab-pane>
        </a-tabs>
        <a-form layout="inline" @keyup.enter.native="$refs.table.refresh(true)">
          <a-row :gutter="15">
            <a-col :md="6" :sm="24" v-if="queryParam.bizType=='WAIT_CHECK'">
              <a-form-item label="出库时间">
                <rangeDate ref="rangeDate" :value="time" @change="dateChange" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24" v-else-if="queryParam.bizType=='FINISH'">
              <a-form-item label="签收时间">
                <rangeDate ref="rangeDate" :value="time" @change="dateChange" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24" v-else>
              <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="replenishmentManagementList-replenishBillNo" v-model.trim="queryParam.replenishBillNo" allowClear placeholder="请输入补货单号" /></a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="货架名称">
                <shelfSList :showAll="true" v-model="queryParam.shelfSn"></shelfSList>
              </a-form-item>
            </a-col>
            <template v-if="advanced">
              <a-col :md="6" :sm="24">
                <a-form-item label="产品编码"><a-input id="replenishmentManagementList-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="replenishmentManagementList-productName" v-model.trim="queryParam.productName" allowClear placeholder="请输入产品名称" />
                </a-form-item>
              </a-col>
            </template>
            <a-col :md="6" :sm="24">
              <span class="table-page-search-submitButtons">
                <a-button type="primary" style="margin-left: 5px" @click="queryByTypeSum" :disabled="disabled" id="replenishmentManagementList-refresh">查询</a-button>
                <a-button style="margin-left: 5px" @click="resetSearchForm()" :disabled="disabled" id="replenishmentManagementList-reset">重置</a-button>
                <a @click="advanced = !advanced" style="margin-left: 5px">
                  {{ advanced ? '收起' : '展开' }}
                  <a-icon :type="advanced ? 'up' : 'down'" />
                </a>
              </span>
            </a-col>
          </a-row>
        </a-form>
        <!-- 操作按钮 -->
        <div class="table-operator">
          <a-button type="primary" class="button-error" @click="openSlodOut=true">待补货产品</a-button>
          <span style="margin-left:10px;color:#999;">请点击此按钮，选择需要补货的产品创建补货单</span>
        </div>
      </div>
      <s-table
        class="sTable fixPagination"
        ref="table"
        :style="{ height: tableHeight+84.5+'px' }"
        size="small"
        :rowKey="(record) => record.id"
        :columns="columns"
        :data="loadData"
        :expandedRowKeys="expandedRowKeys"
        @expand="expandFun"
        :expandRowByClick="true"
        :scroll="{ y: tableHeight }"
        :defaultLoadData="false"
        bordered>
        <a-table
          v-if="listData&&listData[index]"
          slot="expandedRowRender"
          slot-scope="record, index"
          size="small"
          :rowKey="(record) => record.id"
          :columns="subColumns"
          :data-source="listData[index].subList"
          :pagination="false"
          :bordered="false"
          style="margin: 15px 10px;">
        </a-table>
        <!-- 操作 -->
        <template slot="action" slot-scope="text, record">
          <!-- <a-button v-if="record.billState=='WAIT_CONFIRM'" size="small" type="link" class="button-primary" @click.stop="handleConfirm(record)">确认</a-button> -->
          <a-button v-if="record.billState=='WAIT_OUT_STOCK'" size="small" type="link" class="button-primary" @click.stop="handleOutWarehousing(record)">出库</a-button>
          <a-button v-if="record.billState=='WAIT_CHECK'" size="small" type="link" class="button-primary" @click.stop="handlePutWarehousing(record)">签收</a-button>
          <a-button v-if="record.billState=='WAIT_CONFIRM' || record.billState=='WAIT_OUT_STOCK'" size="small" type="link" class="button-primary" @click.stop="handleCancelOrder(record)">取消补货单</a-button>
          <a-button v-if="record.billState=='CANCEL'" size="small" type="link" class="button-error" @click.stop="handleDelete(record)">删除</a-button>
          <a-button v-if="record.billState!='CANCEL'&&record.billState!='WAIT_CONFIRM'" size="small" type="link" class="button-primary" @click.stop="handlePrintSticker(record)">打印贴签</a-button>
        </template>
        <!-- 货架名称 -->
        <template slot="shelfName" slot-scope="text, record">
          {{text}}
          <a-badge count="已注销" :number-style="{ zoom:'80%',marginLeft:'5px', color: '#fff',background:'#999' }" v-if="record.shelfInfo.state=='WRITE_OFF'"></a-badge>
          <a-badge count="已暂停" :number-style="{ zoom:'80%',marginLeft:'5px', color: '#fff',background:'#999' }" v-if="record.shelfInfo.state=='SUSPEND'"></a-badge>
          <a-badge count="已停用" :number-style="{ zoom:'80%',marginLeft:'5px', color: '#fff',background:'#999' }" v-if="record.shelfInfo.state=='DISABLED'"></a-badge>
        </template>
        <!-- 补货单号 -->
        <template slot="replenishBillNo" slot-scope="text, record">
          <span class="table-td-link" @click.stop="handleDetail(record)">{{ record.replenishBillNo }}</span>
        </template>
      </s-table>
      <!-- 确认 -->
      <confirm-modal :openModal="openConfirmModal" :nowData="nowData" @ok="handleValidate" @close="handleCancel" />
      <!-- 库存不足，确认弹框 -->
      <stock-modal
        :openModal="openStockModal"
        :type="validateType"
        :params="paramsData"
        :listData="stockList"
        @ok="handleStockOk"
        @close="handleStockCancel" />
      <!-- 打印贴签 -->
      <print-sticker-modal :openModal="openPrintStickerModal" :nowData="nowData" @ok="handlePrintStickerOk" @close="handleCancel" />
      <!-- 出库 -->
      <out-warehousing-modal :openModal="openOutWarehousingModal" :nowData="nowData" @ok="handleOutWarehousingOk" @close="handleCancel" />
      <!-- 签收 -->
      <put-warehousing-modal :openModal="openPutWarehousingModal" :nowData="nowData" @ok="handlePutWarehousingOk" @close="handleCancel" />
      <!-- 详情 -->
      <detailModal :openModal="openDetailModal" :nowData="nowData" @close="handleCancel" />
      <!-- 待补货产品 -->
      <slodOutModal :openModal="openSlodOut" @close="openSlodOut=false" />
    </a-spin>
  </a-card>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { STable, VSelect } from '@/components'
import getDate from '@/libs/getDate.js'
import rangeDate from '@/views/common/rangeDate.vue'
import shelfSList from '@/views/common/shelfList'
import confirmModal from './confirmModal.vue'
import stockModal from './stockModal.vue'
import printStickerModal from './printStickerModal.vue'
import outWarehousingModal from './outWarehousingModal.vue'
import putWarehousingModal from './putWarehousingModal.vue'
import detailModal from './detailModal.vue'
import slodOutModal from './slodOutModal.vue'
import { shelfReplenishList, shelfReplenishDetailList, shelfReplenishCancel, shelfReplenishStateCount, shelfReplenishDetailStock, shelfReplenishConfirm, shelfReplenishDelete } from '@/api/shelfReplenish'
export default {
  components: { STable, VSelect, rangeDate, shelfSList, confirmModal, stockModal, printStickerModal, outWarehousingModal, putWarehousingModal, detailModal, slodOutModal },
  mixins: [commonMixin],
  data () {
    return {
      isNotProd: false,
      spinning: false,
      advanced: true, //  高级搜索 展开/关闭
      tableHeight: 0,
      disabled: false, //  查询、重置按钮是否可操作
      curBizType: 'ALL',
      time: [
        getDate.getCurrMonthDays().starttime,
        getDate.getCurrMonthDays().endtime
      ],
      // 查询参数
      queryParam: {
        bDate: getDate.getCurrMonthDays().starttime,
        eDate: getDate.getCurrMonthDays().endtime,
        bizType: 'ALL',
        replenishBillNo: '',
        shelfSn: undefined,
        productCode: '',
        productName: ''
      },
      expandedRowKeys: [],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        this.expandedRowKeys = []
        parameter.billState = this.queryParam.bizType == 'ALL' ? '' : this.queryParam.bizType
        const params = Object.assign(parameter, this.queryParam)
        if (params.billState == 'WAIT_CHECK') {
          params.outStockTimeBegin = this.queryParam.bDate
          params.outStockTimeEnd = this.queryParam.eDate
        } else if (params.billState == 'FINISH') {
          params.putStockTimeBegin = this.queryParam.bDate
          params.putStockTimeEnd = this.queryParam.eDate
        } else {
          params.beginDate = this.queryParam.bDate
          params.endDate = this.queryParam.eDate
        }
        delete params.index
        delete params.tableId
        delete params.bizType
        return shelfReplenishList(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
              data.list[i].subList = []
            }
            this.listData = data.list || []
            this.disabled = false
          }
          this.spinning = false
          return data
        })
      },
      subColumns: [
        { title: '序号', dataIndex: 'no', width: '4%', align: 'center' },
        { title: '货位号', dataIndex: 'shelfPlaceCode', width: '12%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '产品编码', dataIndex: 'product.code', width: '20%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '产品名称', dataIndex: 'product.name', width: '32%', align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '补货数量', dataIndex: 'qty', width: '12%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '签收数量', dataIndex: 'putQty', width: '12%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '单位', dataIndex: 'product.unit', width: '8%', align: 'center', customRender: function (text) { return text || '--' } }
      ],
      listData: [],
      tabPaneData: [
        { bizName: '全部', bizType: 'ALL', countNum: 0 },
        // { bizName: '待确认', bizType: 'WAIT_CONFIRM', countNum: 0 },
        { bizName: '待出库', bizType: 'WAIT_OUT_STOCK', countNum: 0 },
        { bizName: '待签收', bizType: 'WAIT_CHECK', countNum: 0 },
        { bizName: '已完成', bizType: 'FINISH', countNum: 0 },
        { bizName: '已取消', bizType: 'CANCEL', countNum: 0 }
      ],
      nowData: null,
      openConfirmModal: false,
      openStockModal: false,
      openPrintStickerModal: false,
      openOutWarehousingModal: false,
      openPutWarehousingModal: false,
      openDetailModal: false,
      openSlodOut: false,
      validateType: 'confirm',
      stockList: [],
      paramsData: null
    }
  },
  computed: {
    columns () {
      const ret = [
        { title: '序号', dataIndex: 'no', width: '4%', align: 'center' },
        { title: '创建时间', dataIndex: 'createDate', width: '11%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '补货单号', dataIndex: 'replenishBillNo', scopedSlots: { customRender: 'replenishBillNo' }, width: '15%', align: 'center' },
        { title: '货架名称', dataIndex: 'shelfInfo.shelfName', scopedSlots: { customRender: 'shelfName' }, width: '25%', align: 'left', ellipsis: true },
        { title: '状态', dataIndex: 'billStateDictValue', width: '8%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '补货总量', dataIndex: 'totalQty', width: '8%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '签收总量', dataIndex: 'totalPutQty', width: '8%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '16%', align: 'left' }
      ]
      if (this.queryParam.bizType == 'WAIT_CHECK') {
        ret.splice(1, 1, { title: '出库时间', dataIndex: 'outStockTime', width: '11%', align: 'center', customRender: function (text) { return text || '--' } })
      } else if (this.queryParam.bizType == 'FINISH') {
        ret.splice(1, 1, { title: '签收时间', dataIndex: 'putStockTime', width: '11%', align: 'center', customRender: function (text) { return text || '--' } })
      }
      return ret
    }
  },
  methods: {
    // 确认
    handleConfirm (row) {
      this.nowData = row
      this.openConfirmModal = true
    },
    // 补货详情
    handleDetail (row) {
      this.nowData = row
      this.openDetailModal = true
    },
    // 库存不足 确认 ok
    handleStockOk (type, params) {
      this.openStockModal = false
      this.openConfirmModal = false
      this.openOutWarehousingModal = false
      if (type == 'confirm') { // 确认
        this.confirmFun(params)
      }
    },
    // 库存不足 确认 cancel
    handleStockCancel () {
      this.stockList = []
      this.validateType = 'confirm'
      this.openStockModal = false
    },
    // 打印贴签
    handlePrintSticker (row) {
      this.nowData = row
      this.openPrintStickerModal = true
    },
    // 打印贴签 ok
    handlePrintStickerOk () {},
    // 出库
    handleOutWarehousing (row) {
      this.nowData = row
      this.openOutWarehousingModal = true
    },
    // 出库 ok
    handleOutWarehousingOk () {
      this.nowData = null
      this.openOutWarehousingModal = false
      this.queryByTypeSum(true)
    },
    // cancel
    handleCancel () {
      this.nowData = null
      this.openConfirmModal = false
      this.openStockModal = false
      this.openPrintStickerModal = false
      this.openOutWarehousingModal = false
      this.openPutWarehousingModal = false
      this.openDetailModal = false
    },
    handleValidate (type, params) {
      if (type == 'confirm') { // 确认
        this.confirmFun(params)
      }
      // this.spinning = true
      // 校验产品库存是否足够
      // shelfReplenishDetailStock(params).then(res => {
      //   if (res.status == 200) {
      //     if (res.data && res.data.length > 0) {
      //       this.stockList = res.data
      //       this.validateType = 'confirm'
      //       this.paramsData = params
      //       this.openStockModal = true
      //     } else {
      //       if (type == 'confirm') { // 确认
      //         this.confirmFun(params)
      //       }
      //     }
      //   }
      // })
    },
    // 提交确认
    confirmFun (params) {
      shelfReplenishConfirm(params).then(res => {
        if (res.status == 200) {
          this.$message.success('确认补货成功')
          this.$refs.table.refresh()
          this.handleCancel()
        }
        this.spinning = false
      })
    },
    // 签收
    handlePutWarehousing (row) {
      this.nowData = row
      this.openPutWarehousingModal = true
    },
    // 签收 ok
    handlePutWarehousingOk () {
      this.nowData = null
      this.openPutWarehousingModal = false
      this.queryByTypeSum(true)
    },
    // 取消补货单
    handleCancelOrder (row) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '确认取消补货单吗？',
        centered: true,
        onOk () {
          _this.spinning = true
          shelfReplenishCancel({ replenishBillSn: row.replenishBillSn }).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.$refs.table.refresh()
              _this.spinning = false
            } else {
              _this.spinning = false
            }
          })
        }
      })
    },
    // 删除
    handleDelete (row) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '确认删除补货单吗？',
        centered: true,
        onOk () {
          _this.spinning = true
          shelfReplenishDelete({ replenishBillSn: row.replenishBillSn }).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.$refs.table.refresh()
              _this.spinning = false
            } else {
              _this.spinning = false
            }
          })
        }
      })
    },
    expandFun (expanded, record) {
      if (expanded) {
        this.expandedRowKeys.push(record.id)
        this.getSubItem(record) // 获取表格内部数据
      } else {
        const i = this.expandedRowKeys.findIndex(item => item == record.id)
        this.expandedRowKeys.splice(i, 1)
      }
    },
    // 获取子节点数据
    getSubItem (record) {
      this.spinning = true
      shelfReplenishDetailList({ replenishBillSn: record.replenishBillSn }).then(res => {
        const ind = this.listData.findIndex(item => item.id == record.id)
        if (ind >= 0) {
          if (res.status == 200 && res.data && res.data.length) {
            res.data.map((item, index) => {
              item.no = index + 1
            })
            this.listData[ind].subList = res.data
          } else {
            this.listData[ind].subList = []
          }
        }
        this.spinning = false
      })
    },
    // 重置
    resetSearchForm () {
      this.resetData()
      this.queryByTypeSum()
    },
    // 重置数据
    resetData () {
      this.$refs.rangeDate.resetDate(this.time)
      this.queryParam.bDate = getDate.getCurrMonthDays().starttime
      this.queryParam.eDate = getDate.getCurrMonthDays().endtime
      this.queryParam.bizType = this.curBizType
      this.queryParam.replenishBillNo = ''
      this.queryParam.shelfSn = undefined
      this.queryParam.productCode = ''
      this.queryParam.productName = ''
    },
    //  时间  change
    dateChange (date) {
      this.queryParam.bDate = date[0] || null
      this.queryParam.eDate = date[1] || null
    },
    // 选择类型
    handleTabChange (key) {
      this.expandedRowKeys = []
      this.queryParam.bizType = key
      this.curBizType = key
      this.resetSearchForm()
    },
    // 客户 change
    custChange (obj) {
      this.queryParam.customerSn = obj.key || undefined
    },
    // 获取类型
    queryByTypeSum (flag) {
      const params = JSON.parse(JSON.stringify(this.queryParam))
      if (params.bizType == 'WAIT_CHECK') {
        params.outStockTimeBegin = this.queryParam.bDate
        params.outStockTimeEnd = this.queryParam.eDate
      } else if (params.bizType == 'FINISH') {
        params.putStockTimeBegin = this.queryParam.bDate
        params.putStockTimeEnd = this.queryParam.eDate
      } else {
        params.beginDate = this.queryParam.bDate
        params.endDate = this.queryParam.eDate
      }
      delete params.bizType
      this.spinning = true
      shelfReplenishStateCount(params).then(res => {
        if (res.data && res.status == 200) {
          // this.tabPaneData[1].countNum = res.data.WAIT_CONFIRM || 0
          this.tabPaneData[1].countNum = res.data.WAIT_OUT_STOCK || 0
          this.tabPaneData[2].countNum = res.data.WAIT_CHECK || 0
          this.tabPaneData[3].countNum = res.data.FINISH || 0
          this.tabPaneData[4].countNum = res.data.CANCEL || 0
          this.queryParam.bizType = this.curBizType
          this.$refs.table.refresh(!flag)
        }
        this.spinning = false
      })
    },
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 200
    },
    pageInit () {
      const _this = this
      this.isNotProd = !!process.env.VUE_APP_ENVTIPS
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
      this.curBizType = this.$route.query && this.$route.query.bizType || this.curBizType
      this.queryByTypeSum()
      if (this.$route.query && this.$route.query.bizType == 'ALL') {
        this.openSlodOut = true
      }
    }
  },
  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.resetData()
      this.pageInit()
    }
  },
  activated () {
    // 如果是新页签打开，则重置当前页面
    if (this.$store.state.app.isNewTab) {
      this.resetData()
      this.pageInit()
    }
  }
}
</script>

<style lang="less">
	.replenishmentManagementList-wrap{
    .replenishmentManagementList-tabs.ant-tabs.ant-tabs-card .ant-tabs-bar{
      margin: 0 0 10px 0!important;
    }
		.replenishmentManagementList-tabs.ant-tabs.ant-tabs-card .ant-tabs-card-bar .ant-tabs-nav-container{
      height: 30px!important;
		}
    .replenishmentManagementList-tabs.ant-tabs.ant-tabs-card .ant-tabs-card-bar .ant-tabs-tab-active{
      height: 30px!important;
    }
    .replenishmentManagementList-tabs.ant-tabs.ant-tabs-card .ant-tabs-card-bar .ant-tabs-tab{
      line-height: 26px!important;
      height: 30px!important;
    }
	}
</style>
