<template>
    <view class="page">
      <StickyNavBar>
        <NavBar :title="$t('录入到货单')"></NavBar>
      </StickyNavBar>
      <view style="padding: 0 10px;">
        

        <u-form ref="daohuoForm" :modelValue="daohuoForm" :rules="rules" labelWidth="200">
          <u-form-item prop="warehouse" class="under" :label="$t('到货仓')">
            <uni-data-select
            v-model="daohuoForm.warehouse"
            :clear="false"
            :localdata="typeData"
            ></uni-data-select>
          </u-form-item>
            <u-form-item prop="supplierNo" class="under" :label="$t('采购发票')">
            <input
                v-model="daohuoForm.invoiceNo"
                type="text"
                :placeholder="$t('采购发票')"
            >
          </u-form-item>
          <u-form-item prop="supplierNo" class="under" :label="$t('到货供应商')">
            <input
                v-model="daohuoForm.supplierNo"
                type="text"
                disabled
                :placeholder="$t('供应商代码')"
            >
            </input>
          </u-form-item>
        </u-form>
        
        <!-- 扫码到货按钮 -->
        <view class="scan-btn-container">
          <u-button 
            type="primary" 
            @click="goToScanning"
            :disabled="!daohuoForm.warehouse"
            style="width: 100%; height: 80rpx; font-size: 32rpx;"
          >
            {{$t('扫码到货')}}
          </u-button>
        </view>
        
        <view v-if="goodsList.length > 0">{{$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 {
        number: 0,
        totalNum: 0,
        show: true,
        goodsList: [],
        typeData: [],
        btnArr: [
        {
          style: "",
          type: "warning",
          text: i18n.t('返回'),
          way: "goBack",
        },
        {
          style: "",
          type: "primary",
          text: i18n.t('到货确认'),
          way: "goSubmit",
        },
      ],
        wxparams: "",
        loading: false,
        daohuoForm: {
					supplierNo: "",
          invoiceNo:"",
          warehouse: null
				},
        rules: {
          supplierNo: { required: true,type: 'string', trigger: ['blur'], errorMessage: "" },
          invoiceNo: { required: true,type: 'string', trigger: ['blur'], errorMessage: "" },
					purchaseType: { required: true, type: 'string',trigger: ['blur'], errorMessage: "" }
				},
      }
    },
    beforeDestroy(){

    },
    created() {
      this.warehouseList()
    },
    methods: {
      warehouseList() {
        this.$u.api.warehouseList().then(res => {
          if(res.success) {
            this.typeData = res.data.map(v => ({text: v.warehouseName, value: v.warehouseName}))
          }
        })
      },
      getBtnHandle(row) {
        this[row.way]();
      },
      goBack() {
        uni.navigateBack();
      },
      goToScanning() {
        if (!this.daohuoForm.warehouse) {
          this.$u.toast(i18n.t('请先选择到货仓'));
          return;
        }
        uni.navigateTo({
          url: '/pages/dhd/scanning'
        });
      },
      // 接收扫码页面返回的数据
      updateGoodsList(newGoodsList) {
        if (newGoodsList && newGoodsList.length > 0) {
          // 先验证供应商是否一致
          if (this.goodsList.length > 0 && newGoodsList[0] && newGoodsList[0].supplierNo) {
            const currentSupplier = this.goodsList[0].supplierNo;
            if (currentSupplier && currentSupplier !== newGoodsList[0].supplierNo) {
              this.$u.toast(i18n.t('一个到货单无法录入两个供应商订单'));
              return;
            }
          }
          
          // 智能合并数据，避免重复累加
          newGoodsList.forEach(newItem => {
            const existingIndex = this.goodsList.findIndex(item => item.joinlabel === newItem.joinlabel);
            if (existingIndex > -1) {
              // 如果已存在，直接替换数量（因为scanning页面已经处理了累加逻辑）
              this.goodsList[existingIndex].arrivalQuantity = Number(newItem.arrivalQuantity);
            } else {
              // 如果不存在，添加新项
              this.goodsList.push(newItem);
            }
          });
          
          // 更新供应商信息（只有在验证通过后才更新）
          if (newSupplierNo && !currentSupplierNo) {
            this.daohuoForm.supplierNo = newSupplierNo;
          }
        }
      },
    deleGonds(idx) {
      this.goodsList.splice(idx, 1);
      // 如果删除了所有商品，清空供应商信息
      if (this.goodsList.length === 0) {
        this.daohuoForm.supplierNo = '';
      }
    },
    goSubmit(){
      if (!this.goodsList.length) return;
        if(!this.daohuoForm.warehouse) return this.$u.toast(i18n.t('请选择到货仓'));
        this.loading = true;
        this.$u.api.confirmArrival({
          warehouse: this.daohuoForm.warehouse,
          invoiceNo: this.daohuoForm.invoiceNo,
          details: this.goodsList.map(v => ({arrivalQuantity: v.arrivalQuantity, materialNo: v.materialNo, purchaseNo: v.purchaseNo, purchaseSerial: v.purchaseSerial, purchaseType: v.purchaseType, supplierNo: v.supplierNo}))
        })
        .then(res => {
          this.loading = false;
          if (res.success) {
            this.$u.toast(i18n.t('确认成功'));
            this.goodsList = [];
            this.daohuoForm.supplierNo = '';
            this.daohuoForm.invoiceNo='';
          } else {
          this.$u.toast(res.errorMessage);
        }
        });
      }
    },
  };
  </script>
  
  <style lang="scss" scoped>
  .page {
    background: #fff;
  }
  .btn {
    padding: 20rpx;
    background: #fff;
    .topSearch {
      margin-bottom: 20rpx;
    }
  }
  .scan-btn-container {
    margin: 30rpx 0;
  }
  .bottomBtn {
    position: sticky;
    padding: 20rpx;
    display: flex;
    justify-content: space-between;
    background: #fff;
    bottom: 0rpx;
    margin-top: 20rpx;
    .u-btn {
      width: 300rpx;
    }
  }
  .blue {
    color: #3f9dcc;
  }
  .total {
    background: #fff;
    color: #000;
    padding: 0rpx 40rpx;
    display: flex;
    justify-content: space-between;
    font-size: 32rpx;
    .line {
      margin: 0px 10rpx;
    }
  }
  .cardbox {
    border: 1px solid #dadde2;
    border-radius: 5px;
    background: #f3f3f5;
    margin: 0rpx 20rpx;
    margin-top: 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%;
  }

  .cardbox {
  min-height: calc(100vh - 570rpx);
  padding: 0rpx 20rpx;
  margin-top: 20rpx;
}
  </style>
  