<template>
  <div>
    <div class="pda-container">
      <div class="status-bar">
        <div class="goBack" @click="handleBack"><i class="el-icon-arrow-left"></i>上一页</div>
        <div class="goBack">采购订单接收</div>
        <div class="network" style="color: #fff" @click="$router.push({ path: '/' })">🏠首页</div>
      </div>
      <div style="overflow-y: auto">
        <!-- Step 1: 扫描 -->
        <div v-if="processFlag === 1">
          <div class="scan-box" style="margin: 2px;">
            <el-input clearable v-model="scanCode" placeholder="扫描PO条码或输入PO号"
                      @keyup.enter.native="searchPoList" ref="scanCodeRef" />
          </div>
          <div class="item-list" v-if="poList.length > 0" style="margin: 2px;">
            <el-form label-position="top" style="margin: 3px;">
              <el-row :gutter="5" @click.native="recvLine(poDetail)"
                      v-for="(poDetail, index) in poList" :key="index" :class="index < poList.length - 1 ? 'bottom-line-row' : ''">
                <el-col :span="8">
                  <el-form-item label="商品编码"><span>{{ poDetail.partNo }}</span></el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="行号/下达号"><span>{{ poDetail.lineNo }}/{{ poDetail.wdr }}</span></el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="">
                    <el-button type="text" class="recvButton" @click="recvLine(poDetail)"
                               style="margin-top: 10px;margin-left: 20px" size="small">接收</el-button>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="商品描述"><span>{{ poDetail.description }}</span></el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="订单数量"><span>{{ poDetail.purchaseQty }}</span></el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="待收数量"><span>{{ poDetail.qtyToReceive }}</span></el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="此次接收数量"><span>{{ poDetail.thisRecvQty }}</span></el-form-item>
                </el-col>
                <el-col :span="6" >
                  <el-form-item style="margin-left: 20px" label="单位"><span>{{ poDetail.inventoryUOM }}</span></el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </div>

        <!-- Step 2: 收货明细 -->
        <div v-if="processFlag === 2">
          <el-form label-position="top" class="form-section" style="margin: 5px;">
            <el-row :gutter="20">
              <el-col :span="12"><el-form-item label="PO号码"><el-input v-model="recvItem.orderNo" disabled /></el-form-item></el-col>
              <el-col :span="12"><el-form-item label="行号/下达号"><el-input v-model="displayLineWdr" disabled /></el-form-item></el-col>
              <el-col :span="12"><el-form-item label="商品编码"><el-input v-model="recvItem.partNo" disabled /></el-form-item></el-col>
              <el-col :span="12"><el-form-item label="计量单位"><el-input v-model="recvItem.inventoryUOM" disabled /></el-form-item></el-col>
              <el-col :span="24"><el-form-item label="商品名称"><el-input v-model="recvItem.description" disabled /></el-form-item></el-col>
              <el-col :span="12"><el-form-item label="订单数量"><el-input v-model="recvItem.purchaseQty" disabled /></el-form-item></el-col>
              <el-col :span="12"><el-form-item label="待收数量"><el-input v-model="recvItem.qtyToReceive" disabled /></el-form-item></el-col>
              <el-col :span="12">
                <el-form-item label="此次接收数量">
                  <el-input v-model="recvItem.transQty" :disabled="recvItem.needHandlingUnit === 'Y'" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label=" ">
                  <el-button type="text" @click.stop="handlingUnitStep" :disabled="recvItem.needHandlingUnit !== 'Y'"
                             :class="{ 'disabled-button': recvItem.needHandlingUnit !== 'Y' }"
                             style="font-size: 16px" size="small">包装记录</el-button>
                </el-form-item>
              </el-col>
              <el-col :span="12"><el-form-item label="制造日期"><el-date-picker v-model="recvItem.manufactureDate" type="date" format="yyyy-MM-dd" value-format="yyyy-MM-dd" placeholder="选择制造日期" style="width: 100%" /></el-form-item></el-col>
              <el-col :span="12"><el-form-item label="失效日期"><el-date-picker v-model="recvItem.expiringDate" type="date" format="yyyy-MM-dd" value-format="yyyy-MM-dd" placeholder="选择失效日期" style="width: 100%" /></el-form-item></el-col>
              <el-col :span="12"><el-form-item label="库位"><el-input v-model="recvItem.locationNo" placeholder="请输入库位" /></el-form-item></el-col>
              <el-col :span="12"><el-form-item label="批号"><el-input v-model="recvItem.batchNo" placeholder="请输入批号" /></el-form-item></el-col>
              <el-col :span="8" style="margin-top: 10px"><el-form-item><el-button type="text" style="font-size: 16px;margin-left: 30px" @click="processFlag = 1">回退</el-button></el-form-item></el-col>
              <el-col :span="8" style="margin-top: 10px"><el-form-item><el-button type="text" style="font-size: 16px;margin-left: 20px" @click="receivePo">保存</el-button></el-form-item></el-col>
              <el-col :span="8" style="margin-top: 10px"><el-form-item><el-button type="text" style="font-size: 16px;margin-left: 10px" @click="$router.push('/')">退出</el-button></el-form-item></el-col>
            </el-row>
          </el-form>
        </div>

        <!-- Step 3: 包装记录 -->
        <div v-if="processFlag === 3">
          <el-form label-position="top" class="form-section" style="margin: 5px;">
            <el-row :gutter="20">
              <el-col :span="12"><el-form-item label="商品编码"><el-input v-model="recvItem.partNo" disabled /></el-form-item></el-col>
              <el-col :span="12"><el-form-item label="计量单位"><el-input v-model="recvItem.unit" disabled /></el-form-item></el-col>
              <el-col :span="24"><el-form-item label="商品名称"><el-input v-model="recvItem.desc" disabled /></el-form-item></el-col>
              <el-col :span="8"><el-form-item label="单包装数量"><el-input v-model="hanlingItem.perQty" /></el-form-item></el-col>
              <el-col :span="8"><el-form-item label="包装数"><el-input v-model="hanlingItem.packageQty" /></el-form-item></el-col>
              <el-col :span="8" style="margin-top: 24px"><el-form-item>
                <el-button type="text" @click="createHandlingUnit" style="font-size: 16px">创建</el-button></el-form-item></el-col>
              <el-table :data="handlingUnit" :row-style="{ height: '30px' }" style="width: 94%; margin-left: 10px;" highlight-current-row>
                <el-table-column prop="code" label="Unit ID" />
                <el-table-column prop="qty" label="数量" width="60" />
                <el-table-column label="操作">
                  <template slot-scope="scope">
                    <a @click="removeItem(scope.$index)">删除</a>
                  </template>
                </el-table-column>
              </el-table>
              <el-col :span="24"><el-form-item><span>合计</span><span style="margin-left: 38%">{{ totalQty }}</span></el-form-item></el-col>
              <el-col :span="12"><el-form-item><el-button type="text" @click="processFlag = 2" style="font-size: 18px;margin-left: 60px">回退</el-button></el-form-item></el-col>
              <el-col :span="12"><el-form-item><el-button type="text" @click="processFlag = 2" style="font-size: 18px;">确定</el-button></el-form-item></el-col>
            </el-row>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getPoList, receivePo } from "@/api/po/po.js";

export default {
  data() {
    return {
      processFlag: 1,
      scanCode: '',
      poList: [],
      recvItem: {},
      handlingUnit: [],
      hanlingItem: { code: '', qty: '', perQty: '', packageQty: '' },
      site:localStorage.getItem('site')
    };
  },
  computed: {
    totalQty() {
      const sum = this.handlingUnit.reduce((sum, item) => sum + Number(item.qty), 0);
      this.recvItem.transQty = sum;
      return sum;
    },
    huKey() {
      return `hu_${this.recvItem.poNumber}_${this.recvItem.lineNo}`;
    },
    displayLineWdr() {
      return `${this.recvItem.lineNo || ''}/${this.recvItem.wdr || ''}`;
    }
  },
  methods: {
    handleBack() {
      if (this.processFlag === 1) this.$router.back();
      else if (this.processFlag === 3) this.processFlag = 2;
      else this.processFlag = 1;
    },
    searchPoList() {
      if (!this.scanCode) return this.poList = [];
      getPoList({ poNumber: this.scanCode,site: this.site }).then(({ data }) => {
        if (data.code === 0) this.poList = data.rows;
      });
    },
    recvLine(row) {
      this.recvItem = {
        ...row,
        poNo: row.poNumber || this.scanCode,
        dueinQty: row.qtyToReceive || row.thisRecvQty,
        transQty: row.thisRecvQty || 0
      };
      this.processFlag = 2;
    },
    handlingUnitStep() {
      this.processFlag = 3;
      const saved = localStorage.getItem(this.huKey);
      this.handlingUnit = saved ? JSON.parse(saved) : [];
    },
    createHandlingUnit() {
      const { perQty, packageQty } = this.hanlingItem;
      if (!perQty || !packageQty || isNaN(perQty) || isNaN(packageQty)) {
        return this.$message.warning("请填写有效的包装信息");
      }
      const qty = parseFloat(perQty) * parseInt(packageQty);
      const code = 'H' + String(this.handlingUnit.length + 1).padStart(3, '0');
      const newItem = { ...this.hanlingItem, qty, code };
      this.handlingUnit.push(newItem);
      localStorage.setItem(this.huKey, JSON.stringify(this.handlingUnit));
    },
    removeItem(index) {
      this.handlingUnit.splice(index, 1);
      localStorage.setItem(this.huKey, JSON.stringify(this.handlingUnit));
    },
    receivePo() {
      const item = this.recvItem;
      if (!item.transQty || !item.locationNo || !item.batchNo) {
        return this.$message.error("请填写完整信息");
      }

      // 构建符合服务端TransDetailDto结构的数据
      const receiveData = {
        // 基本字段
        site: this.site,
        partNo: item.partNo,
        transQty: item.transQty,
        batchNo: item.batchNo,
        locationNo: item.locationNo,
        itemNo: 1,

        // PO相关字段
        poNo: item.poNumber || item.poNo,
        orderNo: item.orderNo,
        lineNo: item.lineNo,
        relNo: item.relNo,
        receiptNo: item.receiptNo,

        // 业务控制字段
        needHandlingUnit: item.needHandlingUnit || 'N',
        needCheck: item.needCheck || 'N',
        warehouseType: item.warehouseType || 'MANUAL',
        needPallet: item.needPallet || 'N',
        workshopFlag: item.workshopFlag || 'N',
        cuttingFlag: item.cuttingFlag || 'N',

        // 日期字段
        manufactureDate: item.manufactureDate,
        // 注意：失效日期由服务端自动计算，不需要传递
        // expiredDate: item.expiringDate,

        // 处理单元列表
        handlingUnitList: item.needHandlingUnit === 'Y' ? this.handlingUnit.map(hu => ({
          perQty: hu.qty,
          packageQty: 1
        })) : []
      };

      receivePo(receiveData).then(({ data }) => {
        if (data.code === 0) {
          this.$message.success("操作成功");
          localStorage.removeItem(this.huKey);
          this.processFlag = 1;
          this.scanCode = '';
          this.poList = [];
          this.recvItem = {};
          this.handlingUnit = [];
        } else {
          this.$message.error(data.msg || '操作失败');
        }
      }).catch(error => {
        console.error('接收失败:', error);
        this.$message.error('网络错误，请重试');
      });
    }
  },
  mounted() {
    this.$nextTick(() => this.$refs.scanCodeRef.focus());
  }
};
</script>

<style scoped>
.scan-box input {
  width: 100%;
  padding: 12px;
  font-size: 16px;
}
.item-list {
  flex: 1;
  overflow-y: auto;
  margin: 10px 0;
  border: 1px solid rgba(200, 200, 200, 0.8);
}
.item-list span {
  color: #000;
  font-size: 15px;
}
.bottom-line-row {
  border-bottom: 1px solid rgba(200, 200, 200, 0.8);
}
.recvButton {
  font-size: 16px;
  border-radius: 3px;
  color: #17b3a3;
}
.item-list .el-row {
  cursor: pointer;
  transition: background 0.3s;
}
.item-list .el-row:hover {
  background: #f5f7fa;
}
.disabled-button {
  color: #ccc !important;
  cursor: not-allowed !important;
}
.form-section >>> .el-col {
  margin-bottom: 12px;
}
.status-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #17b3a3;
  color: white;
}
</style>
