<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-if="type !== 'detail' && type !== 'receipt'">
          <view class="btn-group">
            <u-button type="success" class="btn-add" @click="addGoods">新增在制品</u-button>
          </view>
        </u-list-item>

        <!-- 货物列表 -->
        <u-list-item v-for="(item, index) in goodsList" :key="index">
          <view class="goods-item">
          <view class="goods-header">
            <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 === 'receipt'" class="goods-row">
            <text class="label">接收数量:</text>
            <view class="input-wrapper">
              <input
                v-model="item.receiveQuantity"
                type="digit"
                :disabled="itemData.sendStatus == 4"
                class="quantity-input"
                placeholder="请输入接收数量"
              />
              <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 !== 'detail' && itemData.sendStatus != 4" class="footer-btns">
      <u-button class="btn-cancel" @click="handleCancel">取消</u-button>
      <u-button v-if="type === 'receipt'" 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 {
  pleaseEntrustDetail,
  pleaseEntrustGoodsDetail,
  pleaseEntrustSaveDetail,
  pleaseTReceiveGoods
} from '@/api/entrust/index';

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

  onLoad(options) {
    this.type = options.type || 'add';
    this.id = options.id;
    this.title = this.type !== 'receipt' ? '发货单' : '收货单';

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

  methods: {
    async getDetailData() {
      try {
        // 先获取请托详情
        const detailRes = await pleaseEntrustDetail(this.id);
        this.itemData = detailRes || {};

        // 再获取货物详情
        await this.getGoodsDetail();
      } catch (error) {
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        });
      }
    },

    async getGoodsDetail() {
      try {
        const detailType = this.type === 'receipt' ? 2 : 1;
        const res = await pleaseEntrustGoodsDetail({
          id: this.id,
          detailType
        });

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

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

    addGoods() {
      const existingIds = encodeURIComponent(JSON.stringify(this.goodsList));
      uni.navigateTo({
        url: `/pages/pda/entrust/selectGoods/selectGoods?id=${this.id}&existingIds=${existingIds}`
      });
    },

    receiveGoods(selectedList) {
      // 接收选择的在制品数据
      this.goodsList = selectedList.map(item => ({ ...item }));
    },

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

    handleReject() {
      uni.showModal({
        title: '驳回原因',
        editable: true,
        placeholderText: '请输入驳回原因',
        success: (res) => {
          if (res.confirm && res.content) {
            // 处理驳回逻辑
            uni.showToast({
              title: '已驳回',
              icon: 'success'
            });
            setTimeout(() => {
              uni.navigateBack();
            }, 1500);
          }
        }
      });
    },

    async handleConfirm() {
      if (this.type !== 'receipt') {
        // 发货
        if (this.goodsList.length === 0) {
          uni.showToast({
            title: '请先新增一条在制品数据',
            icon: 'none'
          });
          return;
        }

        uni.showLoading({ title: '发货中...' });

        try {
          await pleaseEntrustSaveDetail(this.goodsList);
          uni.hideLoading();
          uni.showToast({
            title: '发货成功',
            icon: 'success'
          });
          setTimeout(() => {
            // 通知上一页刷新
            const pages = getCurrentPages();
            const prevPage = pages[pages.length - 2];
            if (prevPage && prevPage.$vm.getDetail) {
              prevPage.$vm.getDetail();
            }
            uni.navigateBack();
          }, 1500);
        } catch (error) {
          uni.hideLoading();
          uni.showToast({
            title: '发货失败',
            icon: 'none'
          });
        }
      } else {
        // 收货
        uni.showLoading({ title: '收货中...' });

        try {
          await pleaseTReceiveGoods(this.goodsList);
          uni.hideLoading();
          uni.showToast({
            title: '收货成功',
            icon: 'success'
          });
          setTimeout(() => {
            // 通知上一页刷新
            const pages = getCurrentPages();
            const prevPage = pages[pages.length - 2];
            if (prevPage && prevPage.$vm.getDetail) {
              prevPage.$vm.getDetail();
            }
            uni.navigateBack();
          }, 1500);
        } catch (error) {
          uni.hideLoading();
          uni.showToast({
            title: '收货失败',
            icon: 'none'
          });
        }
      }
    }
  }
};
</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;
  }
}

.btn-group {
  padding: 0 24rpx 20rpx;

  .btn-add {
    width: 100%;
    height: 70rpx;
    border-radius: 35rpx;
    font-size: 28rpx;
  }
}

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

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

    .goods-name {
      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: 16rpx;
    font-size: 28rpx;

    .label {
      color: #999;
      min-width: 180rpx;
    }

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

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

      .quantity-input {
        flex: 1;
        padding: 12rpx 16rpx;
        border: 1rpx solid #e0e0e0;
        border-radius: 6rpx;
        font-size: 28rpx;
      }

      .unit {
        margin-left: 8rpx;
        color: #999;
      }
    }
  }
}

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