<template>
  <view class="page">
    <StickyNavBar>
      <NavBar :title="$t('扫码到货')"></NavBar>
    </StickyNavBar>
    <view style="padding: 0 10px;">
      <view class="scan-input-container">
        <input 
          style="flex: 1; height: 60px; border: 1px solid #ddd; border-radius: 8px; padding: 0 15px; font-size: 16px;" 
          type="text" 
          v-model="input" 
          :focus="isFocus" 
          :disabled="isEditMode"
          @focus="focus"
          @blur="blur" 
          @confirm="inputCC"
          :placeholder="$t('请扫描条码')"
        />
        <u-button 
          type="default" 
          size="mini" 
          @click="toggleEditMode"
          class="mode-toggle-btn"
        >
          {{ isEditMode ? $t('继续扫码') : $t('编辑明细') }}
        </u-button>
      </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"
          :editable="isEditMode"
          @deleGonds="deleGonds"
          @updateItem="updateItem"
        />
      </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,
      isEditMode: false,
      isEditingDetails: 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(){
      if (this.isEditMode || this.isEditingDetails) return;
      this.$nextTick(() => {
        setTimeout(()=>{
          uni.hideKeyboard();
        },500);
      });
    },
    blur(){
      this.isFocus = false;
      this.$nextTick(() => {
        setTimeout(()=>{
          if (!this.isEditMode && !this.isEditingDetails) {
            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],
              "supplierNo": arr[0]
            })
            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 {
              // 检查供应商是否一致
              if (this.goodsList.length > 0) {
                const firstSupplier = this.goodsList[0].supplierNo;
                if (firstSupplier && firstSupplier !== arr[0]) {
                  this.$u.toast(i18n.t('一个到货单无法录入两个供应商订单'));
                  this.input = '';
                  return;
                }
              }
              
              const data1 = await this.$u.api
              .getforinvmbinfo({
                mb001: arr[4]
              })
              
              // 直接使用后端返回的默认批次号
              const batchNo = (data && data.data && data.data.defBatchNo) ? data.data.defBatchNo : ''
              
              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'],
                mb148: data1.data['mb148'] || '',
                batchNo: batchNo,
                productionDate: (() => {
                  const today = new Date()
                  const yy = today.getFullYear()
                  const mm = String(today.getMonth() + 1).padStart(2, '0')
                  const dd = String(today.getDate()).padStart(2, '0')
                  return `${yy}${mm}${dd}`
                })(),
                effectiveDate: (() => {
                  const shelf = Number(data1.data['udf07']) || 0
                  if (!shelf) return ''
                  const today = new Date()
                  today.setDate(today.getDate() + shelf)
                  const yy = today.getFullYear()
                  const mm = String(today.getMonth() + 1).padStart(2, '0')
                  const dd = String(today.getDate()).padStart(2, '0')
                  return `${yy}${mm}${dd}`
                })(),
                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 = ''
        }
      }
    },
    updateItem(payload) {
      const { idx, key, value } = payload || {}
      if (typeof idx === 'number' && key) {
        this.$set(this.goodsList, idx, { ...this.goodsList[idx], [key]: value })
        const pages = getCurrentPages();
        const prevPage = pages[pages.length - 2];
        if (prevPage && prevPage.$vm) {
          prevPage.$vm.updateGoodsList(this.goodsList);
        }
      }
    },
    toggleEditMode() {
      this.isEditMode = !this.isEditMode
      if (this.isEditMode) {
        this.isFocus = false
        uni.hideKeyboard()
      } else {
        this.$nextTick(() => {
          setTimeout(() => {
            this.isFocus = true
          }, 300)
        })
      }
    },
    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;
  display: flex;
  align-items: center;
}

.mode-toggle-btn {
  margin-left: 12rpx;
  height: 60px;
  line-height: 60px;
  white-space: nowrap;
}

.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;
}

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

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