<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-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="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 ref="shelfList" @change="shelfChange" :itemSn="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="info" @click="printTest">打印</a-button>
                <a-button type="primary" style="margin-left: 5px" @click="$refs.table.refresh(true)" :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>
      <!-- 标签页 -->
      <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.countNum==0">({{ item.countNum }})</span></p>
        </a-tab-pane>
      </a-tabs>
      <s-table
        class="sTable fixPagination"
        ref="table"
        :style="{ height: tableHeight+84.5+'px' }"
        size="small"
        :rowKey="(record) => record.id"
        :columns="columns"
        :data="loadData"
        @expand="expandFun"
        :expandRowByClick="true"
        :scroll="{ y: tableHeight }"
        :showPagination="false"
        :defaultLoadData="false"
        bordered>
        <a-table
          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="handlePrintSticker(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>
        </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" />
    </a-spin>

    <div id="print">
      <div class="print-pages" style="font-size: 9px;padding:3pt 0 3pt 6pt;">
        <div class="storeName" style="text-align: center;font-weight: bold;margin: 2pt 0;">箭冠汽配西安大兴店</div>
        <div style="overflow: hidden;display: flex;justify-content: space-between;">
          <div style="padding-right: 3pt;">
            <div class="shelfName" style="margin-bottom: 2pt;">
              西安车领主常青二路数字货架
            </div>
            <div class="productCode" style="font-weight: bold;">JA-11070N</div>
            <div class="productName">箭牌空气滤清器 07款丰田新皇冠2.5 / 3.0</div>
            <div class="userName" style="margin-top: 2pt;font-size: 8px;"><span style="margin: 0 5pt 0 0;">2021-10-01  15:30</span> <span>王明</span></div>
          </div>
          <div>
            <div class="productSno" style="font-size: 16pt;text-align: center;">A08</div>
            <div class="qrcode" ref="qrCodeUrl" style="width: 40px;height: 40px;overflow: hidden;"></div>
          </div>
        </div>
      </div>
    </div>
  </a-card>
</template>

<script>
import QRCode from 'qrcodejs2'
import { getLodop } from '@/libs/LodopFuncs'
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.vue'
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 { shelfReplenishList, shelfReplenishDetailList, shelfReplenishCancel, shelfReplenishStateCount, shelfReplenishDetailStock, shelfReplenishConfirm } from '@/api/shelfReplenish'
export default {
  components: { STable, VSelect, rangeDate, shelfSList, confirmModal, stockModal, printStickerModal, outWarehousingModal, putWarehousingModal },
  mixins: [commonMixin],
  data () {
    return {
      spinning: false,
      advanced: true, //  高级搜索 展开/关闭
      tableHeight: 0,
      disabled: false, //  查询、重置按钮是否可操作
      curBizType: 'ALL',
      time: [
        getDate.getCurrMonthDays().starttime,
        getDate.getCurrMonthDays().endtime
      ],
      // 查询参数
      queryParam: {
        beginDate: getDate.getCurrMonthDays().starttime,
        endDate: getDate.getCurrMonthDays().endtime,
        bizType: 'ALL',
        replenishBillNo: '',
        shelfSn: undefined,
        productCode: '',
        productName: ''
      },
      columns: [
        { title: '序号', dataIndex: 'no', width: '4%', align: 'center' },
        { title: '创建时间', dataIndex: 'createDate', width: '11%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '补货单号', dataIndex: 'replenishBillNo', width: '16%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '货架名称', dataIndex: 'shelfName', width: '21%', align: 'left', customRender: function (text) { return text || '--' }, 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: 'totalConfirmQty', width: '7%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '签收总量', dataIndex: 'totalPutQty', width: '7%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '18%', align: 'left' }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        return shelfReplenishList(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
              data.list[i].subList = []
            }
            this.listData = data.list || []
            this.disabled = false
          }
          this.spinning = false
          return data
        })
      },
      subColumns: [
        { title: '序号', dataIndex: 'no', width: '8%', align: 'center' },
        { title: '产品编码', dataIndex: 'product.code', width: '20%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '产品名称', dataIndex: 'product.name', width: '28%', 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: 'confirmQty', 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: [],
      nowData: null,
      openConfirmModal: false,
      openStockModal: false,
      openPrintStickerModal: false,
      openOutWarehousingModal: false,
      openPutWarehousingModal: false,
      validateType: 'confirm',
      stockList: [],
      paramsData: null
    }
  },
  methods: {
    printTest () {
      var qrcode = new QRCode(this.$refs.qrCodeUrl, {
        text: 'dealerSn=1033242&shelfSn=342326735950757888&productCode=RPF2340&shelfPlaceCode=A01&shelfPlaceSn=123213', // 需要转换为二维码的内容
        width: 40,
        height: 40,
        colorDark: '#000000',
        colorLight: '#ffffff',
        correctLevel: QRCode.CorrectLevel.H
      })
      const LODOP = getLodop(document.getElementById('LODOP_OB'), document.getElementById('LODOP_EM'))
      console.log(LODOP, 'LODOP')
      // LODOP.ADD_PRINT_RECT(0, 0, '40mm', '30mm', 0, 1)
      LODOP.SET_SHOW_MODE('HIDE_PAPER_BOARD', 1) //  隐藏底图上有模拟走纸板的条纹线
      LODOP.SET_PRINT_MODE('POS_BASEON_PAPER', true) // 可使输出以纸张边缘为基点
      LODOP.ADD_PRINT_HTM(0, 0, '100%', '100%', document.getElementById('print').innerHTML)
      LODOP.SET_PRINT_PAGESIZE(1, '40mm', '30mm')
      LODOP.PREVIEW()
    },
    // 确认
    handleConfirm (row) {
      this.nowData = row
      this.openConfirmModal = true
    },
    // cancel
    handleCancel () {
      this.nowData = null
      this.openConfirmModal = false
      this.openStockModal = false
      this.openPrintStickerModal = false
      this.openOutWarehousingModal = false
      this.openPutWarehousingModal = false
    },
    // 库存不足 确认 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 () {
      this.nowData = null
      this.openPrintStickerModal = false
      this.$refs.table.refresh(true)
    },
    // 出库
    handleOutWarehousing (row) {
      this.nowData = row
      this.openOutWarehousingModal = true
    },
    // 出库 ok
    handleOutWarehousingOk () {
      this.nowData = null
      this.openOutWarehousingModal = false
      this.$refs.table.refresh(true)
    },
    handleValidate (type, params) {
      // 校验产品库存是否足够
      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(true)
          this.handleCancel()
        }
      })
    },
    // 签收
    handlePutWarehousing (row) {
      this.nowData = row
      this.openPutWarehousingModal = true
    },
    // 签收 ok
    handlePutWarehousingOk () {
      this.nowData = null
      this.openPutWarehousingModal = false
      this.$refs.table.refresh(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
            }
          })
        }
      })
    },
    // 货架  change
    shelfChange (obj) {
      this.queryParam.shelfSn = obj.key || undefined
    },
    expandFun (expanded, record) {
      if (expanded) {
        this.getSubItem(record) // 获取表格内部数据
      }
    },
    // 获取子节点数据
    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.$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.bizType = this.curBizType
      this.queryParam.replenishBillNo = ''
      this.queryParam.shelfSn = undefined
      this.$refs.shelfList.resetForm()
      this.queryParam.productCode = ''
      this.queryParam.productName = ''
    },
    //  时间  change
    dateChange (date) {
      this.queryParam.beginDate = date[0] || null
      this.queryParam.endDate = date[1] || null
    },
    // 选择类型
    handleTabChange (key) {
      this.queryParam.bizType = key
      this.$refs.table.refresh(true)
      this.curBizType = key
    },
    // 客户 change
    custChange (obj) {
      this.queryParam.customerSn = obj.key || undefined
    },
    // 获取类型
    queryByTypeSum () {
      shelfReplenishStateCount({}).then(res => {
        if (res.data && res.status == 200) {
          this.tabPaneData = [
            { bizName: '全部', bizType: 'ALL', countNum: null },
            { bizName: '待确认', bizType: 'WAIT_CONFIRM', countNum: 0 },
            { bizName: '待出库', bizType: 'WAIT_OUT_STOCK', countNum: 0 },
            { bizName: '待签收', bizType: 'WAIT_CHECK', countNum: 0 },
            { bizName: '已完成', bizType: 'FINISH', countNum: null },
            { bizName: '已取消', bizType: 'CANCEL', countNum: null }
          ]
          this.queryParam.bizType = 'ALL'
          this.tabPaneData[1].countNum = res.data.WAIT_CONFIRM || 0
          this.tabPaneData[2].countNum = res.data.WAIT_OUT_STOCK || 0
          this.tabPaneData[3].countNum = res.data.WAIT_CHECK || 0
          this.$refs.table.refresh(true)
        }
      })
    },
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 240
    },
    pageInit () {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
      this.queryByTypeSum()
    }
  },
  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>
