<template>
  <view class="content-box">
    <uni-nav-bar
      fixed="true"
      statusBar="true"
      left-icon="back"
      :title="title"
      background-color="#157A2C"
      color="#fff"
      @clickLeft="back"
    ></uni-nav-bar>

    <view class="list_box">
      <u-list>
        <u-list-item v-for="(item, index) in goodsList" :key="index">
          <view class="goods-item">
            <view class="goods-header">
              <checkbox-group
                v-if="type === 'add'"
                @change="checkboxChange($event, item)"
              >
                <checkbox
                  :value="item.id"
                  :checked="item.checked"
                  color="#157A2C"
                />
              </checkbox-group>
              <text class="goods-name">{{ item.categoryName }}</text>
              <view class="goods-type">
                <text class="type-tag">{{
                  getTypeName(item.rootCategoryLevelId)
                }}</text>
              </view>
            </view>

            <view class="goods-row">
              <text class="label">牌号:</text>
              <text class="value">{{ item.brandNum }}</text>
            </view>

            <view class="goods-row">
              <text class="label">批次号:</text>
              <text class="value">{{ item.batchNo }}</text>
            </view>

            <view class="goods-row">
              <text class="label">数量:</text>
              <text class="value"
                >{{ item.quantity }}{{ item.measuringUnit }}</text
              >
            </view>

            <view class="goods-row">
              <text class="label">重量:</text>
              <text class="value">{{ item.weight }}{{ item.weightUnit }}</text>
            </view>

            <view class="goods-row">
              <text class="label">生产工单号:</text>
              <text class="value">{{ item.workOrderCode }}</text>
            </view>

            <view class="goods-row">
              <text class="label">规格:</text>
              <text class="value">{{ item.specification }}</text>
            </view>

            <view class="goods-row">
              <text class="label">型号:</text>
              <text class="value">{{ item.modelType }}</text>
            </view>

            <view class="goods-row">
              <text class="label">编码:</text>
              <text class="value">{{ item.categoryCode }}</text>
            </view>

            <view v-if="type !== 'send'" class="goods-row receive-row">
              <text class="label">接收数量:</text>
              <view class="input-wrapper">
                <u-input
                  v-model="item.receiveQuantity"
                  type="digit"
                  :disabled="type === 'detail'"
                  placeholder="请输入接收数量"
                  :customStyle="{ flex: 1 }"
                  :inputAlign="'left'"
                  border="surround"
                />
                <text class="unit">{{ item.measuringUnit }}</text>
              </view>
            </view>
          </view>
        </u-list-item>

        <u-list-item v-if="goodsList.length === 0">
          <view class="empty-wrapper">
            <u-empty iconSize="150" textSize="32" text="暂无货物信息"></u-empty>
          </view>
        </u-list-item>
      </u-list>
    </view>

    <view v-if="type === 'add'" class="footer-btns">
      <u-button class="btn-cancel" @click="handleCancel">取消</u-button>
      <u-button type="error" class="btn-reject" @click="handleReject"
        >驳回</u-button
      >
      <u-button type="success" class="btn-confirm" @click="handleConfirm"
        >确定</u-button
      >
    </view>
  </view>
</template>

<script>
import {
  beEntrustDetail,
  beEntrustGoodsDetail,
  confirmReceipt,
  rejectGoods,
} from "@/api/beEntrust/index";

export default {
  data() {
    return {
      type: "add",
      title: "收货单",
      itemData: {},
      goodsList: [],
      selection: [],
      id: "",
    };
  },

  onLoad(options) {
    this.type = options.type || "add";
    this.id = options.id;
    this.title =
      this.type === "add"
        ? "收货单"
        : this.type === "send"
          ? "发货单"
          : "收货详情";

    if (this.id) {
      this.getDetailData();
    }
  },

  methods: {
    back() {
      uni.navigateBack();
    },

    async getDetailData() {
      try {
        const detailRes = await beEntrustDetail(this.id);
        this.itemData = detailRes || {};
        await this.getGoodsDetail();
      } catch (error) {
        uni.showToast({
          title: "加载失败",
          icon: "none",
        });
      }
    },

    async getGoodsDetail() {
      try {
        const detailType = this.type !== "send" ? 1 : 2;
        const res = await beEntrustGoodsDetail({
          id: this.id,
          detailType,
        });

        this.goodsList = [];
        if (res && res.length > 0) {
          res.forEach((item) => {
            if (this.type !== "detail") {
              item.receiveQuantity = item.quantity;
            }
            item.checked = false;
            item.sendStatus = 2;
            this.goodsList.push({ ...item });
          });
        }
      } catch (error) {
        uni.showToast({
          title: "加载失败",
          icon: "none",
        });
      }
    },

    checkboxChange(e, item) {
      item.checked = e.detail.value.length > 0;
      this.updateSelection();
    },

    updateSelection() {
      this.selection = this.goodsList.filter((item) => item.checked);
    },

    getTypeName(type) {
      const typeMap = {
        1: "原材料",
        2: "半成品",
        3: "成品",
        4: "辅料",
        5: "包材",
      };
      return typeMap[type] || "";
    },

    handleCancel() {
      uni.navigateBack();
    },

    handleReject() {
      uni.showModal({
        title: "驳回原因",
        editable: true,
        placeholderText: "请输入驳回原因",
        success: async (res) => {
          if (res.confirm && res.content) {
            uni.showModal({
              title: "提示",
              content: "确认要驳回该收货单吗？",
              success: async (confirmRes) => {
                if (confirmRes.confirm) {
                  uni.showLoading({ title: "驳回中..." });
                  try {
                    const ids = this.goodsList.map((it) => it.id);
                    await rejectGoods({
                      ids,
                      applyId: this.id,
                      beReason: res.content,
                    });
                    uni.hideLoading();
                    uni.showToast({
                      title: "驳回成功",
                      icon: "success",
                    });
                    setTimeout(() => {
                      uni.navigateBack();
                    }, 1500);
                  } catch (error) {
                    uni.hideLoading();
                    uni.showToast({
                      title: "驳回失败",
                      icon: "none",
                    });
                  }
                }
              },
            });
          }
        },
      });
    },

    async handleConfirm() {
      if (this.selection.length === 0) {
        uni.showToast({
          title: "请先选择一条收货数据",
          icon: "none",
        });
        return;
      }

      const selectionIds = new Set(this.selection.map((it) => it.id));
      this.goodsList.forEach((item) => {
        if (!selectionIds.has(item.id)) {
          item.receiveQuantity = 0;
        }
      });

      const totalNum = this.selection.reduce(
        (total, pro) => total + Number(pro.receiveQuantity || 0),
        0,
      );
      const formingNum = Number(this.itemData.sendOutQuantity);

      let confirmMessage = "";
      if (totalNum < formingNum) {
        confirmMessage = "收货数量小于请托数量，是否继续收货？";
      } else if (totalNum > formingNum) {
        confirmMessage = "收货数量大于请托数量，是否继续收货？";
      }

      const doConfirmReceipt = async () => {
        uni.showLoading({ title: "收货中..." });
        try {
          await confirmReceipt(this.goodsList);
          uni.hideLoading();
          uni.showToast({
            title: "收货成功",
            icon: "success",
          });
          setTimeout(() => {
            uni.navigateBack();
          }, 1500);
        } catch (error) {
          uni.hideLoading();
          uni.showToast({
            title: "收货失败",
            icon: "none",
          });
        }
      };

      if (confirmMessage) {
        uni.showModal({
          title: "提示",
          content: confirmMessage,
          success: (res) => {
            if (res.confirm) {
              doConfirmReceipt();
            }
          },
        });
      } else {
        doConfirmReceipt();
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.content-box {
  height: 100vh;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  background-color: $page-bg;
}

.list_box {
  flex: 1;
  overflow: hidden;
  padding: 16rpx 0;

  .u-list {
    height: 100% !important;
  }

  /deep/ .u-list-item {
    width: 100%;
  }
}

.goods-item {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 24rpx;
  margin: 0 24rpx 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.08);
  overflow: hidden;

  .goods-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;
    padding-bottom: 20rpx;
    border-bottom: 1rpx solid #f0f0f0;
    gap: 16rpx;

    checkbox-group {
      display: flex;
      align-items: center;
    }

    .goods-name {
      flex: 1;
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }

    .type-tag {
      display: inline-block;
      padding: 4rpx 16rpx;
      background-color: rgba(21, 122, 44, 0.1);
      color: $theme-color;
      border-radius: 4rpx;
      font-size: 24rpx;
    }
  }

  .goods-row {
    display: flex;
    align-items: center;
    margin-bottom: 12rpx;
    font-size: 28rpx;
    width: 100%;

    .label {
      color: #999;
      width: 180rpx;
      flex-shrink: 0;
    }

    .value {
      flex: 1;
      color: #333;
      word-break: break-all;
    }

    .input-wrapper {
      flex: 1;
      display: flex;
      align-items: center;
      min-width: 0;

      .unit {
        margin-left: 8rpx;
        color: #999;
        white-space: nowrap;
        flex-shrink: 0;
      }
    }

    &.receive-row {
      /deep/ .u-input {
        flex: 1;
      }
    }
  }
}

.empty-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  padding-top: 25vh;
}

.footer-btns {
  display: flex;
  gap: 20rpx;
  padding: 20rpx 32rpx;
  background-color: #fff;
  box-shadow: 0 -2rpx 8rpx rgba(0, 0, 0, 0.08);
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);

  /deep/ .u-button {
    flex: 1;
    height: 80rpx;
    border-radius: 40rpx;
    font-size: 30rpx;
  }

  .btn-cancel {
    background-color: #fff;
    color: #666;
    border: 1rpx solid #e0e0e0;
  }
}
</style>
