<template>
  <view class="page">
    <StickyNavBar>
      <NavBar :title="$t('扫码到货')"></NavBar>
    </StickyNavBar>
    <view style="padding: 0 10px;">
      <view class="scan-input-container">
        <input 
          style="width: 100%; height: 60px; border: 1px solid #ddd; border-radius: 8px; padding: 0 15px; font-size: 16px;" 
          type="text" 
          v-model="input" 
          :focus="isFocus" 
          @focus="focus"
          @blur="blur" 
          @confirm="inputCC"
          :placeholder="$t('请扫描条码')"
        />
      </view>
      
      <view v-if="goodsList.length > 0" class="scan-result-title">{{$t('扫码结果')}}</view>
    </view>
    
    <ContentLoadingMore class="cardbox" :list="goodsList">
      <view class="cardContent" v-for="(item, index) in goodsList" :key="index">
        <scanningList
          :item="item"
          :idx="index"
          @deleGonds="deleGonds"
        />
      </view>
    </ContentLoadingMore>
    
    <BottomBtn :btnArr="btnArr" @getBtnHandle="getBtnHandle"></BottomBtn>
  </view>
</template>

<script>
import i18n from '../../lang/index'
import scanningList from "./scanningList.vue";
import BottomBtn from "@/components/BottomBtn/index.vue";
import StickyNavBar from "@/components/StickyNavBar/index.vue";
import ContentLoadingMore from "@/components/ContentLoadingMore/index.vue";

export default {
  components: {
    StickyNavBar,
    scanningList,
    BottomBtn,
    ContentLoadingMore,
  },
  data() {
    return {
      goodsList: [],
      isFocus: false,
      input: '',
      btnArr: [
        {
          style: "",
          type: "warning",
          text: i18n.t('返回'),
          way: "goBack",
        }
      ],
    }
  },
  created() {
    this.$nextTick(() => {
      this.isFocus = true;
    });
  },
  onLoad(options) {
    // 接收主页面传递的数据
    const pages = getCurrentPages();
    const prevPage = pages[pages.length - 2];
    if (prevPage && prevPage.$vm && prevPage.$vm.goodsList) {
      this.goodsList = [...prevPage.$vm.goodsList];
    }
  },
  methods: {
    focus(){
      this.$nextTick(() => {
        setTimeout(()=>{
          uni.hideKeyboard();
        },500);
      });
    },
    blur(){
      this.isFocus = false;
      this.$nextTick(() => {
        setTimeout(()=>{
          this.isFocus = true;
        },500);
      });
    },
    getBtnHandle(row) {
      this[row.way]();
    },
    goBack() {
      uni.navigateBack();
    },
    // 每次扫码成功后自动同步数据到主页面
    async inputCC(e){
      if(e.detail.value && e.detail.value) {
        if(e.detail.value.includes("-")){
          const arr = e.detail.value.split("-")
          if (arr.length === 6) {
            const data = await this.$u.api.validateArrival({
              "materialNo": arr[4],
              "purchaseNo": arr[2],
              "purchaseSerial": arr[3],
              "purchaseType": arr[1]
            })
            if (!data.success) return this.input = ''
            const index = this.goodsList.findIndex(v => v.joinlabel === arr.slice(0, 5).join('-'))
            if (index > -1) {
              this.goodsList[index]['arrivalQuantity'] = Number(this.goodsList[index]['arrivalQuantity']) + Number(arr[5])
            } else {
              const data1 = await this.$u.api
              .getforinvmbinfo({
                mb001: arr[4]
              })
              
              // 生成批号：品号+客户+日期yyyyMMdd
              const today = new Date()
              const dateStr = today.getFullYear().toString() + 
                            (today.getMonth() + 1).toString().padStart(2, '0') + 
                            today.getDate().toString().padStart(2, '0')
              const customer = arr[0] // 使用供应商号作为客户，如果没有则使用默认值
              const batchNo = arr[4] + customer + dateStr
              
              this.goodsList.push({
                supplierNo: arr[0],
                purchaseType: arr[1],
                purchaseNo: arr[2],
                purchaseSerial: arr[3],
                materialNo: arr[4],
                arrivalQuantity: arr[5],
                udf07: data1.data['udf07'],
                mb002: data1.data['mb002'],
                mb029: data1.data['mb029'],
                batchNo: batchNo,
                joinlabel: arr.slice(0, 5).join('-')
              })
            }
            this.input = ''
            // 自动同步到主页面
            const pages = getCurrentPages();
            const prevPage = pages[pages.length - 2];
            if (prevPage && prevPage.$vm) {
              prevPage.$vm.updateGoodsList(this.goodsList);
            }
          } else {
            this.input = ''
          }
        } else {
          this.input = ''
        }
      }
    },
    deleGonds(idx) {
      this.goodsList.splice(idx, 1);
      // 删除后也同步到主页面
      const pages = getCurrentPages();
      const prevPage = pages[pages.length - 2];
      if (prevPage && prevPage.$vm) {
        prevPage.$vm.updateGoodsList(this.goodsList);
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.page {
  background: #fff;
}

.scan-input-container {
  margin: 20rpx 0;
}

.scan-result-title {
  font-size: 32rpx;
  font-weight: bold;
  margin: 20rpx 0;
  color: #333;
}

.cardbox {
  border: 1px solid #dadde2;
  border-radius: 5px;
  background: #f3f3f5;
  margin: 0rpx 20rpx;
  margin-top: 20rpx;
  min-height: calc(100vh - 570rpx);
  padding: 0rpx 20rpx;
}

.cardContent {
  border-radius: 8px;
  background: #fff;
  margin-top: 20rpx;
}

/deep/ .u-sticky {
  top: 0 !important;
  background: #fff;
}

page {
  position: relative;
  width: 100%;  
  height: 100%;
}
</style> 