<template>
  <div class="in-store" data-key="NEW_SCAN_IN">
    <!-- loading -->
    <Spin
      v-show="isLoading"
      id="ruku-loading"
      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;"
    />

    <Navbar
      ref="navbar"
      from-type="NEW_SCAN_IN"
      :all-user-default-storage="allUserDefaultStorage"
      :all-user-physical-storage="allUserPhysicalStorage"
      :input-config="inputConfig"
      :button-config="buttonConfig"
      :enable-config="enableConfig"
      :form-config="formConfig"
      :default-config="defaultConfig"
      :doc-url="docUrl"
      :print-type="printType"
      :allStoreCanBeModify="allStoreCanBeModify"
      popper-class="in-store-pop"
      @on-enter="inputEnter"
      @on-button-click="onButtonClick"
      @openStoreModal="openStoreModal"
    >
    <!-- @onPrintChangeOne="onPrintChangeOne" -->
      <!-- 输入框左侧图标 -->
      <template #prepend-input="slotProps">
        <Tooltip
          placement="top"
          transfer
          max-width="230"
          content="支持扫描退货物流单号、退单编号、原订单编号、原订单平台单号；强制入库功能只支持按物流单号扫描。"
        >
          <Icon
            v-if="slotProps.colname === 'orderNo'"
            style="color: var(--primary-color);vertical-align: -2px;"
            type="md-information-circle"
          />
        </Tooltip>
      </template>
      <!-- 顶部右侧图标 -->
      <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 || isAbnormalOrder">
      <!-- 左侧订单信息 -->
      <div
        slot="left"
        class="overflow left-panel"
      >
        <InStorePanel
          ref="leftPanel"
          :open-store-type='openStoreType'
          :user-default-storage="userDefaultStorage"
          :user-physical-storage="userPhysicalStorage"
          :all-user-physical-storage="allUserPhysicalStorage"
          :all-user-default-storage="allUserDefaultStorage"
          :allStoreCanBeModify="allStoreCanBeModify"
          :order-info="orderInfo"
          :scan-num="scanNum"
          :total-num="totalNum"
          :color-tags="colorTags"
          :is-abnormal-order="isAbnormalOrder"
          :refund-batch-id-list="refundBatchIdList"
          :ISUSERETURNBATCHMANAGEMENT="ISUSERETURNBATCHMANAGEMENT"
          @on-confirm="onConfirmStore"
          @on-confirm-color="onConfirmColor"
          @on-confirm-logisticse="onConfirmLogisticse"
          @on-confirm-remark="onConfirmremark"
          @on-change-refundbatch="onChangeRefundBatch"
        ></InStorePanel>
      </div>
      <!-- 右侧篮子 -->
      <div
        slot="right"
        class="right-panel"
      >
        <div class="good-list">
          <!-- <virtual-list :size="2000" :remain="10"> -->
            <div v-if="goodList.length < 100">
              <GoodItem
                v-for="(item, index) in goodList"
                :key="index"
                :data="item"
                :index="index"
                :current-index="lastScanIndex"
                :defectiveReasonList = 'defectiveReasonList'
                @changeProductRemark = 'changeProductRemark'
              />
            </div>
            <div v-else>
              <arkCommonTableByAgGrid
              ref="ag"
              :height="`${tableHeightOne}px`"
              :columns="agColumns"
              :border="false"
              :data="goodList"
              :renderParams="agRenderParams"
              :options="{
                rowHeight: 100
              }"
              class="scanningInTable"></arkCommonTableByAgGrid>
            </div>
          <!-- </virtual-list> -->
        </div>
      </div>
    </Layout>
  </div>
</template>

<script>
  import dayjs from 'dayjs';
  import cloneDeep from 'lodash/cloneDeep';
  import Navbar from '../components/navbar.vue';
  import Layout from '../components/layout.vue';
  import InStorePanel from './inStorePanel.vue';
  import GoodItem from './goodItem.vue';
  // 添加lodash debounce
  import debounce from 'lodash/debounce';
  
  // import VirtualList from 'vue-virtual-scroll-list'

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

  export default {
    name: 'InStore',

    components: {
      Navbar,
      Layout,
      InStorePanel,
      GoodItem,
    },

    data() {
      return {
        isLoading: false, // 是否显示loading
        inputConfig: [
          {
            label: '扫描单号',
            placeholder: '物流单号/退单编号/订单编号/平台单号',
            icon: 'ios-clock-outline-saoma',
            colname: 'orderNo',
            value: '',
            'element-id': 'order-input',
            class: 'order-input-wrap',
            width: '250px'
          },
          {
            label: '扫描商品',
            placeholder: '商品sku/国标码/唯一码',
            icon: 'ios-clock-outline-saoma',
            colname: 'skuNo',
            value: '',
            'element-id': 'sku-input',
            width: '250px'
          }
        ],
        buttonConfig: [

          {
            description: '强制入库',
            type: '1',
            displayType: 'fcdefault',
            show: false,
          },
          {
            description: '自动匹配',
            type: '2',
            displayType: 'fcdefault',
            disabled: true,
            show: false,
            content: '操作后系统会自动将退单商品的已退数量更新为应退数量并自动入库完成'
          },
        ],
        formConfig: [
          {
            title: '扫描完成自动提交',
            name: 'isAutoScanInFinishAutoCommit',
          },
          {
            title: '默认商品类型',
            name: 'goodType',
            type: 'select',
            Checkbox: false,
            value: '1',
            disabled: false,
            child: [
              {
                title: '正品',
                name: '1',
                value: false,
              },
              {
                title: '瑕疵品',
                name: '2',
                value: false,
              },
              {
                title: '残次品',
                name: '3',
                value: false,
              }
            ]

          },
        ],
        defaultConfig: {
          // clear: false,
          isAutoScanInFinishAutoCommit: false,
        },
        docUrl: 'https://burgeon.yuque.com/cgmq7t/gndrvn/rraedvnnt1tobhyt?singleDoc#', // 语雀文档
        scanError: '', // 扫描失败声音
        goodsAudioUrl: '', // 扫描商品声音
        scanOk: '', // 提示声音
        successAudioUrl: '', // 入库成功声音
        logisticsAudioUrl: '', // 扫描物流单号声音
        isStoreToDefaultFlag: false, // 扫描入库退回至店铺默认退货仓
        moneyForceFlag: false, // 串款是否允许强制入库
        unMatchTipFlag: false, // 扫描入库匹配不到售后单是否提示
        numForceFlag: false, // 	扫描入库数量不一致是否允许强制入库
        supportOnlySkuFlag: false, // 仅支持SKU入库
        supportUniqueCodeFlag: false, // 仅支持唯一码入库
        supportCodeAndSkuFlag: false, // 是否开启支持唯一码/sku入库
        supportCodeInStoreFlag: false, // 仅支持退单/订单中商品唯一码入库
        isReturnOrderFlag: false, // 扫描单号是否是退货单
        ISUSERETURNBATCHMANAGEMENT: false, // 默认不使用退货批次管理
        isQrcodeFlag: false, // 订单明细中商品是否唯一码管控
        orderInfo: {}, // 订单信息
        goodList: [], // 商品列表
        userPhysicalStorage: {
          value: '',
          label: ''
        }, // 用户的实体仓
        userDefaultStorage: {
          value: '',
          label: ''
        }, // 用户的默认仓
        allUserPhysicalStorage: {
          value: '',
          label: ''
        }, // 所有单据的实体仓
        allUserDefaultStorage: {
          value: '',
          label: ''
        }, // 所有单据的默认仓
        // returnGoodsNum: 0, // 退货商品数量
        scanNum: 0, // 扫描数量
        totalNum: 0, // 应入数量
        scanGoodInfo: {}, // 扫描商品的信息
        colorTags: [], // 颜色标签
        warehouseReceiptRemark: '', // 入库单备注
        showContent: false, // 显示内容
        initColors: [], // 缓存用户订单的颜色
        lastScanIndex: -1, // 记录最新扫描商品的索引
        isAbnormalOrder: false, // 是否是三无入库单
        localPhysicalStorage: {
          value: '',
          label: ''
        },
        localDefaultStorage: {
          value: '',
          label: ''
        },
        isQrcodeScanFlag: false, // 标记扫描商品输入框扫的是否是唯一码
        pagetype: 'inStore',
        openStoreType: '',
        defectiveReasonList: [], // 次品原因数据
        printType: '',
        allStoreCanBeModify: true,//默认仓库是否可更改
        refundBatchIdList: [], // 退货批次数据
        getieswarehousebyrefundbatch: {},
        getreturnstorebyrefundbatch: {},

        scanOrderNoText:'', // 扫描单号暂存
        linkGoodsColumns: [
          {
            title: '商品图片',
            key: 'pic_url',
            width: 100,
            render: (h,params) => {
              return h(
                'img',
                {
                  attrs: {
                    src: params.row.pic_url?params.row.pic_url:'../../../static/img/camera.jpg',
                  },
                  style: {
                    height: '68px',
                    width: '68px',
                    verticalAlign: 'middle',
                    marginTop: '-6px',
                  },
                  on: {
                    mouseover: (e) => {
                      const value = params.row.pic_url
                      var img=document.createElement("img");
                      img.id='previewImg'
                      img.src=value?value:'../../../static/img/camera.jpg'
                      img.style.height='200px'
                      img.style.width='200px'
                      img.style.position='fixed'
                      img.style.zIndex='999'

                      const windowHeight = $(window).height();
                      const scrollTop = $(window).scrollTop();
                      img.style.bottom = 10 + windowHeight - scrollTop -  $(e.target).offset().top + 'px'
                      img.style.left= -30 + $(e.target).offset().left + 'px'
                      $('body').append(img)
                    },
                    mouseout: () => {
                      $("#previewImg").remove();
                    }
                  },
                },
              );
            }
          },
          {
            title: '商品名称',
            key: 'title',
            tooltip: true,
            width: 300,
          },
          {
            title: '商品SKU',
            key: 'sku_no'
          },
          {
            title: '国标码',
            key: 'gbcode',
          },
          {
            title: '商品标记',
            align: 'right',
            key: 'productRemark',
            width: 180,
            render: (h, params) => {
              const vm = this;
              return h('Select', {
                         style: {
                           zIndex: 999
                         },
                         props: {
                           transfer: true,
                           value: params.row.productRemark, // 获取选择的下拉框的值
                         },
                         on: {
                           'on-change': (e) => {
                            console.log(e)
                            //  vm.linkGoodsData[params.index].productRemark = e;
                           }
                         }
                       },
                       vm.markOptions.map(item => h('Option', {
                         props: {
                           value: item.value, // 绑定的值
                         }
                       }, item.name)));
            }
          },
          {
            title: '扫描数量',
            key: 'scanInNum',
            width: 80
          },
        ], // 扫描商品表格表头
        tableHeightOne: 560,

        markOptions: [ // 商品标记
          {
            name: '正品',
            value: 1
          },
          {
            name: '瑕疵品',
            value: 2
          },

          {
            name: '残次品',
            value: 3
          }
        ],

        showForcePower: false, // 强制入库按钮权限
        showAutoPower: false, // 自动匹配按钮权限
        focusInputId: null,// 当前enter得输入框ID
        allParamsArr: [], // log使用
        qrCodeContrlData: [], // log使用
        oriwarehouseid:'', // 订单原发货仓id

      };
    },

    computed: {
      // 是否允许用户设置配置
      enableConfig() {
        return !this.isAbnormalOrder;
      },
      agColumns() {
        const columns = this.linkGoodsColumns.map(item => {
          return {
            ...item,
            field: item.key,
            headerName: item.title,
            suppressMenu: true,
            tdAlign: item.key=='productRemark'?'center':item.key=='scanInNum'?'center':'left'
          }
        })
        return columns
      }
    },
    activated(){
      this.getPermission('force'); // 获取强制入库的功能权限
      this.getPermission('auto'); // 获取自动匹配的功能权限
      this.getSystemParams();
      this.getUniqueCodeConfig();

    },
    created() {
      console.log('created');
      this.getPermission('force'); // 获取强制入库的功能权限
      this.getPermission('auto'); // 获取自动匹配的功能权限
      this.getSystemParams();
      this.getUniqueCodeConfig();

    },
    created() {
      this.getPermission('force'); // 获取强制入库的功能权限
      this.getPermission('auto'); // 获取自动匹配的功能权限
      // 系统参数
      this.getSystemParams();
      // 获取用户选择仓
      this.getUserStore();
      // 获取唯一码策略
      this.getUniqueCodeConfig();
      // 获取打印音效
      this.getPrintSound();
      this.getDefectiveReasonList();
      // 初始化防抖方法
      this.debouncedChangeProductRemark = debounce(this._changeProductRemark, 20);
    },

    mounted() {
      setTimeout(() => {
        this.inputFocus('order-input');
      }, 200);
    },

    methods: {
      getPermission(type){
        let params = {
          AD_ACTION_NAME: '扫描入库',//"强制入库",  //"自动匹配",
        }
        network.post('/p/cs/fetchActionsInCustomizePage',params).then(res => {
          if (res.data.code === 0) {
            const result = res.data.data;
            if(result.length > 0){
              result.forEach((item) => {
                if(item.webid == '4036'){
                  this.showForcePower = res.data.data
                  this.buttonConfig.find(item=>item.type=='1').show = res.data.data
                }else if(item.webid == '4037') {
                  this.showAutoPower = res.data.data
                  this.buttonConfig.find(item=>item.type=='2').show = res.data.data
                }
              })
            }
          }
        })
        // if(type == 'force') {
        //   let params = {
        //     "ad_table_id": 0,
        //     "ad_action_id": 4036
        //   }
        //   network.post('/p/cs/group/have/permission', params).then((res) => {
        //     if(res.data.code == 0){
        //       this.showForcePower = res.data.data
        //       this.buttonConfig.find(item=>item.type=='1').show = res.data.data
        //     }
        //   })
        // }else if(type == 'auto'){
        //   let params = {
        //     "ad_table_id": 0,
        //     "ad_action_id": 4037
        //   }
        //   network.post('/p/cs/group/have/permission', params).then((res) => {
        //     if(res.data.code == 0){
        //       this.showAutoPower = res.data.data
        //       this.buttonConfig.find(item=>item.type=='2').show = res.data.data
        //     }
        //   })
        // }
      },
      agRenderParams(cellData) {
        let renderComponent = null
        if (cellData.field === 'pic_url') {
          renderComponent = {
              renderContainer: 'CellRenderByFunction', // 设置渲染方式为render函数
              renderComponent: (h,params) => {
                return h(
                  'img',
                  {
                    attrs: {
                      src: params.row.pic_url?params.row.pic_url:'../../../static/img/camera.jpg',
                    },
                    style: {
                      height: '68px',
                      width: '68px',
                      verticalAlign: 'middle',
                      marginTop: '-6px',
                    },
                    on: {
                      mouseover: (e) => {
                        const value = params.row.pic_url
                        var img=document.createElement("img");
                        img.id='previewImg'
                        img.src=value?value:'../../../static/img/camera.jpg'
                        img.style.height='200px'
                        img.style.width='200px'
                        img.style.position='fixed'
                        img.style.zIndex='999'

                        const windowHeight = $(window).height();
                        const scrollTop = $(window).scrollTop();
                        img.style.bottom = 10 + windowHeight - scrollTop -  $(e.target).offset().top + 'px'
                        img.style.left= -30 + $(e.target).offset().left + 'px'
                        $('body').append(img)
                      },
                      mouseout: () => {
                        $("#previewImg").remove();
                      }
                    },
                  },
                );
              }
          }
        }
        if(cellData.field === 'stoInQrcode') {
          renderComponent = {
            renderContainer: 'CellRenderByFunction',
            renderComponent: (h,params) => {
              return h(
                'div',
                {
                  style: {
                    color: params.row.stoInQrcodeColor == 'green'?'green':'orange'
                  },
                },
                [params.row.stoInQrcode]
              );
            }
          }
        }
        if (cellData.field === 'productRemark') {
          renderComponent = {
            renderContainer: 'CellRenderByFunction',
            renderComponent: (h,params) => {
              const vm = this;
              return h(
                'div',{
                  style: {
                    display: params.row.productRemark != 1?'':'flex',
                    alignItems:params.row.productRemark != 1?'':'center',
                    height: params.row.productRemark != 1?'':'80px',
                    marginLeft: params.row.productRemark == 1?'72px':'0px',
                  }
                },[
                  h('Select', {
                    style: {
                      zIndex: 999,
                      display: 'flex',
                      justifyContent: 'flex-end',
                      marginTop: '18px',
                      width: '180px',
                      marginLeft: '-17px'
                    },
                    props: {
                      transfer: true,
                      value: params.row.productRemark, // 获取选择的下拉框的值
                    },
                    on: {
                      'on-change': (e) => {
                        vm.goodList[params.index].productRemark = e;
                        const obj = { itemSku: params.row.sku_no || "", type: 'HANDLE_ROW2' }
                        this.changeProductRemark(obj)
                        //  vm.linkGoodsData[params.index].productRemark = e;
                      }
                    }
                  }, 
                  vm.markOptions.map(item => h('Option', {
                    props: {
                      value: item.value, // 绑定的值
                    }
                  }, item.name))),
                  h('div',{
                    style: {
                      display: 'flex',
                      justifyContent: 'center',
                      alignItems: 'center',
                      height: '30px',
                      visibility: params.row.productRemark != 1?'visible':'hidden'
                    },
                  },[
                    h('span', {
                      style: {
                        marginTop: '10px'
                      }
                    },['次品原因：']),
                    h('Select', {
                      style: {
                        zIndex: 999,
                        display: 'block',
                        marginTop: '10px'
                      },
                      props: {
                        transfer: true,
                        value: params.row.defective_cause, // 获取选择的下拉框的值
                      },
                    }, 
                    vm.defectiveReasonList.map(item => h('Option', {
                      props: {
                        value: item.label, // 绑定的值
                      }
                    }, item.label))),
                  ])
                ]
              );
            }
          }
        }
        if (cellData.field === 'title') {
          renderComponent = {
            renderContainer: 'CellRenderByFunction',
            renderComponent: (h,params) => {
              return h(
                'div',{
                  style: {
                    'height': '116px',
                    'margin-top': '-26px',
                  }
                },[
                  h('div', {
                    style: {
                      'height': '30px',
                      'font-size': '14px',
                      // 'font-weight': '500',
                      'color': '#333333',
                      'width': '400px'
                    }
                  }, [params.row.title]),
                  h('div', {
                    style: {
                      'height': '20px',
                      'color': '#666666',
                    }
                  }, ['款号：'+params.row.productcode]),
                  h('div', {
                    style: {
                      'height': '20px',
                      'color': '#666666',
                    }
                  }, ['规格：'+params.row.normsdetailnames]),
                ]
              );
            }
          }
        }
        if (cellData.field === 'sku_no') { 
          renderComponent = {
            renderContainer: 'CellRenderByFunction',
            renderComponent: (h,params) => {
              return h(
                'div',{
                  style: {
                    'color': '#666666',
                  }
                },
                ['SKU：'+params.row.sku_no]
              )
            }
          }
        }
        if (cellData.field === 'gbcode') { 
          renderComponent = {
            renderContainer: 'CellRenderByFunction',
            renderComponent: (h,params) => {
              return h(
                'div',{
                  style: {
                    'color': '#666666',
                  }
                },
                params.row.gbcode?['国标码：'+params.row.gbcode]:['国标码：']
              )
            }
          }
        }
        if (cellData.field === 'scanInNum') {
          renderComponent = {
            renderContainer: 'CellRenderByFunction',
            renderComponent: (h,params) => {
              return h(
                'div',{
                  style: {
                    'color': '#666666',
                    'font-size': '24px',
                    'font-family': 'inherit',
                  }
                },[
                  h('span', {
                    class: params.row.scanInNum===params.row.qty?'green':'red'
                  }, [params.row.scanInNum]),
                  h('span', {
                    style: {
                    }
                  }, ['/'+params.row.qty]),
                ]
              )
            }
          }
        }

        return renderComponent
      },

      onPrintChangeOne(e) {
        this.goodList.forEach(item => {
          item.productRemark = Number(this.formConfig[1].value);
        })
      },
      getDefectiveReasonList() {
        let params = {
          searchdata:{
            "table":"T_OMSDEFECTIVE_CAUSE",
            "startindex":0,
            "range":1000,
            "fixedcolumns":{},
            "column_include_uicontroller":true,
            "isolr":false
          }
        }
        network.post('/p/cs/QueryList',urlSearchParams(params)).then((res) => {
          if(res.data.code==0){
            if(res.data.data.row.length > 0){
              this.defectiveReasonList = []
              res.data.data.row.forEach(item => {
                let obj = {
                  label: item.DEFECTIVE_CAUSE.val,
                  value: item.ID.val
                }
                this.defectiveReasonList.push(obj)
              })
            }else {
              this.defectiveReasonList = []
            }
            
          }
        })
      },
      // 是否禁用自动匹配
      setAutoMatchDisabled(val) {
        this.$set(this.buttonConfig[1], 'disabled', val);
      },

      // 选择退货批次debugger
      onChangeRefundBatch(e) {
        this.refundBatchIdList.forEach(item=>{
          if(item.id == e){
              this.userPhysicalStorage = {  // 实体仓
                label: item.IESWAREHOUSENAME,
                value: item.IESWAREHOUSEID
              };
              this.userDefaultStorage = {  // 逻辑仓
                label: item.IESSTORENAME,
                value: item.IESSTOREID
              };
          }
        })
        // if(this.getieswarehousebyrefundbatch){ // && this.getreturnstorebyrefundbatch){
        //   this.userPhysicalStorage = {  // 实体仓
        //     label: this.getieswarehousebyrefundbatch.WAREHOUSENAME,
        //     value: this.getieswarehousebyrefundbatch.ID
        //   };
        //   this.userDefaultStorage = {  // 逻辑仓
        //     label: this.getreturnstorebyrefundbatch?this.getreturnstorebyrefundbatch.STORENAME:'',
        //     value: this.getreturnstorebyrefundbatch?this.getreturnstorebyrefundbatch.ID:''
        //   };
        // }
      },

      // 颜色标签确认
      onConfirmColor(e) {
        console.log('选择颜色', e);
        if (e.type === '1') {
          // 添加标签
          const index = this.colorTags.findIndex(item => item.color === e.data.color);
          // 标签已存在就不管
          if (index > -1) {
            return;
          }
          // 列表中不存在该标签,则添加
          this.colorTags = [...this.colorTags, e.data];
        } else {
          // 删除标签
          const index = this.colorTags.findIndex(item => item.color === e.data.color);
          if (index !== -1) {
            this.colorTags.splice(index, 1);
          }
        }
      },

      // 物流确认
      onConfirmLogisticse(e) {
        console.log("物流确认", e)
        this.orderInfo.logisticsNo = e.logistics_number;
        this.orderInfo.logistics_number = e.logistics_number;
        this.orderInfo.shipperName = e.expressName[0].Label;
        this.orderInfo.shipperId = e.expressName[0].ID;
      },

      // 入库单备注
      onConfirmremark(e) {
        this.warehouseReceiptRemark = e.target.value;
      },


      // 计算新增和删除的颜色标签，分别调用新增和保存接口
      updateDiffColor(id) {
        const addList = [];
        const removeList = [];
        // 找出新增的颜色
        this.colorTags.forEach(item => {
          const index = this.initColors.findIndex(obj => obj.color === item.color);
          // 找不到说明是新增的颜色
          if (index === -1) {
            addList.push(item);
          }
        });
        // 找出删除的颜色
        this.initColors.forEach(item => {
          const index = this.colorTags.findIndex(obj => obj.color === item.color);
          // 找不到说明是删除的颜色
          if (index === -1) {
            removeList.push(item);
          }
        });

        console.log('新增', addList);
        console.log('删除', removeList);

        addList.forEach(item => {
          this.addColorTag(item, id);
        });

        removeList.forEach(item => {
          this.removeTag(item.color);
        });
      },

      // 添加标签
      addColorTag(colorInfo, id) {
        // type值
        // 1订单
        // 2退货入库单
        // 3退换货单
        // 4出库单
        // 5纠错订单
        const params = {
          colorIds: [colorInfo.value],
          ids: [id],
          type: 2
        };
        network.post('/p/cs/color/mark/rel/linkage', params).then(res => {
          if (res.data.code == 0) {
          } else {
            this.$Message.error(res.data.message);
          }
        });
      },

      // 删除颜色标签
      removeTag(color) {
        // 取消标签
        let params = {};
        let url = '';
        if (this.orderInfo.returnOrderCode) {
          // 如果存在退单编号
          params = {
            type: 3,
            ids: this.orderInfo.returnOrderCode.split(','),
            color: [color]
          };
          url = '/p/cs/color/mark/rel/cancel/linkage';
        } else {
          params = {
            type: 1,
            ids: this.orderInfo.orderCode.split(','),
            color: [color]
          };
          url = '/p/cs/color/mark/rel/cancel';
        }

        network.post(url, params).then(res => {
          if (res.data.code == 0) {
          } else {
            this.$Message.error(res.data.message);
          }
        });
      },

      // 清除所有颜色标签
      clearColorTags() {
        this.colorTags = [];
      },

      // 获取当前设置的系统参数
      getSystemParams() {
        this.showLoading();
        network.post('/p/cs/getSysParams').then(res => {
          
          if (res.data.code == 0) {
            let allParamsList = []
            res.data.data.forEach(item => {
              allParamsList=[...allParamsList,...item.sysParam]
            })
            this.allParamsArr = allParamsList;
            allParamsList.forEach(param => {
              // 是否使用退货批次管理
              this.printType = 'scanRuku'
              if (param.paraName == 'ISUSERETURNBATCHMANAGEMENT') {
                this.ISUSERETURNBATCHMANAGEMENT = param.paraValue === 'True' ? true : false;
                if(this.ISUSERETURNBATCHMANAGEMENT === false){
                  this.allStoreCanBeModify = true;
                }else {
                  this.allStoreCanBeModify = false;
                }
              }
               // 扫描入库退回至店铺默认退货仓
              if(param.paraName == 'InStoreToDefault'){ 
                this.isStoreToDefaultFlag = param.paraValue === 'False' ? false : true;
                console.log('🚀 扫描入库退回至店铺默认退货仓', this.isStoreToDefaultFlag);
                if (this.isStoreToDefaultFlag === false && this.ISUSERETURNBATCHMANAGEMENT === false) {
                  // this.printType = 'scanRuku'
                  // 判断是否弹仓库弹框
                  // console.log(555,this.ISUSERETURNBATCHMANAGEMENT)
                  this.judgeShowStoreModal();
                }else {
                  this.printType = ''
                }
              }
              // 串款是否允许强制入库
              if(param.paraName == 'isInStore_byProductcode'){
                this.moneyForceFlag = param.paraValue === 'False' ? false : true;
              }
              // 扫描入库匹配不到售后单是否提示
              if(param.paraName == 'unMatchRefundShowTips'){
                this.unMatchTipFlag = param.paraValue === 'False' ? false : true;
              }
              // 	扫描入库数量不一致是否允许强制入库
              if(param.paraName == 'unInstoreRefundNeNum'){
                this.numForceFlag = param.paraValue === 'False' ? false : true;
              }
              // 扫描完成自动提交
              if (param.paraName == 'isAutoScanInFinishAutoCommit') {
                // this.defaultConfig.clear = obj.paraValue === 'True' ? true : false;
                this.defaultConfig.isAutoScanInFinishAutoCommit = param.paraValue === 'True' ? true : false;
              }
              
            })
          }
          this.hideLoading()
        });
      },

      // 判断是否弹仓库弹框
      judgeShowStoreModal() {
        let firstDate = localStorage.getItem('firstDate') ? JSON.parse(localStorage.getItem('firstDate')) : [];
        // 获取当前时间（年月日）
        let now = new Date().toLocaleDateString();
        // 转换成时间戳
        let time = Date.parse(new Date(now));
        let id = JSON.parse(window.localStorage.getItem('userInfo')).id;
        let obj = {
          time,
          id,
        };
        let isHaveId = false;
        if (firstDate.length > 0) {
          for (let i = 0; i < firstDate.length; i++) {
            if (firstDate[i].id == id) {
              isHaveId = true;
              if (time > firstDate[i].time) {
                // this.selectStorageInModal = true;
                this.openStoreModal('allUser');
                firstDate[i].time = time;
                localStorage.removeItem('task');
                localStorage.setItem('firstDate', JSON.stringify(firstDate));
              }
              break;
            }
          }
          if (!isHaveId) {
            // this.selectStorageInModal = true;
            this.openStoreModal('allUser');
            firstDate.push(obj);
            localStorage.removeItem('task');
            localStorage.setItem('firstDate', JSON.stringify(firstDate));
          }
        } else {
          // this.selectStorageInModal = true;
          this.openStoreModal('allUser');
          firstDate.push(obj);
          localStorage.removeItem('task');
          localStorage.setItem('firstDate', JSON.stringify(firstDate));
        }
      },

      // 打开仓库弹框
      openStoreModal(type) {
        this.openStoreType = type;
        this.$refs.leftPanel.showStoreModal = true;
      },

      // 获取唯一码策略
      getUniqueCodeConfig() {
        network.get('/p/cs/platform/config/qr_code_control').then(res => {
          if (res.data.code === 0) {
            const qrCodeContrl = res.data.data;
            this.qrCodeContrlData = qrCodeContrl;
            // 仅支持SKU入库
            this.supportOnlySkuFlag = qrCodeContrl.RETURN_AND_STORAGE[0].configValue == 'true' ? true : false;
            // 支持唯一码/SKU入库
            this.supportCodeAndSkuFlag = qrCodeContrl.RETURN_AND_STORAGE[1].configValue == 'true' ? true : false;
            // 仅支持唯一码入库。即通过唯一码匹配，有可能入库(如果允许串款)
            this.supportUniqueCodeFlag = qrCodeContrl.RETURN_AND_STORAGE[2].configValue == 'true' ? true : false;
            // 仅支持退单/订单中商品唯一码入库。即通过唯一码匹配，与supportUniqueCodeFlag区别是如果匹配不到，肯定不能入库
            this.supportCodeInStoreFlag = qrCodeContrl.RETURN_AND_STORAGE[3].configValue == 'true' ? true : false;
            console.log('唯一码策略', qrCodeContrl.RETURN_AND_STORAGE);
          }
        });
      },

      // 获取颜色
      getBillColorList() {
        const params = {
          type: 3,
          ids: this.orderInfo.returnOrderCode.split(',')
        };
        network.post('/p/cs/color/mark/rel/list', params).then(res => {
          if (res.data.code == 0 && res.data.data.length > 0) {
            const data = res.data.data[0].color_block;
            this.colorTags = data.map(item => ({
              label: item.text,
              value: '',
              color: item.color
            }));
            this.initColors = cloneDeep(this.colorTags);
          }
        });
      },

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

      // 关闭loading
      hideLoading() {
        this.isLoading = false;
      },
      //输入框获取焦点
      inputFocus(id) {
        try {
          this.$nextTick(()=> {
            const elem = document.getElementById(id);
            if (elem) elem.focus();
          })
        } catch (error) {
          console.log(`focus-error`, error)
        }
      },
      inputBlur(id) {
        try {
          this.$nextTick(()=> {
            const elem = document.getElementById(id);
            if (elem) elem.blur();
          })
        } catch (error) {
          console.log(`blur-error`, error)
        }
      },

      // 输入框回车事件
      inputEnter(e, colname, type) {
        let value = '';
        if(type){
          value = this.scanOrderNoText;
        }else {
          if(colname == 'orderNo'){
            this.scanOrderNoText = e.target.value.trim();
          }
          value = e.target.value.trim();
        }
        this.focusInputId = e.target.id || null;
        this.showLoading();
        if (colname === 'orderNo') {
          if (!value) {
            this.$Message.warning('扫描单号不能为空!');
            this.hideLoading();
            return;
          }
          this.lastScanIndex = -1; // 重置最新扫描商品索引
          if (this.scanNum === this.totalNum) {
            this.scanOrderNo(value);
          } else {
            // this.playAudio(this.scanOk);
            if(!type){
              this.$Modal.fcWarning({
                title: '提示',
                mask: true,
                showCancel: true,
                content: '商品未全部入库完成，是否要继续扫描下一张退单？',
                onOk: () => {
                  this.scanOrderNo(value);
                },
                onCancel: () => {
                  this.hideLoading();
                }
              });
            }else {
              this.scanOrderNo(value);
            }
            
          }
        } else {
          // 因为要保证用户输过单号后并按回车过。所以这里用orderInfo.scanOrderNo判断单号是否存在
          if (!this.orderInfo.scanOrderNo) {
            this.$Message.warning('扫描单号不能为空!');
            this.inputFocus('order-input');
            this.hideLoading();
            return;
          }
          if (!value) {
            this.$Message.warning('商品SKU（国标码）不能为空！');
            this.hideLoading();
            return;
          }
          this.lastScanIndex = -1; // 重置最新扫描商品索引
          this.scanGood(value);
        }
      },

      // 扫描商品
      scanGood(value) {
        const param = {
          sku: value
        };
        this.inputBlur(this.focusInputId);
        network.post('/p/cs/return_and_storage/query/sku', param).then( async res => {
          if (res.data.code == 0 && res.data.data) {
            this.playAudio(this.goodsAudioUrl);
            const data = res.data.data;
            if (!data.GBCODE) {
              data.GBCODE = data.SKU;
            }
            console.log('🚀 ~ 商品信息', data);
            this.scanGoodInfo = data;
            this.isQrcodeScanFlag = false; // 重置标记。用于标记扫描商品输入框扫的是否是唯一码
            if (this.scanGoodInfo.wareHousingSkuItemVOList && this.scanGoodInfo.wareHousingSkuItemVOList.length > 0) {
              const qrcode = data.wareHousingSkuItemVOList[0].qrcode;
              if (qrcode === value) {
                this.isQrcodeScanFlag = true;
              } else {
                this.isQrcodeScanFlag = false;
              }
              this.scanGoodInfo.qrcode = qrcode;
             await this.singleMatch(data.SKU, data.GBCODE, qrcode);
              this.hideLoading();
            } else {
              await this.singleMatch(data.SKU, data.GBCODE, '');
              this.hideLoading();
            }
          } else {
            this.inputConfig[1].value = '';
            // this.inputConfig.forEach(item => {
            //   if(item.colname == 'skuNo') {
            //     item.value = ''
            //   }
            // })
            this.$Message.error(res.data.message);
            this.playAudio(this.scanError);
            this.hideLoading();
          }
        }).finally(() => {
          this.inputFocus(this.focusInputId);
        });
      },

      // 单个匹配
     async singleMatch(sku, gbCode, qrcode) {
        // 获取唯一码策略
       await  this.getUniqueCodeConfig();

        if (this.goodList.length > 0) {
          let matchIndex = -1; // 记录匹配到到商品索引
          // 记录本次是通过哪个字段匹配到的商品
          const matchWay = {
            qrcode: 1,
            sku: 2,
            productCode: 3
          };
          // 遍历商品列表判断是否存在当前商品
          // 特殊情况： 商品列表存在相同商品A，第一个A是1/1 ,第二个A是0/1。那么第一次扫虽然匹配到第一个A，但是它算未扫完的，因为第二个A还没扫
          // 特殊处理方案情况：匹配到商品后依然继续匹配，但是要记录匹配过程中遇到的0/1的相同商品.通过notScannedIndex标记这个商品是否扫描过了
          let matchWayFlag; // 记录通过何种方式匹配到的商品
          const notScannedIndex = [];
          let qrcodeMatchIndex = -1; // 记录已录入的唯一码位置
          let hasSameProductCode = false
          console.log('配置', this.supportCodeAndSkuFlag, this.supportUniqueCodeFlag);
          for (let i = 0; i < this.goodList.length; i++) {
            const good = this.goodList[i];
            console.log('比较----', good);
            if (!this.supportOnlySkuFlag && qrcode && good.qrcode === qrcode && (this.supportCodeAndSkuFlag || this.supportUniqueCodeFlag)) {
              console.log(222,good.scanInNum)
              debugger
              matchIndex = i;
              if (!matchWayFlag) {
                matchWayFlag = matchWay.qrcode;
              }
              if (good.scanInNum === 0) {
                notScannedIndex.push(i);
              }
              if (good.scanInNum > 0 && good.good_qrcode === qrcode) {
                qrcodeMatchIndex = i;
              }
              console.log('命中qrcode相等');
              if(notScannedIndex.length > 0){
                break;
              }else{
                continue;
              }
            }
            // canMatch用于处理一个特殊情况：配置了"仅支持唯一码"，此时可以通过接口带入的sku进行匹配
            const canMatch = this.supportUniqueCodeFlag && good.sku_no === sku;   // && this.isQrcodeScanFlag
            if ((good.sku_no === sku && this.supportCodeAndSkuFlag) || (good.sku_no === sku && this.supportOnlySkuFlag) || canMatch) {
              matchIndex = i;
              if (!matchWayFlag) {
                matchWayFlag = matchWay.sku;
              }
              if (good.scanInNum === 0) {
                notScannedIndex.push(i);
              }
              // --- 唯一码匹配到的特殊情况 start---
              if (canMatch && good.scanInNum === 0) {
                matchWayFlag = matchWay.qrcode;
                notScannedIndex.push(i);
                console.log('特殊：命中qrcode相等');
              }
              // --- 唯一码匹配到的特殊情况 end---
              console.log('命中sku相等');
              if(notScannedIndex.length > 0){
                break;
              }else{
                continue;
              }
              
            }
            if (!this.supportOnlySkuFlag && good.gbcode === gbCode && !this.supportUniqueCodeFlag) {
              matchIndex = i;
              if (!matchWayFlag) {
                matchWayFlag = matchWay.gbCode;
              }
              if (good.scanInNum === 0) {
                notScannedIndex.push(i);
              }
              if(notScannedIndex.length > 0){
                break;
              }else{
                continue;
              }
            }
            // 同款串条码
            if(!this.moneyForceFlag && this.scanGoodInfo.PRODUCTCODE === good.productcode) {
              hasSameProductCode = true
              console.log('串款')
              // 重复扫同款的条码
              if(good.sku_no == sku && good.gbcode == gbCode) {
                matchIndex = i;
                break;
              }
            }
          }
          // 扫描商品不在列表里时
          if (matchIndex === -1) {
            // 如果开启串款强制入库
            if (this.moneyForceFlag) {
              // 如果开启仅支持退单/订单中商品唯一码入库。即商品列表里查不到唯一码就不给入库
              if (this.supportCodeInStoreFlag) {
                this.$Modal.fcWarning({
                  mask: true,
                  showCancel: true,
                  title: '警告',
                  content: '退回商品的唯一码在订单中不存在，商品不允许入库！',
                  onOk: () => {
                    this.clearSkuInput();
                  },
                  onCancel: () => {
                    this.clearSkuInput();
                  }
                });
              } else if (this.isAbnormalOrder) {
                this.insertGood();
              } else {
                this.$Modal.fcWarning({
                  mask: true,
                  showCancel: true,
                  title: '警告',
                  content: '当前商品不存在，是否继续？',
                  onOk: () => {
                    this.insertGood();
                  },
                  onCancel: () => {
                    this.clearSkuInput();
                  }
                });
              }
            } else {
              // 同款串条码
              if(hasSameProductCode && !this.isAbnormalOrder) { 
                this.$Modal.fcWarning({
                  mask: true,
                  showCancel: true,
                  title: '警告',
                  content: '当前商品不存在，是否继续？',
                  onOk: () => {
                    this.insertGood();
                  },
                  onCancel: () => {
                    this.clearSkuInput();
                  }
                });
                return
              }
              if(this.isAbnormalOrder) {
                this.insertGood();
              }else {
                //当前商品不存在，是否继续？
                this.$Message.warning({
                  content: '串款商品不允许入库，如需入库请修改系统参数！',
                  // duration: 0,
                });
              }
            }
          } else {
            console.log(notScannedIndex)
            // 扫描商品在列表里时
            const hasScanned = notScannedIndex.length === 0 ? true : false; // 是否扫过
            console.log('🚀 ~ 未扫列表、已录入唯一码索引、命中方式', notScannedIndex, qrcodeMatchIndex, matchWayFlag);
            // 通过唯一码匹配到了，且扫过，且录入了
            if (matchWayFlag === 1 && qrcodeMatchIndex !== -1 && this.goodList[qrcodeMatchIndex].good_qrcode) {
              this.lastScanIndex = qrcodeMatchIndex;
              this.$Message.warning('已经录入过该唯一码，不允许重复录入！');
              return;
            }
            // // 通过唯一码匹配到了，且扫过，且没有录入
            // if(matchWayFlag === 1 && qrcodeMatchIndex !== -1 && !this.goodList[qrcodeMatchIndex].good_qrcode && this.goodList[qrcodeMatchIndex].scanInNum > 0) {
            //   this.lastScanIndex = qrcodeMatchIndex
            //   this.goodList[qrcodeMatchIndex].good_qrcode = qrcode
            //   return
            // }
            // 通过唯一码匹配到了，但是没扫过
            if (matchWayFlag === 1 && !hasScanned) {
              const currentGood = this.goodList[notScannedIndex[0]];
              this.updateGood(currentGood, notScannedIndex[0]);
              return;
            }
            // 下面逻辑是 通过sku或者gbcode匹配到的情况
            // 已经扫过了
            if (hasScanned) {
              if (this.isAbnormalOrder) {
                this.insertGood();
              } else {
                this.$Modal.fcWarning({
                  mask: true,
                  showCancel: true,
                  title: '警告',
                  content: '当前商品已扫描过，是否继续？',
                  onOk: () => {
                    this.insertGood();
                  }
                });
              }
            } else {
              // 没有扫过
              const currentGood = this.goodList[notScannedIndex[0]];
              this.updateGood(currentGood, notScannedIndex[0]);
            }
          }
        } else {
          // 商品列表为空时时
          // 如果开启串款强制入库
          if (this.moneyForceFlag) {
            if (this.isAbnormalOrder) {
              this.insertGood();
            } else {
              this.$Modal.fcWarning({
                mask: true,
                showCancel: true,
                title: '警告',
                content: '当前商品不存在，是否继续？',
                onOk: () => {
                  this.insertGood();
                }
              });
            }
          } else if (this.isAbnormalOrder) {
              this.insertGood();
          } else {
              this.$Message.warning('串款商品不允许入库，如需入库请修改系统参数！');
          }
        }
      },

      // 扫描商品时排序
      // 商品排序: 当前已扫-未扫-之前已扫
      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];
      },

      // 更新商品
      updateGood(currentGood, firstMatchIndex) {
        this.scanNum++;
        // console.log(111111, this.scanGoodInfo.qrcode, matchWayFlag)
        if ((this.supportCodeAndSkuFlag || this.supportUniqueCodeFlag) && this.scanGoodInfo.qrcode) {
          currentGood.good_qrcode = this.scanGoodInfo.qrcode; // 展示qrcode
          currentGood.qrcode = this.scanGoodInfo.qrcode;
        }
        currentGood.scanInNum++;
        // this.$set(this.goodList, notScannedIndex, currentGood)
        this.goodList.splice(firstMatchIndex, 1);
        this.goodList.unshift(currentGood);
        this.sortGoodList(currentGood);
        this.lastScanIndex = 0;
        this.clearSkuInput();
        // && this.defaultConfig.clear
        
        if (!this.isAbnormalOrder && this.defaultConfig.isAutoScanInFinishAutoCommit && this.isAllScanned() && this.scanNum == this.totalNum) {
          this.autoMatch({ autoType: 'UPDATE_GOOD' });
        }
        if(Number(this.scanNum) == Number(this.totalNum)){
          this.recordLogFn({
            LOG_ID: 17,
            LOG_OPERATOR: `updateGood`,
            LOG_INFO: {
              isAbnormalOrder: !this.isAbnormalOrder,
              isAutoScanInFinishAutoCommit:this.defaultConfig,
              isAllScanned:this.isAllScanned(),
              scanNum:this.scanNum,
              totalNum:this.totalNum,
            },
          })
        }
        
      },

      // 往商品列表插入新商品
      insertGood() {
        if (this.isAbnormalOrder) {
          // 三无订单
          this.scanNum++;
          this.totalNum++;
        } else {
          // 正常订单
          this.scanNum++;
        }
        this.scanGoodInfo.scanInNum = 1;
        this.scanGoodInfo.qty = 1;
        let picUrl = ''
        try {
          picUrl = JSON.parse(this.scanGoodInfo.pic_url)[0].URL
        } catch (e) {
          picUrl = this.scanGoodInfo.pic_url
        }
        this.scanGoodInfo.pic_url = picUrl
        const newGood = {
          ...this.scanGoodInfo,
          sku_no: this.scanGoodInfo.SKU,
          gbcode: this.scanGoodInfo.GBCODE,
          normsdetailnames: this.scanGoodInfo.NORMSDETAILNAMES,
          productcode: this.scanGoodInfo.PRODUCTCODE,
          title: this.scanGoodInfo.SKUNAME,
          productRemark: 1,
        };
        // console.log(22222, this.scanGoodInfo.qrcode, matchWayFlag)
        if ((this.supportCodeAndSkuFlag || this.supportUniqueCodeFlag) && this.scanGoodInfo.qrcode) {
          newGood.good_qrcode = this.scanGoodInfo.qrcode; // 展示qrcode
          newGood.qrcode = this.scanGoodInfo.qrcode;
        }
        this.goodList.unshift(newGood);
        this.sortGoodList(newGood);

        this.lastScanIndex = 0;
        this.clearSkuInput();
        if (!this.isAbnormalOrder && this.defaultConfig.clear && this.defaultConfig.isAutoScanInFinishAutoCommit && this.isAllScanned() && this.scanNum === this.totalNum) {
          this.autoMatch({ autoType: 'INSERT_GOOD' });
        }
      },

      // 扫描单号
      scanOrderNo(id) {
        // 重置订单类型标记
        this.isReturnOrderFlag = true;
        // 重置唯一码标记
        this.isQrcodeFlag = false;
        // 重置退货批次相关
        this.refundBatchIdList = [];
        this.orderInfo.refundBatchId = '';
        this.getreturnstorebyrefundbatch = {}
        this.getieswarehousebyrefundbatch = {}
        this.userPhysicalStorage = {
            value: '',
            label: ''
        }
        this.userDefaultStorage = {
            value: '',
            label: ''
        }

        const scanNo = this.inputConfig[0].value.trim(); // 扫描单号
        this.clearPage();
        this.orderInfo.scanOrderNo = scanNo; // 扫描单号

        const param = {
          logistics_no: id
        };
        // 检测物流单是否入库
        network.post('/p/cs/returnInStore/checkLogisticsNo', param).then(res => {
          if (res.data.code == 0) {
            if (res.data.data.isExistLogistics == 1) {
              this.$Modal.fcWarning({
                title: '提示',
                mask: true,
                showCancel: true,
                content: '此物流单号已入库，是否重复强制入库？',
                onOk: () => {
                  this.getOrderInfo(id);
                  // this.hideLoading();
                },
                onCancel: () => {
                  this.clearPage();
                  this.hideLoading();
                }
              });
            } else {
              this.getOrderInfo(id);
              // this.hideLoading();
            }
          } else {
            this.playAudio(this.scanError);
            this.hideLoading();
          }
        })
      },

      // 获取物流单信息
      getOrderInfo(id) {
        // this.showLoading();
        const param = {
          logistics_no: id
        };
        this.oriwarehouseid = '';
        network.post('/p/cs/logistics/queryItemByLogisticsNo', param).then(res => {
          if (res.data.code === 0) {
            this.formConfig[1].disabled = true;
            const data = res.data.data;
            // LOG
            // 订单原发货仓id
            if(data && data.ext && data.ext.oriwarehouseid){
                  this.oriwarehouseid = data.ext.oriwarehouseid
            }
            this.recordLogFn({
              LOG_ID: 10,
              LOG_OPERATOR: `SCAN_IN_${id}`,
              LOG_INFO: {
                F_scanInData: data,
                F_formConfig: this.formConfig,
              },
            })
            this.playAudio(this.logisticsAudioUrl, '#order-audio');
            this.clearColorTags(); // 清除颜色标签
            if (data === '' || data === null) {
              // 如果是三无订单
              this.getUserStore();
              this.isAbnormalOrder = true;
              this.playAudio(this.scanError);
              this.$Message.error({
                content: '未找到退换货单或订单，如需继续入库，可扫描商品进行强制入库',
                duration: 3
              });
            } else if (!data.list || data.list.length == 0) {
              // 如果是三无订单
              this.getUserStore();
              this.isAbnormalOrder = true;
              this.playAudio(this.scanError);
              this.$Message.error({
                content: '未找到退换货单或订单，如需继续入库，可扫描商品进行强制入库',
                duration: 3
              });
            } else {
              this.isAbnormalOrder = false;
              // bill_type:  1订单 2退单
              if (data.list[0].bill_type == 1) {
                // 扫描入库匹配不到售后单是否提示
                this.RefundBatchId = data.list[0].bill_id
                const obj = { type:'start', list: data.list, billType:1 }
                this.changeProductRemark(obj);
                if (this.unMatchTipFlag) {
                  this.playAudio(this.scanOk);
                  this.$Modal.fcWarning({
                    title: '提示',
                    mask: true,
                    showCancel: true,
                    content: '该物流单为拒收类型，入库后会生成拒收类型退货单，是否继续？',
                    onOk: () => {
                      this.handleOrder(data);
                    },
                    onCancel: () => {
                      this.clearPage();
                    }
                  });
                } else {
                  this.handleOrder(data);
                }
              } else {
                this.handleOrder(data);
                if(data.list[0].ori_order_id){
                  this.RefundBatchId = data.list[0].ori_order_id 
                  // 
                  const obj = { type:'start', list: data.list, billType:2 }
                  this.changeProductRemark(obj);
                }else {
                  this.RefundBatchId = ''
                  if(this.ISUSERETURNBATCHMANAGEMENT) {
                    this.$Message.warning({
                      content:'无法找到原订单发货仓库确认批次销售类型',
                      duration: 3
                    });
                  }
                }
              }
            }
          } else {
            this.playAudio(this.scanError);
          }
        }).finally(() => {
          setTimeout(() => {
           this.hideLoading();
          }, 50);
        });
      },
      async changeProductRemark(option) {
        // 使用防抖函数
        this.debouncedChangeProductRemark(option);
      },

      // 实际执行商品标记变更的方法
      async _changeProductRemark(option) {
        const { type, list, billType } = option || {}
        // console.log(option, 'wjf_002')
        // 判断数组中的所有元素paramName参数值是否一样
        // 查询退单符合的批次数据
        // ISUSERETURNBATCHMANAGEMENT 是否批次
        this.recordLogFn({
          LOG_ID: 11,
          LOG_OPERATOR: `PRE_PICI_${this.RefundBatchId}`,
          LOG_INFO: {
            F_remarkOption: option || null,
            F_isUseRest: this.ISUSERETURNBATCHMANAGEMENT,
          },
        })
        if(this.ISUSERETURNBATCHMANAGEMENT){
          let isSameFlag = this.goodList.every(item => item['productRemark'] === this.goodList[0]['productRemark']);
          if(!isSameFlag){  // 如果都是残次品或者瑕疵品
            let hasName = this.goodList.some(item => item['productRemark'] == 1);
            if(!hasName){
              isSameFlag = true;
            }
          }
          if(isSameFlag){
            let productcodes = [];
            let productMark = 0
            if(type == 'start'){
              list.forEach(item => {
                productcodes.push(item.productcode)
              })
              productMark = this.formConfig[1].value == 1?0:1
            }else {
              this.goodList.forEach(item => {
                productcodes.push(item.productcode)
              })
              productMark = this.goodList[0]['productRemark'] == 1?0:1
            }
            let params = {
              "orderId": this.RefundBatchId,
              "productcodes": productcodes,
              productMark
            }
            if(this.RefundBatchId){
              this.showLoading();
              const res = await network.post('/p/cs/logistics/queryRefundBatchNo', params);
              const resData = res.data || {};
              const { code, data = {} } = resData || {};
              if(code == 0){
                this.hideLoading();
                const { list } = data || {};
                this.orderInfo.refundBatchId = ''
                this.userDefaultStorage = {
                  value: '',
                  label: ''
                }
                this.userPhysicalStorage = {
                  value: '',
                  label: ''
                }
                this.refundBatchIdList = list || [];
                if(this.refundBatchIdList.length == 1){
                  this.orderInfo.refundBatchId = this.refundBatchIdList[0].id
                    this.userPhysicalStorage = {
                      label: list[0].IESWAREHOUSENAME,
                      value: list[0].IESWAREHOUSEID
                    };
                    this.userDefaultStorage = {
                      label: list[0].IESSTORENAME,
                      value: list[0].IESSTOREID
                    };
                }
                this.recordLogFn({
                  LOG_ID: 12,
                  LOG_OPERATOR: `TUIHUO_PICI_${this.RefundBatchId}`,
                  LOG_INFO: {
                    F_piciData: data,
                    F_orderInfo: this.orderInfo,
                    F_piciOption: option || null,
                    F_piciParams: params,
                  },
                })
              } else{
                this.hideLoading();
              }
            }
          }else {
            this.refundBatchIdList = [];
            this.orderInfo.refundBatchId = ''
            // this.getieswarehousebyrefundbatch = {};
            // this.getreturnstorebyrefundbatch = {};
            this.userDefaultStorage = {
              value: '',
              label: ''
            }
            this.userPhysicalStorage = {
              value: '',
              label: ''
            }
          }
        }
      },

      // 获取当前用户选择的仓库
      getUserStore() {
        const localData = localStorage.getItem('firstDate') ? JSON.parse(localStorage.getItem('firstDate')) : [];
        const userId = JSON.parse(localStorage.getItem('userInfo')).id;
        // 从本地缓存里查当前用户的数据
        const userDataIndex = localData.findIndex(item => item.id === userId && item.storageList);
        // 如果本地存在当前用户的数据
        if (userDataIndex > -1) {
          this.userPhysicalStorage = localData[userDataIndex].storageList.physicalStorage || {
            value: '',
            label: ''
          };
          this.userDefaultStorage = localData[userDataIndex].storageList.defaultStorage || {
            value: '',
            label: ''
          };
          this.localPhysicalStorage = cloneDeep(this.userPhysicalStorage);
          this.localDefaultStorage = cloneDeep(this.userDefaultStorage);
          this.allUserDefaultStorage = cloneDeep(this.userDefaultStorage);
          this.allUserPhysicalStorage = cloneDeep(this.userPhysicalStorage);
        }
        console.log('用户仓库', this.userPhysicalStorage, this.userDefaultStorage);
      },

      // 入库弹框确认
      onConfirmStore(val) {
        if(this.openStoreType=='allUser'){
          this.allUserDefaultStorage = val.defaultStorage;
          this.allUserPhysicalStorage = val.physicalStorage;
          this.openStoreType = '';
        }else {
          this.userDefaultStorage = val.defaultStorage;
          this.userPhysicalStorage = val.physicalStorage;
        }
        this.inputFocus('order-input');
      },

      // 读取订单入库仓库
      setStore(data) {
        this.userPhysicalStorage = {
          label: data.ext.warehouse_name,
          value: data.ext.warehouse_id
        };
        const warehouse_id = data.ext.warehouse_id;
        if (warehouse_id) {
          this.getDefaultStoreList(warehouse_id);
        }
      },

      // 获取逻辑店仓列表
      getDefaultStoreList(id) {
        network.post('/p/cs/store/getStoreByhouseId', { ID: id }).then(res => {
          if (res.data.code === 0) {
            if (!res.data.data) {
              this.$Message.error({
                content: res.data.message,
                duration: 3
              });
              return;
            }
            const data = res.data.data.map(item => ({
              label: item.STORENAME,
              value: item.ID
            }));
            // 只有一个仓库时
            if (data.length === 1) {
              this.userDefaultStorage = data[0];
              this.allUserDefaultStorage = data[0];
            } else {
              this.userDefaultStorage = {
                value: '',
                label: ''
              };
            }
          }
        });
      },

      // 处理物流单
      handleOrder(data) {
        this.inputFocus('sku-input');
        this.showContent = true;

        // 判断扫描入库退回至店铺默认退货仓
        if (this.isStoreToDefaultFlag) {
          this.setStore(data);
        } else {
          // 用本地缓存的
          this.getUserStore();
        }

        // 判断当前是订单还是退货单
        if (data.list[0].bill_type == 1) {
          this.isReturnOrderFlag = false;
          this.$Message.info('未找到退换货单，自动带出原订单信息!');
        }

        const bill_nos = new Set(); // 退单编号
        const ori_order_ids = new Set(); // 原订单编号
        const source_codes = new Set(); // 原平台单号
        const goodList = []; // 商品列表
        this.returnGoodsNum = 0; // 重置退货商品数量

        data.list.forEach(item => {
          bill_nos.add(item.bill_id);
          ori_order_ids.add(item.ori_order_id);
          source_codes.add(item.source_code);

          // 如果应入库数量大于1，则需要拼接下每个sku的唯一码
          if (item.qty > 1) {
            let qrcodeList = item.qrcode ? item.qrcode.split(',') : [];
            for (let i = 0; i < item.qty; i++) {
              let obj = cloneDeep(item);
              let picUrl = ''
              try {
                picUrl = JSON.parse(obj.pic_url)[0].URL
              } catch (e) {
                picUrl = obj.pic_url
              }
              obj.pic_url = picUrl
              obj.qty = 1; // 应入数量
              obj.productRemark = Number(this.formConfig[1].value); // 商品标记
              obj.scanInNum = 0; // 扫描数量
              obj.qrcode = qrcodeList[i] ? qrcodeList[i] : ''; // 唯一码
              goodList.push(obj);
            }
          } else {
            let obj = cloneDeep(item);
            let picUrl = ''
            try {
              picUrl = JSON.parse(obj.pic_url)[0].URL
            } catch (e) {
              picUrl = obj.pic_url
            }
            obj.pic_url = picUrl
            obj.productRemark = Number(this.formConfig[1].value);
            obj.scanInNum = 0;
            goodList.push(obj);
          }
        });
        this.goodList = goodList;
        console.log('🚀 ~ 商品列表', this.goodList);

        // 如果是退货单
        this.orderInfo.returnOrderCode = [];
        if (this.isReturnOrderFlag) {
          this.orderInfo.returnOrderCode = Array.from(bill_nos).join(','); // 退单编号
          this.orderInfo.orderCode = Array.from(ori_order_ids).join(','); // 原订单编号
        } else {
          this.orderInfo.orderCode = Array.from(bill_nos).join(','); // 原订单编号
        }

        this.totalNum = this.goodList.length; // 应入数量
        this.orderInfo.logisticsNo = data.ext.logistics_no;// 物流单号
        this.orderInfo.shipperName = data.ext.shipper_name;// 物流公司
        this.orderInfo.shipperId = data.ext.shipper_id;// 物流公司id
        this.orderInfo.shop = data.ext.shop_title; // 店铺
        this.orderInfo.platformName = data.ext.plat_form_name; // 平台
        this.orderInfo.orderType = data.refundExchangeOrderProductDTOList && data.refundExchangeOrderProductDTOList.length > 0 ? '退换货' : '退货'; // 是否换货
        this.orderInfo.sourceCodes = Array.from(source_codes).join(','); // 原平台单号
        this.orderInfo.sellermemo = data.ext.sellermemo; // 订单卖家备注
        this.orderInfo.remark = data.ext.remark; // 内部备注
        this.orderInfo.returndesc = data.ext.returndesc; // 退换货说明
        this.orderInfo.buyermessage = data.ext.buyermessage; // 退单买家备注
        const stores = new Set();
        data.list.forEach(item => {
          stores.add(item.warehousename);
        });
        this.orderInfo.warehouseName = Array.from(stores).join(','); // 发货仓库

        // 入库参数需要的信息
        this.orderInfo.buyerNick = data.ext.buyer_nick;
        this.orderInfo.userName = data.ext.user_name;
        this.orderInfo.phone = data.ext.phone;
        this.orderInfo.tel = data.ext.tel;
        this.orderInfo.platform = data.ext.plat_form ? data.ext.plat_form.toString() : ''; // 平台
        this.orderInfo.shopId = data.ext.shop_id.toString(); // 店铺id

        // 判断是否禁用自动匹配
        // 匹配不到单据，或扫入的单据商品包含唯一码管控商品
        if (this.goodList.length === 0 || this.judgeIsQrcode(data) || this.isAbnormalOrder) {
          this.setAutoMatchDisabled(true);
        } else {
          this.setAutoMatchDisabled(false);
        }

        // 获取订单的颜色标签
        this.getBillColorList();
      },

      // 判断是否明细是否唯一码管控
      judgeIsQrcode(data) {
        for (let i = 0; i < data.list.length; i++) {
          if (data.list[i].isQrcode) {
            this.isQrcodeFlag = true;
          }
        }
        return this.isQrcodeFlag;
      },

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

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

      // 检测订单是否扫描完成
      isAllScanned() {
        const index = this.goodList.findIndex(item => item.scanInNum == 0);
        return index === -1 ? true : false;
      },

      // 清除界面
      clearPage() {
        this.inputConfig[1].value = '';
        this.orderInfo = {};
        this.totalNum = 0;
        this.scanNum = 0;
        this.goodList = [];
        this.userPhysicalStorage = {
          value: '',
          label: ''
        };
        this.userDefaultStorage = {
          value: '',
          label: ''
        };
        this.showContent = false;
        this.isAbnormalOrder = false;
        this.warehouseReceiptRemark = '';
        this.$refs.leftPanel.warehouseReceiptRemark = '';
        this.clearColorTags();
      },

      // 点击顶部按钮
      onButtonClick(e) {
        // 强制入库
        if (e.type === '1') {
          this.forceInStore();
        } else if (e.type === '2') {
          // 自动匹配
          this.autoMatch({ autoType: 'AUTO_FIND' });
        }
        console.log('🚀 ~ file: index.vue:75 ~ onButtonClick ~ e:', e);
      },

      // 强制入库
      forceInStore() {
        // 	开启了"扫描入库数量不一致是否允许强制入库"
        this.recordLogFn({
            LOG_ID: 13,
            LOG_OPERATOR: `forceInStore`,
            LOG_INFO: {
              allParamsArr: this.allParamsArr,
              numForceFlag:this.numForceFlag,
              isAbnormalOrder:this.isAbnormalOrder,
            },
        })
        if (this.numForceFlag) {
          this.handleForce();
        } else {
          if (this.scanNum !== this.totalNum) {
            this.$Message.error('当前应入数量与扫描数量不一致，不允许强制入库');
            return;
          }
          this.handleForce();
        }
        
      },

      handleForce() {
        // 扫描单号没值
        if (this.inputConfig[0].value === '') {
          this.playAudio(this.scanError);
          this.$Message.error('扫描单号必填');
        } else {
          this.autoMatch({ autoType: 'FORCE_IN', isForce: true });
        }
      },

      // 自动匹配
      autoMatch(option) {
        const { autoType, isForce } = option || {}
        if (this.goodList.length === 0) {
          return;
        }
        const inStoreGoods = []; // 入库商品
        this.goodList.forEach(item => {
          // 强制入库，把扫过的都入库
          if (isForce) {
            if (item.scanInNum !== 0) {
              const obj = {
                quality_mark: item.productRemark,
                defective_cause: item.defective_cause,
                sku: item.sku_no,
                qrcode: item.good_qrcode,
              };
              inStoreGoods.push(obj);
            }
          } else {
            // 自动匹配。每个商品都扫一遍并入库
            if (item.scanInNum === 0) {
              item.scanInNum = 1;
              this.scanNum++; // 已扫描数量增加
            }
            const obj = {
              quality_mark: item.productRemark,
              defective_cause: item.defective_cause,
              sku: item.sku_no,
              qrcode: item.good_qrcode,
            };
            inStoreGoods.push(obj);
          }
        });

        console.log('待入库商品', inStoreGoods);
        if (inStoreGoods.length === 0) {
          console.log('没有入库商品');
          return;
        }

        const params = {
          create_type: '2',
          logistics_no: this.orderInfo.scanOrderNo, // 扫描单号
          logistics_number: this.orderInfo.logistics_number, // 用户手动输入的物流单号
          default_store: this.userDefaultStorage.value, // 默认逻辑仓
          flaw_store: '',
          defective_store: '',
          shipper_id: this.orderInfo.shipperId, // 物流公司id
          shipper_name: this.orderInfo.shipperName, // 物流公司
          buyer_nick: this.orderInfo.buyerNick,
          user_name: this.orderInfo.userName,
          phone: this.orderInfo.phone,
          tel: this.orderInfo.tel,
          delivery_address: '',
          remark: this.warehouseReceiptRemark,//入库单备注
          scan_goods: inStoreGoods,
          plat_form: this.orderInfo.platform, //平台
          shop_id: this.orderInfo.shopId, //店铺
          isForcePut: isForce, // 是否强制入库
        };
        if(this.ISUSERETURNBATCHMANAGEMENT) {
          params.refund_batch_id = this.orderInfo.refundBatchId
        }
        this.inStore(params, option);
      },
      // 请求入库接口
      inStore(params, option) {
        // this.showLoading();
        console.log(123,params)
        params.oriwarehouseid = this.oriwarehouseid

        network.post('/p/cs/returnInStroe/create', params).then(res => {
          if (res.data.code == 0) {
            const resData = res.data.data;
            this.playAudio(this.successAudioUrl);
            this.updateDiffColor(resData);
            this.clearPage();
            this.clearOrderInput();
            this.inputFocus('order-input');
            this.$Message.success({
              content: '入库成功！',
              duration: 5,
            });
            this.recordLogFn({
              LOG_ID: 13,
              LOG_OPERATOR: `IN_STORE_END`,
              LOG_INFO: {
                F_createData: resData,
                F_params: params,
                F_option: option || null,
                F_allParamsArr: this.allParamsArr,
                F_qrCodeContrlData: this.qrCodeContrlData,
              },
            })
          } else {
            console.log(12345)
            this.inputEnter('','orderNo','saveErrorCallback')
            this.playAudio(this.scanError);
          }
        }).finally(() => {
          this.hideLoading();
        });
      },

      openFeedback() {
        this.$FeedbackDialog({
          type: 1,
          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: 'INSTORE',
            customizedModuleId: '2209',
            label: '扫描入库'
          });
          this.triggerPoint();
        }, 0);
      },

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

      // 获取打印音效
      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;
            }
          });
        });
      },

      // 播放语音
      playAudio(url, id = '#audio') {
        const audio = document.querySelector(id);
        audio.src = url;
        audio.play();
      },
      recordLogFn(obj) {
        try {
          this.$comUtils.globalSaveOperateLogFn(obj);
        } catch (error) {
          console.log(error)
        }
      }
    },
  };
</script>

<style lang="less" scoped>
.in-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;
  position: relative;
  height: 100%;
}
</style>

<style lang="less">
.in-store-pop {
  .customizedPage-print {
    padding: 9px 0;
    // display: flex;
    align-items: center;
  }
}
.in-store {
  .content {
    padding: 16px;
  }
}
.scanningInTable .ag-theme-balham .ag-header {
  display: none;
}
.scanningInTable .ag-theme-balham .ag-root-wrapper {
  border: none;
  // border-bottom: 1px solid #dadada;
  // overflow-x: hidden;
}
.scanningInTable .ag-theme-balham .ag-row {
  border: 1px solid #dadada;
  border-bottom: none;
}
.scanningInTable .ag-theme-balham .ag-row:last-child {
  border-bottom: 1px solid #dadada;
}

.scanningInTable .ag-theme-balham .ag-ltr .ag-cell-range-single-cell {
  border: none;
  background: #fff;
}

.scanningInTable .ag-theme-balham .ag-row-hover {
  background: #fff;
}

.scanningInTable .ag-theme-balham .ag-row-odd {
  background: #fff;
}

.scanningInTable .red {
  color: #ff0101;
}

.scanningInTable .green {
  color: #2baa0c;
}

.scanningInTable .ag-theme-balham .ag-cell-range-selected-1:not(.ag-cell-focus), .scanningInTable .ag-theme-balham .ag-root:not(.ag-context-menu-open) .ag-body-viewport:not(.ag-has-focus) .ag-cell-range-selected-1:not(.ag-cell-inline-editing) {
  background: unset;
}


.scanningInTable .ark-select-selection {
  width: 110px;
}

// .scanningInTable .ag-theme-balham .ag-row {
//   background: #D5E7FF;
// }
</style>
