<template>
  <div data-key="AFTER_PRINT_ORDER" class="after-delivery">
    <!-- loading -->
    <Spin
      v-show="isLoading"
      fix
      size="large"
    >
      <div class="loading-wrap">
        <Icon
          type="ios-loading"
          size="24"
          class="demo-spin-icon-load"
        />
        <span class="loading-text" />
      </div>
    </Spin>

    <!-- 扫描声音播放 -->
    <video
      id="audio"
      style="display: none;"
    />

    <!-- 扫描物流单声音播放 -->
    <video
      id="order-audio"
      style="display: none;"
    />

    <!-- 打印组件 -->
    <printHtml ref="printInfo" />

    <Navbar
      ref="navbar"
      :input-config="inputConfig"
      :enable-config="enableConfig"
      :form-config="formConfig"
      :default-config="systemConfig"
      :doc-url="docUrl"
      print-type="scanChuku"
      popper-class="after-delivery-pop"
      @on-enter="inputEnter"
      @on-button-click="onButtonClick"
      @on-print-change="configChange"
    >
      <!-- 顶部右侧图标 -->
      <div
        slot="icon-right"
        style="color: var(--primary-color);"
        class="back-version"
        @click="openFeedback"
      >
        <img
          src="../../../assets/image/back-view.png"
          alt=""
        >
        <span>返回旧版本</span>
      </div>
    </Navbar>

    <Layout v-show="showContent">
      <!-- 左侧订单信息 -->
      <div
        slot="left"
        class="overflow left-panel"
      >
        <AfterDeliveryPanel
          :order-info="orderInfo"
          :scan-num="scanNum"
          :total-num="totalNum"
          :sku-info="skuInfo"
        />
      </div>
      <!-- 右侧篮子 -->
      <div
        slot="right"
        class="right-panel"
      >
        <div
          v-if="goodList.length > 0"
          class="good-list"
        >
          <GoodItem
            v-for="(item, index) in goodList"
            :key="index+ item.title"
            :data="item"
            :index="index"
            :current-index="lastScanIndex"
          />
        </div>
      </div>
    </Layout>
  </div>
</template>

<script>
import cloneDeep from 'lodash/cloneDeep';
import qs from 'qs';
import Navbar from '../components/navbar.vue';
import Layout from '../components/layout.vue';
import AfterDeliveryPanel from './afterDeliveryPanel.vue';
import GoodItem from './goodItem.vue';
import printHtml from '../components/printHtml.vue';
import OrderPanel from './orderPanel.vue';

const R3 = window.R3;
const { network } = R3;

const scanType = {
  qrcode: 'qrcode',
  sku: 'sku',
  gbcode: 'gbcode'
}

export default {
  name: 'AfterDelivery',

  components: {
    Navbar,
    Layout,
    AfterDeliveryPanel,
    GoodItem,
    printHtml,
    OrderPanel
  },

  data() {
    return {
      isLoading: false,
      inputConfig: [
        {
          label: '  拣货单号',
          placeholder: '拣货单号',
          icon: 'ios-clock-outline-saoma',
          colname: 'orderNo',
          value: '',
          'element-id': 'order-input',
          class: 'order-input-wrap',
        },
        {
          label: '扫描商品',
          placeholder: '商品sku/国标码/唯一码',
          icon: 'ios-clock-outline-saoma',
          colname: 'skuNo',
          value: '',
          'element-id': 'sku-input'
        }
      ],
      formConfig: [
        {
          title: '打印物流单',
          name: 'isPrintLogistics',
          Checkbox: false,
          value: true,
          disabled: true
        },
        {
          title: '打印发货单',
          name: 'isPrintDelivery',
          Checkbox: false,
          showTip: '选择发货单',
          value: false,
        },
        {
          title: '打印物流单后直接发货',
          name: 'isDeliveryAfterPrint',
          Checkbox: false,
          value: false,
        },
        {
          title: '扫描完成界面清空',
          name: 'isClear',
          Checkbox: false,
          value: false,
        },
      ],
      systemConfig: {
        isPrintLogistics: true,
        isPrintDelivery: false,
        isDeliveryAfterPrint: false,
        isClear: false,
      },
      docUrl: 'https://burgeon.yuque.com/cgmq7t/gndrvn/mkutyfa31n91elyn?singleDoc#',
      goodList: [],
      lastScanIndex: -1, // 最新扫描的商品索引
      orderInfo: {}, // 订单信息
      skuInfo: {}, // 商品信息
      showContent: false, // 显示扫描结果
      scanError: '', // 扫描失败声音
      scanOrder: '', // 扫描商品声音
      scanOk: '', // 扫描成功声音
      scanWarning: '', // 扫描提示声音
      scanLogistics: '', // 扫描物流单号声音
      orderId: '', // 订单编号
      totalNum: 0, // 应出数量
      scanNum: 0, // 已出数量
      supportOnlySkuFlag: false,
      supportCodeAndSkuFlag: false,
      supportOnlyQrCodeFlag: false,
      isQrcodeScanFlag: false,
      isOneGoodInOrderFlag: false, // 拣货单是否满足一单一件
      isDirectScanGoodFlag: false, // 是否直接扫描商品
      errorMsg: '',

      matchIndex: 0, // 匹配到的商品索引
    };
  },

  mounted() {
    setTimeout(() => {
      this.focusSkuInput()
    }, 200);
    // 按回车关闭出库拦截订单报错
    this.attachEvent('keydown', this.closeErrorModal);
  },

  created() {
    this.getQrCodeConfig();
    this.getPrintSound();
    this.getConfig();
  },

  computed: {
    // 是否允许用户设置配置
    enableConfig() {
      return !this.inputConfig[0].value;
    },
  },

  methods: {
    // 更新打单失败的订单的标签
    showGoodErrorTip() {
      // const currentGood = this.goodList[matchIndex];
      // this.skuInfo = currentGood.orderInfo
      // this.scanGoodIndex
      this.goodList[0].errorTip = true;
      this.goodList = JSON.parse(JSON.stringify(this.goodList))
    },

    // 按回车关闭出库拦截订单报错
    closeErrorModal(e) {
      if (e.keyCode === 13) {
        const dom = document.querySelector('.ark-modal-content-drag.fcError .ark-btn-posdefault');
        if (dom) {
          dom.click();
          this.clearSkuInput()
          this.$nextTick(() => {
            this.focusSkuInput()
          })
        }
      }
    },

    // 绑定事件
    attachEvent(eventName, handler) {
      window.addEventListener(eventName, handler);
      this.$once('hook:beforeDestroy', () => {
        window.removeEventListener(eventName, handler);
      });
    },

    // 配置改变
    configChange(data) {
      localStorage.setItem('AfterDeliveryConfig', JSON.stringify(data));
    },

    getConfig() {
      const configJson = localStorage.getItem('AfterDeliveryConfig')
      console.log("🚀 ~ 获取缓存", configJson)
      if (configJson) {
        const config = JSON.parse(configJson)
        this.systemConfig = config
      }
    },

    openFeedback() {
      this.$FeedbackDialog({
        type: 4,
        onOk: this.closePage
      })
    },

    // 获取唯一码策略
    getQrCodeConfig() {
      network.get('/p/cs/platform/config/qr_code_control').then(res => {
        if (res.data.code === 0) {
          // 仅支持SKU出库
          this.supportOnlySkuFlag = res.data.data.OUT_OF_STOCK[0].configValue == 'true' ? true : false;
          // 支持唯一码/SKU出库
          this.supportCodeAndSkuFlag = res.data.data.OUT_OF_STOCK[1].configValue == 'true' ? true : false;
          // 仅支持唯一码出库。即通过唯一码匹配
          this.supportOnlyQrCodeFlag = res.data.data.OUT_OF_STOCK[2].configValue == 'true' ? true : false;
          console.log('唯一码策略', res.data.data.OUT_OF_STOCK);
        }
      });
    },

    // 清除界面数据
    clearPage(clearSku = true) {
      this.showContent = false;
      this.orderInfo = {};
      this.totalNum = 0;
      this.scanNum = 0;
      this.goodList = [];
      this.skuInfo = {}
      if(clearSku) {
        this.inputConfig[1].value = '';
      }
    },

    // 获取打印音效
    getPrintSound() {
      const params = {
        range: 100,
        startindex: 0,
        table: 'T_OMSSOUNDSET',
        fkdrplist: {
          searchcols: ['TYPE_NAME', 'ID', 'SOUND_ID', 'URL']
        },
        isdroplistsearch: true,
      };
      network.post('/p/cs/list/query', params).then((res) => {
        res.data.rows.forEach(row => {
          if (row.TYPE_NAME.val == '扫描商品') {
            this.scanOrder = row.URL.val;
          } else if (row.TYPE_NAME.val == '失败') {
            this.scanError = row.URL.val;
          } else if (row.TYPE_NAME.val == '成功') {
            this.scanOk = row.URL.val;
          } else if (row.TYPE_NAME.val == '扫描物流') {
            this.scanLogistics = row.URL.val;
          } else if (row.TYPE_NAME.val == '提示') {
            this.scanWarning = row.URL.val;
          }
        });
      });
    },

    // 打开loading
    showLoading() {
      this.isLoading = true;
    },

    // 关闭loading
    hideLoading() {
      this.isLoading = false;
    },

    // 扫描单号输入框获取光标
    focusOrderInput() {
      const dom = this.$refs.navbar.$el;
      const input = dom.querySelector('#order-input');
      if (input) {
        console.log('获取焦点');
        input.focus();
      }
    },

    // 扫描商品输入框获取光标
    focusSkuInput() {
      const dom = this.$refs.navbar.$el;
      const input = dom.querySelector('#sku-input');
      if (input) {
        input.focus();
      }
    },

    // 顶部栏输入框回车
    inputEnter(e, colname) {
      const value = e.target.value.trim();
      this.showLoading()
      if (colname === 'orderNo') {
        this.clearPage()
        if (!value) {
          this.playAudio(this.scanError)
          this.$Message.warning('拣货单号不能为空!');
          this.hideLoading();
          return;
        }
        this.lastScanIndex = -1; // 重置最新扫描商品索引
        this.scanOrderNo(value);
      } else {
        if (!value) {
          this.playAudio(this.scanError)
          this.$Message.warning('商品sku/国标码/唯一码，不能为空！');
          this.hideLoading();
          return;
        }
        const pickNo = this.inputConfig[0].value.trim()
        // 没有配置自动清除，但如果没拣货单，直接扫商品，也要清空数据
        if(!pickNo) {
          this.clearPage(false)
        }
        this.lastScanIndex = -1; // 重置最新扫描商品索引
        this.scanGood(value);
      }
    },

    // 播放语音
    playAudio(url, id = '#audio') {
      const audio = document.querySelector(id);
      audio.src = url;
      audio.play();
    },

    // 扫描单号
    scanOrderNo(value) {
      const params = {
        pick_no: value,
      };
      network.get(`/p/cs/secondary_sorting/polymerization?${qs.stringify(params)}`).then(res => {
        if (res.data.code === 0) {
          this.playAudio(this.scanWarning);

          const data = res.data.data;
          this.orderInfo.pickNo = value;

          if (this.systemConfig.isDeliveryAfterPrint && data.orderInfo && data.orderInfo.ISEMBARGO === 1) {
            this.playAudio(this.scanError);
            this.$Message.warning({
              content: '此订单包含航空禁运商品，请注意！',
              duration: 3
            });
          }

          // 设置左侧面板数据
          this.scanNum = data.order_picking_progress;
          this.totalNum = data.total_order_picking_progress;
          this.orderInfo = {
            pickNo: value,
          };

          this.setGoodListFromPick(data.every_order_of_pick_list);

          if (!this.isOneGoodInOrderFlag) {
            this.playAudio(this.scanError)
            this.$Message.warning('含有一单多件订单，不支持后置出库！');
            this.hideLoading();
            return;
          }
          this.showContent = true;
          this.focusSkuInput();
        } else {
          this.$Message.error(res.data.message);
          this.playAudio(this.scanError);
        }
      }).finally(() => {
        this.hideLoading();
      })
    },

    // 扫描商品
    scanGood(value) {
      const isExistPickNo = this.inputConfig[0].value ? true : false;
      const url = isExistPickNo ? '/p/cs/secondary_sorting/scan/polymerization' : '/p/cs/order/item/sku/polymerization' // 有拣货单号时用新接口
      network.post(url, {
        includingDelivery: this.systemConfig.isPrintDelivery, // 是否打印发货单
        pickingNo: this.inputConfig[0].value.trim(),
        sku: value
      }).then(res => {
        if (res.data.code === 0) {
          const data = res.data.data;

          // 判断用户是否直接扫商品
          const pickNo = this.inputConfig[0].value
          if (!pickNo) {
            this.isDirectScanGoodFlag = true
          } else {
            this.isDirectScanGoodFlag = false
          }

          if (this.isDirectScanGoodFlag) {
            this._dataCache = cloneDeep(data)
            // 往商品列表里添加商品
            this.showContent = true;
          } else {
            this._dataCache = cloneDeep(data.queryOrderByItemSkuPolymerizationVO)
            // 根据already_ship_list判断哪些订单出库了。更新进度
            this.already_ship_list = data.secondarySortingScanResponse.already_ship_list;
            data.errorNotice = data.queryOrderByItemSkuPolymerizationVO.errorNotice
          }

          this._hasError = false // errorNotice有值时，要更新进度，但是不打印。所以加了这个标记
          if (data.errorNotice && data.errorNotice.tempPrinterrorList) {
            this._hasError = true
            let errorMsg = ''
            data.errorNotice.tempPrinterrorList.forEach((item, index) => {
              errorMsg += `${index + 1}.${item.ERRORMSG}\n`
            })
            this.errorMsg = errorMsg
            this.$Modal.info({
              title: '提示',
              render: (h, params) => h('div',
                {
                  style: {
                    'white-space': 'pre-wrap',
                    'line-height': '16px'
                  }
                },
                this.errorMsg),
              cancelType: true,
              titleAlign: 'left',
              mask: true,
              width: 600,
            })
            this.playAudio(this.scanError)
          }
          this.playAudio(this.scanOrder);

          // 去匹配商品列表
          this._qrcodeIsRecorded = false
          this._scanedSkuIndex = -1
          this._scanedGbcodeIndex = -1

          // let qrcode = ''
          // if (data.secondarySortingScanResponse) {
          //   qrcode = data.secondarySortingScanResponse.qrcode
          // }
          // const gbcode = data.secondarySortingScanResponse.gbcode
          // const sku = data.secondarySortingScanResponse.sku
          // const isIntercept = data.secondarySortingScanResponse.is_intercept === 1 ? true : false
          const { sku, qrcode, gbcode, isIntercept, order_id } = this.getGoodFields(data)
          console.log('扫描商品关键数据_wjf_008', this.getGoodFields(data))
          if (isIntercept) {
            this.playAudio(this.scanError);
          }

          // 获取扫描商品输入框里输入的是什么值
          this._scanType = this.getScanType(value, sku, gbcode, qrcode)
          console.log("商品的扫描类型", this._scanType)
          const matchIndex = this.singleMatch(sku, gbcode, qrcode, order_id)
          this.matchIndex = matchIndex;
          console.log("匹配到的索引", matchIndex)
          if (matchIndex > -1) {
            // if(!this._hasError) {
            //   // 打印
            //   this.printGood(matchIndex, qrcode, isIntercept)
            // }
            this.scanGoodIndex = matchIndex
            this.updateGood(matchIndex, qrcode, isIntercept)
            this.hideLoading();
          } else {
            if (this._qrcodeIsRecorded && this._scanType === scanType.qrcode) {
              this.$Message.warning('已经录入过该唯一码，不允许重复录入！');
              this.hideLoading();
              return;
            }
            // 如果是因为匹配过sku，导致匹配不到，需要把命中的商品排到第一位
            if (this._scanedSkuIndex > -1) {
              console.log('匹配过sku，导致匹配不到')
              this.$Message.warning('请勿重复扫描!')
              this.scanGoodIndex = this._scanedSkuIndex
              this.updateGood(this._scanedSkuIndex, null, isIntercept)
              // if(!this._hasError) {
              //   // 打印
              //   this.printGood(this._scanedSkuIndex, null, isIntercept)
              // }
              this.hideLoading();
              return
            }
            // 如果是因为匹配过gbcode，导致匹配不到，需要把命中的商品排到第一位
            if (this._scanedGbcodeIndex > -1) {
              console.log('匹配过gbcode，导致匹配不到')
              this.$Message.warning('请勿重复扫描!')
              // if(!this._hasError) {
              //   // 打印
              //   this.printGood(this._scanedGbcodeIndex, null, isIntercept)
              // }
              this.scanGoodIndex = this._scanedGbcodeIndex
              this.updateGood(this._scanedGbcodeIndex, null, isIntercept)
              this.hideLoading();
              return
            }

            // 只扫商品，没扫拣货单时，直接插入商品
            if (this.isDirectScanGoodFlag) {
              // 设置左侧面板数据
              this.scanNum++
              this.totalNum++
              this.addGood(data.orderInfo, data)
            }
            this.hideLoading();
          }
          if (data.errorNotice && data.errorNotice.tempPrinterrorList) {
            this.showGoodErrorTip()
          }

        } else {
          this.inputConfig[1].value = '';
          this.$Message.error(res.data.message);
          this.playAudio(this.scanError);
          this.hideLoading();
        }
      }).finally(() => {
        this.hideLoading();
      })
    },

    // 获取商品的sku,gbcode,qrcode,拦截状态
    getGoodFields(data) {
      let qrcode = ''
      let gbcode = ''
      let sku = ''
      let order_id = ''
      let isIntercept = false
      if (this.isDirectScanGoodFlag) {
        // 无拣货单时
        if(data.orderInfo && data.orderInfo.wareHousingSkuItemVOList) {
          qrcode = data.orderInfo.wareHousingSkuItemVOList[0].qrcode
        }
        if(data.orderInfo) {
          order_id = data.orderInfo.id
          sku = data.orderInfo.sku
          isIntercept = data.orderInfo.ISINTERECEPT === 1 ? true : false
        }
        if(data.orderItemVOList){
          gbcode = data.orderItemVOList[0].GBCODE
        }
      } else {
        // 有拣货单时
        if (data.secondarySortingScanResponse) {
          qrcode = data.secondarySortingScanResponse.qrcode
        }
        order_id = data.secondarySortingScanResponse.order_id
        gbcode = data.secondarySortingScanResponse.gbcode
        sku = data.secondarySortingScanResponse.sku
        isIntercept = data.secondarySortingScanResponse.is_intercept === 1 ? true : false
      }
      return {
        qrcode,
        gbcode,
        sku,
        isIntercept,
        order_id
      }
    },

    // 更新商品
    updateGood(matchIndex, qrcode, isIntercept) {
      // if(type == 'houzhierror'){
      //   this.showGoodErrorTip(matchIndex, qrcode, isIntercept)
      // }else {
        this.updateProgress(this.already_ship_list)
        const currentGood = this.goodList[matchIndex];
        this.skuInfo = currentGood.orderInfo
        currentGood.isIntercept = isIntercept
        if(isIntercept) {
          return
        }

        if (this._scanType === scanType.qrcode) {
          currentGood.good_qrcode = qrcode
          currentGood.qrcode = qrcode
        }
        if (currentGood.scanInNum < currentGood.qty) {
          currentGood.scanInNum++
          this.scanNum++

          if(!this._hasError) {
            // 打印
            this.printGood(currentGood)
          }
        }
        this.goodList.splice(matchIndex, 1);
        this.goodList.unshift(currentGood);
        this.sortGoodList(currentGood);
        this.lastScanIndex = 0;
        this.clearSkuInput();

        this.clearAfterScan()
      // }
      
    },
    clearAfterScan() {
      if (this.systemConfig.isClear) {
        if (this.isDirectScanGoodFlag) {
          // 无拣货单时，要扫一个商品就清空
          this.clearPage()
          this.focusSkuInput()
        } else {
          // 有拣货单时，要全部扫完再清空
          if (this.totalNum === this.scanNum) {
            this.clearOrderInput()
            this.clearPage()
            this.focusOrderInput()
          }
        }
      } else {
        // 只清空输入框
        this.clearSkuInput()
        if (this.totalNum === this.scanNum) {
          this.clearOrderInput()
        }
      }
    },

    async printGood(matchIndex, qrcode, isIntercept) {
      const data = {
        houzhi: {
          data: this._dataCache,
          isPrintDelivery: this.systemConfig.isPrintDelivery,
          isDeliveryAfterPrint: this.systemConfig.isDeliveryAfterPrint,
          callback: (type) => {
            console.log(type, 'wjf_00000000000000000001')
            // if(type == 'houzhierror'){
            //   this.showGoodErrorTip(matchIndex, qrcode, isIntercept)
            // }else {
              // this.updateGood(matchIndex, qrcode, isIntercept, type)
            // }
            // if(this.systemConfig.isClear) {
            //   alert('清空界面')
            // }
          }
          // callbackerror: () => {
          //   this.showGoodErrorTip(matchIndex, qrcode, isIntercept)
          // }
        }
      };

      console.log('🚀 打印数据', data);
      this.$refs.navbar.$refs.config.print(data);
    },

    // 扫描商品时排序
    // 商品排序: 当前已扫-未扫-之前已扫
    sortGoodList(currentGood) {
      const unScannedList = []; // 未扫
      const scannedList = []; // 已扫
      this.goodList.forEach(item => {
        if (item.scanInNum === 0 && item !== currentGood) {
          unScannedList.push(item);
        } else if (item.scanInNum !== 0 && item !== currentGood) {
          scannedList.push(item);
        }
      });
      this.goodList = [currentGood, ...unScannedList, ...scannedList];
    },

    // 根据already_ship_list判断哪些订单出库了。更新进度
    updateProgress(shipList) {
      shipList.forEach(id => {
        const shipOrder = this.goodList.find(item => item.orderInfo.order_id === id)
        if(shipOrder && shipOrder.scanInNum === 0) {
          shipOrder.scanInNum = 1
          this.scanNum++
        }
      })
    },

    // 匹配商品
    singleMatch(sku, gbcode, qrcode, order_id) {
      let matchIndex = -1; // 记录匹配到到商品索引

      for (let i = 0; i < this.goodList.length; i++) {
        const good = this.goodList[i];
        // 根据扫描商品输入框的输入的类型去匹配商品
        switch (this._scanType) {
          case scanType.qrcode:
            matchIndex = this.matchQrcode(good, i, qrcode, sku, order_id)
            break
          case scanType.sku:
            matchIndex = this.matchSku(good, i, sku, order_id)
            break
          case scanType.gbcode:
            matchIndex = this.matchGbcode(good, i, gbcode, order_id)
            break
          // 开启gbcode、sku截取(类似模糊匹配)
          default:
            const inputValue = this.inputConfig[1].value.trim()
            // 判断是否是截取sku得到的
            if(inputValue.includes(sku)) {
              console.log('截取sku')
              matchIndex = this.matchSku(good, i, sku, order_id)
            }
            // 判断是否是截取gbcode得到的
            else if(inputValue.includes(gbcode)) {
              console.log('截取gbcode')
              matchIndex = this.matchGbcode(good, i, gbcode, order_id)
            }
        }
        // 匹配成功就退出循环
        if (matchIndex > -1) {
          break
        }
      }
      return matchIndex
    },

    matchQrcode(good, i, qrcode, sku, order_id) {
      // 仅支持SKU出库
      if (this.supportOnlySkuFlag) {
        console.log('仅支持SKU出库')
        return -1
      }
      // if (qrcode && good.qrcode === qrcode && !good.good_qrcode) {
      //   // 扫入商品的唯一码匹配到了
      //   console.log('命中qrcode相等');
      //   return i
      // } else if (qrcode && good.sku_no === sku && !good.good_qrcode) {
      //   // 扫入商品的sku匹配到了
      //   console.log('命中qrcode相等(sku命中)');
      //   return i
      // }
      if (good.orderInfo.order_id === order_id && !good.good_qrcode) {
        // 扫入商品的唯一码匹配到了
        console.log('命中qrcode相等');
        return i
      }

      // 记录已经匹配过当前唯一码的商品索引
      if (good.qrcode === qrcode && good.good_qrcode) {
        console.log('记录已经匹配过当前唯一码的商品索引')
        this._qrcodeIsRecorded = true
      }
      return -1
    },

    matchSku(good, i, sku, order_id) {
      // 仅支持唯一码出库
      if (this.supportOnlyQrCodeFlag) {
        console.log('仅支持唯一码出库')
        return -1
      }
      // if (sku && good.sku_no === sku && good.scanInNum === 0) {
      //   console.log('命中sku相等', i);
      //   return i
      // }
      // // 记录已经匹配过当前sku的商品索引
      // if (sku && good.sku_no === sku && good.scanInNum === 1) {
      //   this._scanedSkuIndex = i
      // }
      if (good.orderInfo.order_id === order_id && good.scanInNum === 0) {
        console.log('命中sku相等', i);
        return i
      }
      // 记录已经匹配过当前sku的商品索引
      if (good.orderInfo.order_id === order_id && good.scanInNum === 1) {
        console.log('记录已经匹配过当前sku的商品索引')
        this._scanedSkuIndex = i
      }
      return -1
    },

    matchGbcode(good, i, gbcode, order_id) {
      // 仅支持SKU出库,或者仅支持唯一码出库
      if (this.supportOnlySkuFlag || this.supportOnlyQrCodeFlag) {
        console.log('仅支持SKU出库,或者仅支持唯一码出库')
        return -1
      }
      // if (gbcode && good.gbcode === gbcode && good.scanInNum === 0) {
      //   console.log('命中gbcode相等', i);
      //   return i
      // }
      // // 记录已经匹配过当前gbcode的商品索引
      // if (gbcode && good.gbcode === gbcode && good.scanInNum === 1) {
      //   this._scanedGbcodeIndex = i
      // }
      if (good.orderInfo.order_id === order_id && good.scanInNum === 0) {
        console.log('命中gbcode相等', i);
        return i
      }
      // 记录已经匹配过当前gbcode的商品索引
      if (good.orderInfo.order_id === order_id && good.scanInNum === 1) {
        console.log('记录已经匹配过当前gbcode的商品索引')
        this._scanedGbcodeIndex = i
      }
      return -1
    },

    // 判断扫描商品输入框里输入的是什么值
    getScanType(value, sku, gbcode, qrcode) {
      let type = ''
      // 能扫出商品说明输入的肯定是【唯一码，国标码，sku】之一。
      if (value === qrcode) {
        type = scanType.qrcode
      } else if (value === sku) {
        type = scanType.sku
      } else if (value === gbcode) {
        type = scanType.gbcode
      }
      return type
    },

    // 设置商品列表(只扫商品，没有拣货单)
    addGood(orderInfo, data) {
      // 唯一码
      let qrcode = ''
      if (orderInfo.wareHousingSkuItemVOList) {
        qrcode = orderInfo.wareHousingSkuItemVOList[0].qrcode
      }

      this.skuInfo = {
        tid: orderInfo.tid, // 平台单号
        order_id: orderInfo.id,
        shop_name: orderInfo.orderShopName, // 下单店铺
        platformName: orderInfo.platformName, // 平台
        ship_name: orderInfo.shipperName, // 物流公司
        logistics_number: orderInfo.LOGISTICSNUMBER, // 物流单号
        buyermessage: orderInfo.BUYERMESSAGE, // 买家备注
        sellermemo: orderInfo.SELLERMEMO, // 卖家备注
        insideremark: orderInfo.insideremark, // 内部备注
        wareHouseName: orderInfo.wareHouseName, // 发货仓库
      }
      const sku = {
        pic_url: orderInfo.productImage, // 图片
        title: data.orderItemVOList[0].TITLE, // 标题
        productcode: data.orderItemVOList[0].PRODUCTCODE, // 款号
        sku_no: orderInfo.sku, // sku
        gbcode: data.orderItemVOList[0].GBCODE, // 国标码
        qrcode, // 原唯一码
        good_qrcode: qrcode || '', // 匹配的唯一码
        normsdetailnames: orderInfo.normsDetailName, // 规格
        scanInNum: 1, // 已扫数量
        qty: data.orderItemVOList.find(item=>item.SKU==orderInfo.sku).NUM, //data.orderItemVOList.length, // 应扫数量
        orderInfo: this.skuInfo,
        status: orderInfo.order_status, // 订单状态
        isIntercept: orderInfo.ISINTERCEPT === 1, // 是否拦截
        errorTip: false,
      };


      this.goodList.push(sku)

      if(!this._hasError) {
        // 打印
        this.printGood()
      }

      this.clearAfterScan()
    },

    // 设置商品列表(扫描拣货单时)
    setGoodListFromPick(orderList) {
      // 把每个订单下的sku捞出来
      const list = [];
      this.isOneGoodInOrderFlag = true;

      orderList.forEach(orderData => {
        // 订单不止一个商品
        if (orderData.every_order_item_of_pick_order_list.length > 1) {
          this.isOneGoodInOrderFlag = false;
        }
        orderData.every_order_item_of_pick_order_list.forEach(item => {
          // 商品不止一件
          if (item.num > 1) {
            this.isOneGoodInOrderFlag = false;
          }
          let picUrl = ''
          try {
            picUrl = JSON.parse(item.image)[0].URL
          } catch (e) {
            picUrl = item.image
          }

          const sku = {
            pic_url: picUrl, // 图片
            title: item.product_name, // 标题
            productcode: item.product_code, // 款号
            sku_no: item.sku, // sku
            gbcode: item.gbcode, // 国标码
            qrcode: item.qrcode, // 原唯一码
            good_qrcode: '', // 匹配的唯一码
            normsdetailnames: item.normsdetailnames, // 规格
            scanInNum: orderData.total_already_pick_num, // 已扫数量
            qty: item.num, // 应扫数量
            status: orderData.order_status, // 是否拦截
            isIntercept: item.is_intercept === 1,
            errorTip: false,
            orderInfo: {
              tid: orderData.tid, // 平台单号
              order_id: orderData.order_id,
              shop_name: orderData.shop_name, // 下单店铺
              platformName: orderData.platformName, // 平台
              ship_name: orderData.ship_name, // 物流公司
              logistics_number: orderData.logistics_number, // 物流单号
              buyermessage: orderData.buyermessage, // 买家备注
              sellermemo: orderData.sellermemo, // 卖家备注
              insideremark: orderData.insideremark, // 内部备注
              wareHouseName: orderData.ieswarehouse_name, // 发货仓库
            }
          };
          list.push(sku);
        });
      });
      this.goodList = list;
    },

    // 清空商品输入框
    clearSkuInput() {
      this.inputConfig[1].value = '';
    },

    // 清空单号输入框
    clearOrderInput() {
      this.inputConfig[0].value = '';
    },

    // 顶部栏按钮点击
    onButtonClick(e) {
    },

    // 关闭当前页面打开旧版界面
    closePage() {
      const { fullPath } = this.$route;
      const {
        keepAliveModuleName, tableName
      } = this.$store.state.global.activeTab;
      this.$store.commit('global/tabCloseAppoint', {
        tableName,
        routeFullPath: fullPath,
        keepAliveModuleName,
        stopRouterPush: true,
      });
      // 跳转
      setTimeout(() => {
        R3.store.commit('global/tabOpen', {
          type: 'C',
          customizedModuleName: 'AfterDelivery',
          customizedModuleId: '3323',
          label: '后置打印'
        });
        this.triggerPoint();
      }, 0);
    },

    // 返回旧界面触发埋点
    triggerPoint() {
      network.post('/p/cs/user/bp/4');
    },
  },
};
</script>

<style lang="less" scoped>
.after-delivery {
  margin: 0 -15px;
  height: calc(100% - 80px);
  .overflow {
    height: 100%;
    overflow: auto;
  }
  .back-version {
    color: var(--primary-color);
    display: flex;
    align-items: center;
    cursor: pointer;
    img {
      width: 12px;
    }
    span {
      margin-left: 4px;
      margin-right: 32px;
    }
  }
  .right-panel {
    overflow: auto;
    height: 100%;
  }
}
</style>

<style lang="less">
.after-delivery-pop {
  .customizedPage-print {
    padding: 9px 6px 0;
    .customizedPage-print-li {
      margin-bottom: 12px;
      &:last-of-type {
        margin-bottom: 0;
      }
    }
  }
}
.after-delivery {
  .content {
    padding: 16px;
  }
}
</style>
