<template>
  <div class="out-store">
    <!-- 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
      data-key="SCAN_OUT_PAGE"
      id="audio"
      style="display: none;"
    />

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

    <!-- 打印报错信息 -->
    <printHtml ref="printInfo" />

    <Navbar
      ref="navbar"
      :input-config="inputConfig"
      :button-config="buttonConfig"
      :enable-config="enableConfig"
      :form-config="formConfig"
      :default-config="systemConfig"
      :doc-url="docUrl"
      print-type="scanChuku"
      popper-class="out-store-pop"
      @on-enter="inputEnter"
      @on-button-click="onButtonClick"
    >
      <!-- 顶部右侧图标 -->
      <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"
      >
        <OutStorePanel
          :order-info="orderInfo"
          :scan-num="scanNum"
          :total-num="totalNum"
        />
      </div>
      <!-- 右侧篮子 -->
      <div
        slot="right"
        class="right-panel"
      >
        <div class="good-list">
          <GoodItem
            v-for="(item, index) in goodList"
            :key="index"
            :data="item"
            :index="index"
            :current-index="lastScanIndex"
          />
        </div>
      </div>
    </Layout>

    <!-- 单号核对弹框 -->
    <VerifyModal
      v-model="showVerifyModal"
      :is-scan-logistics="isScanLogistics"
      :order-id="orderId"
      :logistics-id="logisticsId"
      :clear-callback="clearAll"
      :play-error="playError"
      @on-confirm="verifyOk"
    />
  </div>
</template>

<script>
  import Navbar from '../components/navbar.vue';
  import Layout from '../components/layout.vue';
  import OutStorePanel from './outStorePanel.vue';
  import VerifyModal from './VerifyModal.vue';
  import GoodItem from './goodItem.vue';
  import printHtml from '../components/printHtml.vue';

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

  export default {
    name: 'OutStore',

    components: {
      Navbar,
      Layout,
      OutStorePanel,
      GoodItem,
      VerifyModal,
      printHtml,
    },

    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'
          }
        ],
        buttonConfig: [
          {
            description: '强制出库',
            type: '1',
            displayType: 'fcdefault',
            show: true,
          },
        ],
        formConfig: [
          {
            title: '出库完成界面清空',
            name: 'isClear',
            Checkbox: false,
            value: false,
          },
          // {
          //   title: '自动打印物流单',
          //   name: 'autoPrintLogistics',
          //   Checkbox: false,
          //   value: '',
          //   child: [
          //     {
          //       title: '扫描单号后直接打印',
          //       name: '1',
          //       value: false,
          //     },
          //     {
          //       title: '出库完成后打印',
          //       name: '2',
          //       value: false,
          //     },
          //   ]
          // },
          {
            title: '自动打印物流单',
            name: 'autoPrintLogistics',
            Checkbox: false,
            value: false,
          },
          {
            title: '同款同条码提醒',
            name: 'isEnableAlert',
            Checkbox: false,
            value: false,
          },
          {
            title: '核对订单号与物流单号',
            name: 'isVerifyCode',
            Checkbox: false,
            value: false,
          },
          {
            title: '扫描单号自动出库',
            name: 'isAutoOutStore',
            Checkbox: false,
            value: false,
          },
        ],
        systemConfig: {
          isClear: true,
          autoPrintLogistics: false,
          isEnableAlert: false,
          isVerifyCode: false,
          isAutoOutStore: false,
        },
        docUrl: 'https://burgeon.yuque.com/cgmq7t/gndrvn/qvu5qpo7i3d4cs13?singleDoc#',
        goodList: [],
        lastScanIndex: -1, // 最新扫描的商品索引
        isScanLogistics: false, // 扫入的是否是物流单
        orderInfo: {}, // 订单信息
        showContent: false, // 显示扫描结果
        scanError: '', // 扫描失败声音
        goodsAudioUrl: '', // 扫描商品声音
        successAudioUrl: '', // 扫描成功声音
        scanOk: '', // 扫描提示声音
        logisticsAudioUrl: '', // 扫描物流单号声音
        showVerifyModal: false, // 显示校验弹框
        orderId: '', // 订单编号
        logisticsId: '', // 物流单编号
        totalNum: 0, // 应出数量
        scanNum: 0, // 已出数量
        supportOnlySkuFlag: false,
        supportCodeAndSkuFlag: false,
        supportOnlyQrCodeFlag: false,
        isQrcodeScanFlag: false,
        isGBcodeScanFlag: false,
      };
    },

    mounted() {
      setTimeout(() => {
        this.focusOrderInput();
      }, 200);
    },
    created() {
      this.getSystemParams();
      this.getQrCodeConfig();
      this.getPrintSound();
    },

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

    methods: {
      // 获取唯一码策略
      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, this.supportOnlySkuFlag, this.supportCodeAndSkuFlag, this.supportOnlyQrCodeFlag);
          }
        });
      },

      // 播放错误提示音(给子组件回调用的)
      playError() {
        this.playAudio(this.scanError);
      },

      // 恢复初始状态
      clearAll() {
        this.clearPage();
        this.showContent = false;
        this.inputConfig[0].value = '';
      },

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

      // 获取当前设置的系统参数
      getSystemParams() {
        network.post('/p/cs/getSysParams').then(res => {
          if (res.data.code == 0) {
            let allParamsList = [];
            res.data.data.forEach(item => {
              allParamsList = [...allParamsList, ...item.sysParam];
            });
            allParamsList.forEach(param => {
              // 出库完成界面清空
              if (param.paraName == 'IsClearWhenOutstorage') { 
                this.systemConfig.isClear = param.paraValue === 'True' ? true : false;
              }
              // 自动打印物流单
              if (param.paraName == 'autoPickLogistics') { 
                this.systemConfig.autoPrintLogistics = param.paraValue === 'True' ? true : false;
              }
              // 多商品提醒
              if (param.paraName == 'IsNoticeWithSameSku') { 
                this.systemConfig.isEnableAlert = param.paraValue === 'True' ? true : false;
              }
              // 是否核对物流单号和订单号
              if (param.paraName == 'IsCheckLogisticNumberAndOrderId') { 
                this.systemConfig.isVerifyCode = param.paraValue === 'True' ? true : false;
              }
              // 扫描单号自动出库
              if (param.paraName == 'isAutoScanOutByLogisticsNo') { 
                this.systemConfig.isAutoOutStore = param.paraValue === 'True' ? true : false;
              }
            });
            console.log('系统配置', this.systemConfig);
          }
        });
      },

      // 获取打印音效
      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.goodsAudioUrl = row.URL.val;
            } else if (row.TYPE_NAME.val == '失败') {
              this.scanError = row.URL.val;
            } else if (row.TYPE_NAME.val == '成功') {
              this.successAudioUrl = row.URL.val;
            } else if (row.TYPE_NAME.val == '扫描物流') {
              this.logisticsAudioUrl = row.URL.val;
            } else if (row.TYPE_NAME.val == '提示') {
              this.scanOk = 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) {
          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.logFn();
        this.showLoading();
        if (colname === 'orderNo') {
          if (!value) {
            this.$Message.warning('请先扫入单号！');
            this.hideLoading();
            return;
          }
          this.lastScanIndex = -1; // 重置最新扫描商品索引
          this.scanOrderNo(value);
        } else {
          if (!this.inputConfig[0].value) {
            this.playAudio(this.scanError);
            this.$Message.warning('请先扫入单号！');
            this.focusOrderInput();
            this.hideLoading();
            return;
          }
          if (!value) {
            this.$Message.warning('商品sku/国标码/唯一码，不能为空！');
            this.hideLoading();
            return;
          }
          this.lastScanIndex = -1; // 重置最新扫描商品索引
          this.scanGood(value);
        }
      },

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

      // 扫描单号
      scanOrderNo(value) {
        this.clearPage();
        network.post('/p/cs/getOrderInfo/auto', {
          bizId: value,
          normsType: 1,
          searchTypes: [1, 2]
        }).then(res => {
          if (res.data.Code === '0') {
            this.hideLoading();
            const data = res.data.Rows;
            this._orderData = data.Table[0]; // 订单数据
            // this._skuData = data.Table1; // 商品数据
            // 商品数据
            this._skuData = [];
            data.Table1.forEach(item => {
              const sameSku = this._skuData.find(row => row.SKU === item.SKU);
              if (sameSku) {
                sameSku.NUM += item.NUM;
              } else {
                this._skuData.push(item);
              }
            });
            this.isScanLogistics = res.data.searchType !== 1; // 是否是物流单
            this.playAudio(this.logisticsAudioUrl);
            this.orderId = this._orderData.ID; // 订单编号
            this.logisticsId = this._orderData.LOGISTICSNUMBER; // 物流单编号
            const orderStatus = this._orderData.ORDERSTATUS; // 是否是审核订单
            const isIntercept = this._orderData.ISINTERECEPT === 1; // 是否被拦截
            console.log('🚀 ~ file: index.vue:352 ~ scanOrderNo ~ data:', data, orderStatus);
            // 检测订单状态
            if (!this.validateOrderPass(orderStatus, isIntercept)) {
              return;
            }

            // 已审核提示
            if (orderStatus === 3) {
              this.playAudio(this.scanOk);
              this.$Modal.fcWarning({
                title: '警告',
                mask: true,
                showCancel: true,
                content: '订单状态为已审核，是否继续？',
                onOk: () => {
                  // 是否弹出单号核对
                  // 扫订单号，但是物流单没有也不弹
                  if (this.systemConfig.isVerifyCode && this.logisticsId) {
                    this.showVerifyModal = true;
                  } else {
                    this.getPageData();
                  }
                },
                onCancel: () => {
                  this.clearAll();
                }
              });
              return;
            }

            // 是否弹出单号核对
            // 扫订单号，但是物流单没有也不弹
            if (this.systemConfig.isVerifyCode && this.logisticsId) {
              this.showVerifyModal = true;
            } else {
              this.getPageData();
            }
          } else {
            this.inputConfig[0].value = '';
            // 场景：找不到相关单据
            this.playAudio(this.scanError);
            this.hideLoading();
            this.$Message.error({
              content: res.data.Message,
              duration: 3
            });
          }
        });
      },

      // 1 : 未确认
      // 2 : 缺货
      // 3 ：已审核
      // 4 ：配货中
      // 5 ：仓库发货
      // 6 ：平台发货
      // 7 ：已取消
      // 8 ：系统作废
      // 9 ：预售
      // 10：代发
      // 11：物流已送达
      // 12：交易完成
      // 13：未付款
      // 21：传wms中
      // 50：待分配
      // 51：预售待发货
      // 52：预售缺货
      // 校验订单状态
      validateOrderPass(orderStatus, isIntercept) {
        if (orderStatus === 7 || orderStatus === 8 || isIntercept) {
          this.playAudio(this.scanError);
          this.$Message.error({
            content: '订单在拦截中/已取消/已作废，不可出库！',
            duration: 3
          });
          return false;
        }
        if (orderStatus === 5 || orderStatus === 6) {
          this.playAudio(this.scanError);
          this.$Message.error({
            content: '订单已发货！',
            duration: 3
          });
          return false;
        }

        if ([1, 2, 21, 50].includes(orderStatus)) {
          this.playAudio(this.scanError);
          this.$Message.error({
            content: '订单状态不是已审核/配货中，不可操作！',
            duration: 3
          });
          return false;
        }
        return true;
      },

      // 校验成功
      verifyOk() {
        this.playAudio(this.scanOk);
        this.getPageData();
      },

      // 获取界面数据
      getPageData() {
        // 物流单不存在
        if (!this.logisticsId && !this.systemConfig.autoPrintLogistics) {
          this.showContent = false;
          this.$Message.error({
            content: '订单尚未获取物流，不能直接出库！',
            duration: 3
          });
          return;
        }
        this.focusSkuInput();
        const orderData = this._orderData;
        const skuList = this._skuData;
        // 填充订单信息
        this.setOrderInfo(orderData);

        // 设置商品列表
        this.setGoodList(skuList);

        this.showContent = true;

        // 判断是否自动打印物流单
        if (this.systemConfig.autoPrintLogistics) {
          this.print();
        }

        // 判断是否扫描单号自动出库
        if (this.systemConfig.isAutoOutStore) {
          this.autoOutStore();
        }
      },

      // 自动出库
      autoOutStore() {
        const list = [];
        this.goodList.forEach(item => {
          this.scanNum += item.qty;
          item.scanInNum = item.qty;
          // 有多个唯一码时，需要拆分
          if (item.good_qrcode) {
            const codeList = item.good_qrcode.split(';');
            codeList.forEach(qrcode => {
              const obj = {
                sku: item.sku_no,
                qrcode,
              };
              list.push(obj);
            });
          } else {
            const obj = {
              sku: item.sku_no,
              qrcode: item.good_qrcode,
            };
            list.push(obj);
          }
        });
        this.outStore(list);
      },

      // 设置商品信息
      setOrderInfo(data) {
        this.orderInfo = {
          ORDERSHOPNAME: data.ORDERSHOPNAME, // 下单店铺
          ID: data.ID, // 订单编号
          SOURCECODE: data.SOURCECODE, // 平台单号
          PAYTIME: data.PAYTIME, // 支付时间
          ORDERDATE: data.ORDERDATE, // 下单时间
          LOGISTICSNUMBER: data.LOGISTICSNUMBER, // 物流单号
          NAME: data.NAME, // 物流公司
          WEIGHT: data.WEIGHT, // 重量
          ADDRESS: data.RECEIVPROVINCENAME + data.RECEIVCITYNAME + data.RECEIVAREANAME + data.RECEIVADDRESS, // 解密地址
          BUYERMESSAGE: data.BUYERMESSAGE, // 买家备注
          SELLERMEMO: data.SELLERMEMO, // 卖家备注
          INSIDEREMARK: data.INSIDEREMARK, // 内部备注
          PLATFORMNAME: data.PLATFORMNAME, // 平台名称
        };
      },

      // 设置sku列表
      setGoodList(data) {
        this.totalNum = 0;
        this.goodList = data.map(item => {
          this.totalNum += item.NUM;
          let picUrl = '';
          try {
            picUrl = JSON.parse(item.PICPATH)[0].URL;
          } catch {
            picUrl = item.PICPATH;
          }
          return {
            pic_url: picUrl, // 图片
            title: item.TITLE, // 平台商品名称
            systitle: item.SYSTITLE, // 系统商品名称
            productcode: item.PRODUCTCODE, // 款号
            sku_no: item.SKU, // sku
            gbcode: item.GBCODE, // 国标码
            qrcode: item.QRCODE, // 原唯一码
            good_qrcode: '', // 匹配的唯一码
            normsdetailnames: item.SKUSPEC, // 规格
            scanInNum: 0, // 已扫数量
            qty: item.NUM, // 应扫数量
            isGift: item.ISGIFT, // 是否是赠品
          };
        });
      },

      // 扫描商品
      scanGood(value) {
        network.post('/p/cs/out_of_stock/query/sku', {
          sku: value,
          ORDER_ID: this.orderInfo.ID
        }).then(res => {
          if (res.data.code === 0 && res.data.message === 'success') {
            this.playAudio(this.goodsAudioUrl);
            const data = res.data.data;

            this.isGBcodeScanFlag = false;
            this.isQrcodeScanFlag = false; // 重置标记。用于标记扫描商品输入框扫的是否是唯一码。录入唯一码时用到
            let qrcode = '';
            let hasAbnormalQrcode = false; // 是否存在售出的唯一码
            if (data.wareHousingSkuItemVOList && data.wareHousingSkuItemVOList.length > 0) {
              qrcode = data.wareHousingSkuItemVOList[0].qrcode;
              if(qrcode){
                // 唯一码会被截取
                this.isQrcodeScanFlag = true;
              }else{
                this.isQrcodeScanFlag = false;
              }
              if (qrcode === value) {
                this.isQrcodeScanFlag = true;
                if (data.wareHousingSkuItemVOList[0].qrcodeStatus == 3) {
                  hasAbnormalQrcode = true;
                }
              } else {
                // this.isQrcodeScanFlag = false;
              }
            }
            // 扫描的是国标标
            if (value === data.GBCODE) {
              this.isGBcodeScanFlag = true;
            }

            if (this.isQrcodeScanFlag && hasAbnormalQrcode) {
              this.$Modal.fcWarning({
                title: '警告',
                mask: true,
                showCancel: true,
                content: '该唯一码已售出，请确认是否要继续出库？',
                onOk: () => {
                  this.matchGood(data.SKU, data.GBCODE, qrcode);
                  this.hideLoading();
                },
                onCancel: () => {
                  this.hideLoading();
                }
              });
            } else {
              this.matchGood(data.SKU, data.GBCODE, qrcode);
            }

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

      // 获取匹配索引
      getMatchIndex(sku, gbcode, qrcode) {
        console.log('🚀 ~ file: index.vue:607 ~ getMatchIndex ~ sku, gbcode, qrcode:', sku, gbcode, qrcode);
        let matchIndex = -1; // 记录匹配到到商品索引
        for (let i = 0; i < this.goodList.length; i++) {
          const good = this.goodList[i];
          if (this.supportCodeAndSkuFlag || this.supportOnlyQrCodeFlag) {
            // 商品可能有多个唯一码(每件商品一个码)
            let goodQrCodeList = [];
            if (good.good_qrcode) {
              goodQrCodeList = good.good_qrcode.split(';');
            }
            if (qrcode && goodQrCodeList.includes(qrcode)) {
              console.log('已录入过qrcode相等');
              return -2;
            }
            // 没有录入过唯一码  扫描次数超出购买数量，但是商品已扫描完毕订单出库
            let qrCodeList = [];
            if (good.qrcode) {
              qrCodeList = good.qrcode.split(';');
            }
            if (qrcode && qrCodeList.includes(qrcode)) {
              console.log('命中唯一码相等');
              matchIndex = i;
              return matchIndex;
            }
          }

          // 特殊情况，仅唯一码时，也可以通过扫入商品的sku匹配
          if (this.supportOnlySkuFlag || this.supportCodeAndSkuFlag || this.supportOnlyQrCodeFlag) {
            if (sku && good.sku_no === sku) {
              console.log('命中sku相等');
              matchIndex = i;
              return matchIndex;
            }
          }

          if (!this.supportOnlySkuFlag && !this.supportOnlyQrCodeFlag) {
            if (gbcode && good.gbcode === gbcode && this.isGBcodeScanFlag) {
              if (good.scanInNum !== good.qty) {
                console.log('命中gbcode相等');
                matchIndex = i;
                return matchIndex;
              }
              // 扫满的要继续扫，因为gbcode可能有相同的
              console.log('命中gbcode相等，扫满了');
              matchIndex = i;
            }
          }
        }
        return matchIndex;
      },

      // 匹配扫描商品
      matchGood(sku, gbcode, qrcode) {
        // 获取唯一码策略
        this.getQrCodeConfig();

        const matchIndex = this.getMatchIndex(sku, gbcode, qrcode); // 匹配到到商品索引

        // 扫描商品不在列表里时
        if (matchIndex === -1) {
          this.inputConfig[1].value = '';
          this.playAudio(this.scanError);
          this.$Message.warning('商品中不存在此条码');
        } else if (matchIndex === -2) {
          // 唯一码匹配过
          this.playAudio(this.scanError);
          this.$Message.warning('该唯一码已匹配，请勿重复扫描！');
        } else if (this.goodList[matchIndex].scanInNum === this.goodList[matchIndex].qty) {
          // 商品重复扫描
          this.playAudio(this.scanError);
          this.$Message.warning('商品已出库，请勿重复扫描！');
        } else {
          console.log('匹配索引', matchIndex);
          const currentGood = this.goodList[matchIndex];

          // 同款同条码提醒
          // 开启后，每个商品只弹一次提醒，如果用户同意全部匹配则，则自动扫满该商品
          if (this.systemConfig.isEnableAlert && currentGood.qty > 1 && !currentGood.hasAlertFlag) {
            this.$Modal.fcWarning({
              title: '警告',
              mask: true,
              showCancel: true,
              content: `该订单共有${currentGood.qty}件sku商品，是否全部匹配出库？`,
              onOk: () => {
                // 标记这个商品已经弹框提示框
                currentGood.hasAlertFlag = true;
                currentGood.scanInNum = currentGood.qty;
                this.scanNum += currentGood.qty;
                this.updateGood(matchIndex, qrcode);
              },
              onCancel: () => {
                // 标记这个商品已经弹框提示框
                currentGood.hasAlertFlag = true;
              }
            });
            return;
          }
          currentGood.scanInNum++;
          this.scanNum++;
          this.updateGood(matchIndex, qrcode);
        }
      },

      updateGood(matchIndex, qrcode) {
        const currentGood = this.goodList[matchIndex];
        this.goodList.splice(matchIndex, 1);
        this.goodList.unshift(currentGood);
        this.sortGoodList(currentGood);
        this.lastScanIndex = 0;
        this.clearSkuInput();
        console.log('是否展示唯一码', this.isQrcodeScanFlag, (this.supportCodeAndSkuFlag || this.supportOnlyQrCodeFlag), qrcode);
        // 是否展示唯一码
        if (this.isQrcodeScanFlag && (this.supportCodeAndSkuFlag || this.supportOnlyQrCodeFlag)) {
          if (currentGood.good_qrcode) {
            const qrcodeList = currentGood.good_qrcode.split(';');
            qrcodeList.push(qrcode);
            currentGood.good_qrcode = qrcodeList.join(';');
          } else {
            currentGood.good_qrcode = qrcode;
          }
        }
        // 商品全部扫满时，触发出库
        if (this.isAllScanned()) {
          const list = [];
          this.goodList.forEach(item => {
            if (item.scanInNum === item.qty) {
              if (item.good_qrcode) {
                const codeList = item.good_qrcode.split(';');
                codeList.forEach(qrcode => {
                  const obj = {
                    sku: item.sku_no,
                    qrcode,
                  };
                  list.push(obj);
                });
              } else {
                const obj = {
                  sku: item.sku_no,
                  qrcode: item.good_qrcode,
                };
                list.push(obj);
              }
            }
          });
          this.outStore(list);
        }
      },

      // 出库
      outStore(skuList, isForce) {
        const params = {
          orderId: this.orderInfo.ID.toString(),
        };
        if (isForce) {
          params.scanForcedOutProducts = skuList;
        } else {
          params.scanOutOfStockItemDTOList = skuList;
        }

        let url = '/p/cs/scan_out_of_stock';
        if (isForce) {
          url = '/p/cs/orderForcedOut';
        }
        network.post(url, params).then(res => {
          if (res.data.code == 0) {
            this.playAudio(this.successAudioUrl);
            this.clearOrderInput();
            // 判断是否自动打印物流单
            // if (this.systemConfig.autoPrintLogistics === '2') {
            //   this.print();
            // }
            if (this.systemConfig.isClear) {
              this.clearPage();
              this.showContent = false;
            }
            this.focusOrderInput();
            this.$Message.success('出库成功!');
          } else {
            this.playAudio(this.scanError);
          }
        });
        this.logFn();
      },

      // 打印物流单
      print() {
        const data = {
          wuliu: {
            ids: [this.orderInfo.ID],
          },
        };
        console.log('🚀 ~ 打印参数', data);
        this.logFn(data);
        this.$refs.navbar.$refs.config.print(data);
      },

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

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

      // 检测订单是否扫描完成
      isAllScanned() {
        const flag = this.goodList.every(item => item.scanInNum === item.qty);
        return flag;
      },

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

      // 顶部栏按钮点击
      onButtonClick(e) {
        // 强制入库
        if (e.type === '1') {
          this.forceOutStore();
        }
      },


      // 强制出库：把扫满的都出库
      forceOutStore() {
        const list = [];
        const skuList = [];
        this.goodList.forEach(item => {
          if (item.scanInNum > 0) {
            const qrcode = item.good_qrcode ? item.good_qrcode.replace(/;/g, ',') : item.good_qrcode;
            const obj = {
              sku: item.sku_no,
              qrcode,
              isGift: item.isGift,
              outNum: item.scanInNum
            };
            list.push({
              ...obj
            });
            skuList.push(obj);
          }
        });
        // 先检测用户是否开启允许强制出库
        network.post('/p/cs/checkOrderForcedOut', {
          orderId: this.orderInfo.ID.toString(),
          scanForcedOutProducts: list
        }).then(res => {
          if (res.data.code === 0) {
            this.outStore(skuList, true);
          } else if (res.data.code === 10) {
            this.$Modal.fcWarning({
              title: '警告',
              mask: true,
              showCancel: true,
              content: res.data.message,
              onOk: () => {
                this.outStore(skuList, true);
              },
              onCancel: () => {
              }
            });
          }
        });
      },

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

      // 关闭当前页面打开旧版界面
      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: 'OUTSTORE',
            customizedModuleId: '2207',
            label: '扫描出库'
          });
          this.triggerPoint();
        }, 0);
      },

      // 返回旧界面触发埋点
      triggerPoint() {
        network.post('/p/cs/user/bp/3');
      },
      logFn(data){
         // 日志
         const logObj = {
          LOG_ID: 2,
          LOG_OPERATOR: `PRINT_FROM_ScanningOutbound`,
          LOG_INFO: {
            F_defaultConfig: data || this.systemConfig,
            F_supportchuku:{
              supportOnlySkuFlag:`仅支持SKU出库${this.supportOnlySkuFlag}`,
              supportCodeAndSkuFlag:`支持唯一码/SKU出库${this.supportCodeAndSkuFlag}`,
              supportOnlyQrCodeFlag:`仅支持唯一码出库${this.supportOnlyQrCodeFlag}`,
            }
          },
        }
        this.$comUtils.globalSaveOperateLogFn(logObj);
      }
    },
  };
</script>

<style lang="less" scoped>
.out-store {
  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">
.out-store-pop {
  .customizedPage-print {
    padding: 9px 6px 0;
    .customizedPage-print-li {
      margin-bottom: 12px;
      &:last-of-type {
        margin-bottom: 0;
      }
    }
  }
}
.out-store {
  .content {
    padding: 16px;
  }
}
</style>
