<template>
  <view class="">
    <view class="sticky-subsection" :style="{ top: `${stickyTop}px` }">
      <view class="subsection-wrap">
        <u-subsection
          fontSize="25"
          mode="subsection"
          :list="tabList"
          :current="curNow"
          @change="sectionChange"
          activeColor="#157A2C"
        ></u-subsection>
      </view>
    </view>
    <view
      class="sticky-subsection-placeholder"
      :style="{ height: `${stickyPlaceholderHeight}px` }"
    ></view>

    <!-- Tab 0: 委外单详情 -->
    <view v-show="curNow === 0" class="basic_info">
      <view class="info_header">
        <view class="info_title">委外申请单</view>
        <u-gap height="4" bgColor="#1890FF"></u-gap>
      </view>
      <view class="info_content">
        <u-row>
          <u-col span="4">
            <view class="label">委外单编码：</view>
          </u-col>
          <u-col span="8">
            <view class="value">{{ form.code || "—" }}</view>
          </u-col>
        </u-row>
        <u-row>
          <u-col span="4">
            <view class="label">委外单名称：</view>
          </u-col>
          <u-col span="8">
            <view class="value">{{ form.name || "—" }}</view>
          </u-col>
        </u-row>
        <u-row>
          <u-col span="4">
            <view class="label">工单编码：</view>
          </u-col>
          <u-col span="8">
            <view class="value">{{ form.workOrderCode || "—" }}</view>
          </u-col>
        </u-row>
        <u-row>
          <u-col span="4">
            <view class="label">工序：</view>
          </u-col>
          <u-col span="8">
            <view class="value">{{ form.taskName || "—" }}</view>
          </u-col>
        </u-row>
        <u-row>
          <u-col span="4">
            <view class="label">委外数量：</view>
          </u-col>
          <u-col span="8">
            <view class="value">{{ form.totalCount || "—" }}</view>
          </u-col>
        </u-row>
        <u-row>
          <u-col span="4">
            <view class="label">委外重量：</view>
          </u-col>
          <u-col span="8">
            <view class="value">{{ form.totalWeight || "—" }}</view>
          </u-col>
        </u-row>
        <u-row>
          <u-col span="4">
            <view class="label">委外类型：</view>
          </u-col>
          <u-col span="8">
            <view class="value">{{ typeLabel || "—" }}</view>
          </u-col>
        </u-row>
        <u-row>
          <u-col span="4">
            <view class="label">状态：</view>
          </u-col>
          <u-col span="8">
            <view class="value">
              <text :class="['custom-tag', form.status == 1 ? 'custom-tag--success' : 'custom-tag--info']">{{ form.status == 1 ? '已发布' : '未发布' }}</text>
            </view>
          </u-col>
        </u-row>
        <u-row>
          <u-col span="4">
            <view class="label">备注：</view>
          </u-col>
          <u-col span="8">
            <view class="value">{{ form.remark || "—" }}</view>
          </u-col>
        </u-row>
        <u-row>
          <u-col span="4">
            <view class="label">预计到货日期：</view>
          </u-col>
          <u-col span="8">
            <view class="value" v-if="form.deliveryMethod == 1">{{ form.requireDeliveryTime || "—" }}</view>
            <view class="value" v-else-if="form.deliveryMethod == 2">
              <text class="link-text" @click="handleShowTimeList">分批时间</text>
            </view>
            <view class="value" v-else>—</view>
          </u-col>
        </u-row>
        <u-row>
          <u-col span="4">
            <view class="label">创建时间：</view>
          </u-col>
          <u-col span="8">
            <view class="value">{{ form.createTime || "—" }}</view>
          </u-col>
        </u-row>
      </view>

      <!-- 图片附件 -->
      <view v-if="form.technicalDrawings && form.technicalDrawings.length" class="info_content" style="margin-top: 20rpx;">
        <view class="label" style="text-align: left; padding-left: 20rpx;">图片附件：</view>
        <view v-for="link in form.technicalDrawings" :key="link.id" style="padding: 6rpx 20rpx;">
          <text class="link-text">{{ link.name }}</text>
        </view>
      </view>

      <!-- 附件 -->
      <view v-if="form.files && form.files.length" class="info_content" style="margin-top: 20rpx;">
        <view class="label" style="text-align: left; padding-left: 20rpx;">附件：</view>
        <view v-for="link in form.files" :key="link.id" style="padding: 6rpx 20rpx;">
          <text class="link-text">{{ link.name }}</text>
        </view>
      </view>
    </view>

    <!-- Tab 1: 物品清单详情 -->
    <view v-show="curNow === 1" class="basic_info">
      <view class="info_header">
        <view class="info_title">物品清单</view>
        <u-gap height="4" bgColor="#1890FF"></u-gap>
      </view>
      <view v-if="!detailList.length" class="empty_text">暂无物品清单</view>
      <view v-for="(row, idx) in detailList" :key="idx" class="card_box">
        <view class="card_title">物品 {{ idx + 1 }}</view>
        <u-row>
          <u-col span="3">
            <view class="label">编码：</view>
          </u-col>
          <u-col span="9">
            <view class="value">{{ row.categoryCode || "—" }}</view>
          </u-col>
        </u-row>
        <u-row>
          <u-col span="3">
            <view class="label">名称：</view>
          </u-col>
          <u-col span="9">
            <view class="value">{{ row.categoryName || "—" }}</view>
          </u-col>
        </u-row>
        <u-row>
          <u-col span="3">
            <view class="label">类型：</view>
          </u-col>
          <u-col span="9">
            <view class="value">
              <text v-if="row.sourceType == 1" class="custom-tag custom-tag--success">物品清单</text>
              <text v-else-if="row.sourceType == 2" class="custom-tag custom-tag--warning">带料清单</text>
              <text v-else-if="row.sourceType == 3" class="custom-tag custom-tag--error">产出清单</text>
              <text v-else>—</text>
            </view>
          </u-col>
        </u-row>
        <u-row>
          <u-col span="3">
            <view class="label">牌号：</view>
          </u-col>
          <u-col span="9">
            <view class="value">{{ row.brandNum || "—" }}</view>
          </u-col>
        </u-row>
        <u-row>
          <u-col span="3">
            <view class="label">型号：</view>
          </u-col>
          <u-col span="9">
            <view class="value">{{ row.modelType || "—" }}</view>
          </u-col>
        </u-row>
        <u-row>
          <u-col span="3">
            <view class="label">规格：</view>
          </u-col>
          <u-col span="9">
            <view class="value">{{ row.specification || "—" }}</view>
          </u-col>
        </u-row>
        <u-row>
          <u-col span="3">
            <view class="label">数量：</view>
          </u-col>
          <u-col span="9">
            <view class="value">{{ row.totalCount || "—" }}{{ row.measuringUnit || "" }}</view>
          </u-col>
        </u-row>
        <!-- detailType==2 额外字段 -->
        <template v-if="form.detailType == 2">
          <u-row>
            <u-col span="3">
              <view class="label">物料代号：</view>
            </u-col>
            <u-col span="9">
              <view class="value">{{ (row.extInfo && row.extInfo.materielCode) || "—" }}</view>
            </u-col>
          </u-row>
          <u-row>
            <u-col span="3">
              <view class="label">客户代号：</view>
            </u-col>
            <u-col span="9">
              <view class="value">{{ (row.extInfo && row.extInfo.clientCode) || "—" }}</view>
            </u-col>
          </u-row>
          <u-row>
            <u-col span="3">
              <view class="label">刻码：</view>
            </u-col>
            <u-col span="9">
              <view class="value">{{ (row.extInfo && row.extInfo.engrave) || "—" }}</view>
            </u-col>
          </u-row>
        </template>
      </view>
    </view>

    <!-- 分批时间弹窗 -->
    <u-popup :show="showTimePopup" mode="bottom" round="20" @close="showTimePopup = false">
      <view class="time-popup">
        <view class="time-popup-title">分批时间</view>
        <view class="time-popup-total">委外总数：{{ form.totalCount || 0 }}</view>
        <view v-if="!timeList.length" class="empty_text">暂无分批时间</view>
        <view v-for="(item, idx) in timeList" :key="idx" class="card_box">
          <u-row>
            <u-col span="4">
              <view class="label">数量：</view>
            </u-col>
            <u-col span="8">
              <view class="value">{{ item.purchaseQuantity || "—" }}</view>
            </u-col>
          </u-row>
          <u-row>
            <u-col span="4">
              <view class="label">到货时间：</view>
            </u-col>
            <u-col span="8">
              <view class="value">{{ formatTime(item.requireDeliveryTime) || "—" }}</view>
            </u-col>
          </u-row>
        </view>
        <view style="padding: 20rpx;">
          <u-button type="primary" text="关闭" @click="showTimePopup = false"></u-button>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import { getById } from "@/api/wt/outsourcedWarehousing.js";

const TYPE_MAP = {
  1: "采购委外",
  2: "直接发货委外",
  3: "无采购委外",
  4: "带料委外",
  5: "不带料委外",
};

export default {
  props: {
    businessId: {
      default: "",
    },
    taskDefinitionKey: {
      default: "",
    },
  },
  data() {
    return {
      form: {},
      detailList: [],
      timeList: [],
      showTimePopup: false,
      tabList: ["委外单详情", "物品清单"],
      curNow: 0,
      stickyPlaceholderHeight: 0,
      stickyTop: 44,
    };
  },
  computed: {
    typeLabel() {
      return TYPE_MAP[this.form.type] || "";
    },
  },
  async mounted() {
    this.initStickyTop();
    await this.getDetailData(this.businessId);
    this.updateStickyPlaceholderHeight();
  },
  methods: {
    initStickyTop() {
      try {
        const systemInfo = uni.getSystemInfoSync();
        const statusBarHeight = Number(systemInfo.statusBarHeight || 0);
        this.stickyTop = statusBarHeight + 44;
      } catch (error) {
        this.stickyTop = 50;
      }
    },
    updateStickyPlaceholderHeight() {
      this.$nextTick(() => {
        const query = uni.createSelectorQuery().in(this);
        query
          .select(".sticky-subsection")
          .boundingClientRect((rect) => {
            if (rect && rect.height) {
              this.stickyPlaceholderHeight = rect.height;
            }
          })
          .exec();
      });
    },
    sectionChange(index) {
      this.curNow = index;
    },

    async getDetailData(id) {
      if (!id) return;
      try {
        const res = await getById(id);
        if (res) {
          this.form = res;
          this.detailList = res.detailList || [];
          this.timeList = res.timeList || [];
        }
      } catch (e) {
        console.warn("获取委外申请单详情失败", e);
      }
    },

    handleShowTimeList() {
      this.showTimePopup = true;
    },

    formatTime(timestamp) {
      if (!timestamp) return "";
      if (typeof timestamp === "string") return timestamp;
      const date = new Date(timestamp);
      const pad = (n) => String(n).padStart(2, "0");
      return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
    },

    getTableValue() {
      return {
        form: this.form,
      };
    },
  },
};
</script>

<style lang="scss">
.sticky-subsection {
  position: fixed;
  left: 0;
  right: 0;
  z-index: 99;
  width: 100%;
  box-sizing: border-box;
  background: #f5f7fa;
}

.sticky-subsection-placeholder {
  width: 100%;
}

.subsection-wrap {
  background: #f5f7fa;
  padding: 0 16rpx 12rpx;
  width: 100%;
  box-sizing: border-box;
}

.basic_info {
  box-sizing: border-box;
  padding: 0 20rpx;
}

.info_header {
  margin-top: 10rpx;
}

.info_title {
  position: relative;
  padding: 16rpx 50rpx;
  font-size: 36rpx;
  color: #606266;
}

.info_title::after {
  content: "";
  position: absolute;
  top: 16rpx;
  left: 0px;
  width: 16rpx;
  height: 50rpx;
  background: #1890ff;
}

.info_content {
  .label {
    padding: 20rpx 0;
    text-align: right;
    font-size: 28rpx;
    font-weight: 700;
    color: #6e6e6e;
  }

  .value {
    padding: 20rpx 0;
    font-size: 28rpx;
    color: #606266;
  }
}

.card_box {
  box-sizing: border-box;
  padding: 20rpx;
  margin: 20rpx;
  width: calc(100% - 40rpx);
  border-radius: 20rpx;
  box-shadow: 0 0 12rpx -6rpx #000;

  .card_title {
    font-size: 32rpx;
    font-weight: 700;
    color: #666;
    margin-bottom: 10rpx;
  }

  .label {
    padding: 18rpx 0;
    text-align: right;
    font-size: 28rpx;
    font-weight: 700;
    color: #6e6e6e;
  }

  .value {
    padding: 18rpx 0;
    font-size: 28rpx;
    color: #606266;
  }
}

.empty_text {
  text-align: center;
  color: #909399;
  font-size: 28rpx;
  padding: 80rpx 0;
}

.tag-inline {
  display: flex;
  flex-direction: row;
  align-items: center;
  flex-wrap: wrap;
}

.tag-inline .u-tag {
  flex-shrink: 0;
}

.custom-tag {
  display: inline-block;
  padding: 4rpx 16rpx;
  font-size: 24rpx;
  border-radius: 8rpx;
  line-height: 1.5;
}

.custom-tag--success {
  color: #19be6b;
  background-color: #dbf1e1;
  border: 1px solid #d0f0d8;
}

.custom-tag--info {
  color: #909399;
  background-color: #f4f4f5;
  border: 1px solid #e9e9eb;
}

.custom-tag--warning {
  color: #f29100;
  background-color: #fdf6ec;
  border: 1px solid #faecd8;
}

.custom-tag--error {
  color: #fa3534;
  background-color: #fef0f0;
  border: 1px solid #fde2e2;
}

.link-text {
  color: #1890ff;
  font-size: 28rpx;
}

.time-popup {
  padding: 30rpx;
  max-height: 70vh;
  overflow-y: auto;

  .time-popup-title {
    font-size: 34rpx;
    font-weight: 700;
    text-align: center;
    margin-bottom: 20rpx;
  }

  .time-popup-total {
    font-size: 28rpx;
    color: #606266;
    margin-bottom: 20rpx;
    padding-left: 20rpx;
  }
}
</style>
