<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">{{ 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">{{ priorityLabel || "—" }}</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.pleaseEntrustDeptName || "—" }}</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.pleaseEntrustUserName || "—" }}</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.factoriesName || "—" }}</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.beEntrustedFactoriesName || "—"
            }}</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.beEntrustedDeptName || "—" }}</view>
          </u-col>
        </u-row>
      </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="!orderList.length" class="empty_text">暂无产品信息</view>
      <view v-for="(row, idx) in orderList" :key="idx" class="card_box">
        <view class="card_title">产品 {{ idx + 1 }}</view>
        <u-row>
          <u-col span="4">
            <view class="label">产品名称：</view>
          </u-col>
          <u-col span="8">
            <view class="value">{{ row.categoryName || "—" }}</view>
          </u-col>
        </u-row>
        <u-row>
          <u-col span="4">
            <view class="label">计划编号：</view>
          </u-col>
          <u-col span="8">
            <view class="value">{{ row.productionPlanCode || "—" }}</view>
          </u-col>
        </u-row>
        <u-row>
          <u-col span="4">
            <view class="label">牌号：</view>
          </u-col>
          <u-col span="8">
            <view class="value">{{ row.brandNum || "—" }}</view>
          </u-col>
        </u-row>
        <u-row>
          <u-col span="4">
            <view class="label">批次号：</view>
          </u-col>
          <u-col span="8">
            <view class="value">{{ row.batchNo || "—" }}</view>
          </u-col>
        </u-row>
        <u-row>
          <u-col span="4">
            <view class="label">需求描述：</view>
          </u-col>
          <u-col span="8">
            <view class="value">{{ row.describes || "—" }}</view>
          </u-col>
        </u-row>
        <u-row>
          <u-col span="4">
            <view class="label">请托数量：</view>
          </u-col>
          <u-col span="8">
            <view class="value"
              >{{ row.totalCount || "—" }}{{ row.measuringUnit || "" }}</view
            >
          </u-col>
        </u-row>
        <u-row>
          <u-col span="4">
            <view class="label">计划类型：</view>
          </u-col>
          <u-col span="8">
            <view class="value">{{
              getPlanTypeLabel(row.planType) || "—"
            }}</view>
          </u-col>
        </u-row>
        <u-row>
          <u-col span="4">
            <view class="label">生产工单号：</view>
          </u-col>
          <u-col span="8">
            <view class="value">{{ row.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">{{ row.specification || "—" }}</view>
          </u-col>
        </u-row>
        <u-row>
          <u-col span="4">
            <view class="label">名称：</view>
          </u-col>
          <u-col span="8">
            <view class="value">{{ row.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">{{ row.modelType || "—" }}</view>
          </u-col>
        </u-row>
        <u-row>
          <u-col span="4">
            <view class="label">工艺路线：</view>
          </u-col>
          <u-col span="8">
            <view class="value">{{ row.produceRoutingName || "—" }}</view>
          </u-col>
        </u-row>
        <u-row>
          <u-col span="4">
            <view class="label">BOM分类：</view>
          </u-col>
          <u-col span="8">
            <view class="value">{{ getBomTypeLabel(row.bomType) || "—" }}</view>
          </u-col>
        </u-row>
        <u-row>
          <u-col span="4">
            <view class="label">BOM版本：</view>
          </u-col>
          <u-col span="8">
            <view class="value">{{ getBomVersionLabel(row) || "—" }}</view>
          </u-col>
        </u-row>
        <u-row>
          <u-col span="4">
            <view class="label">工序：</view>
          </u-col>
          <u-col span="8">
            <view class="value">{{ row.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">{{ row.categoryCode || "—" }}</view>
          </u-col>
        </u-row>
        <u-row>
          <u-col span="4">
            <view class="label">完成日期：</view>
          </u-col>
          <u-col span="8">
            <view class="value">{{ row.planDeliveryTime || "—" }}</view>
          </u-col>
        </u-row>
        <u-row>
          <u-col span="4">
            <view class="label">计划开始时间：</view>
          </u-col>
          <u-col span="8">
            <view class="value">{{ row.planStartTime || "—" }}</view>
          </u-col>
        </u-row>
        <u-row>
          <u-col span="4">
            <view class="label">计划结束时间：</view>
          </u-col>
          <u-col span="8">
            <view class="value">{{ row.planCompleteTime || "—" }}</view>
          </u-col>
        </u-row>
        <u-row>
          <u-col span="4">
            <view class="label">工单开始时间：</view>
          </u-col>
          <u-col span="8">
            <view class="value">{{ row.startTime || "—" }}</view>
          </u-col>
        </u-row>
        <u-row>
          <u-col span="4">
            <view class="label">工单结束时间：</view>
          </u-col>
          <u-col span="8">
            <view class="value">{{ row.completeTime || "—" }}</view>
          </u-col>
        </u-row>
      </view>
    </view>
  </view>
</template>

<script>
import {
  pleaseEntrustDetail,
  getProduceTaskList,
} from "@/api/entrust/index.js";

import { getDictByCode } from "@/api/common";

const PLAN_TYPE_MAP = {
  1: "内销计划",
  2: "外销计划",
  3: "预制计划",
};

const BOM_TYPE_MAP = {
  1: "产品(PBOM)",
  2: "加工(MBOM)",
  3: "装配(ABOM)",
};

export default {
  props: {
    businessId: {
      default: "",
    },
    taskDefinitionKey: {
      default: "",
    },
  },
  data() {
    return {
      form: {
        name: "",
        type: "",
        priority: "",
        pleaseEntrustDeptName: "",
        pleaseEntrustUserName: "",
        factoriesName: "",
        beEntrustedFactoriesName: "",
        beEntrustedDeptName: "",
      },
      orderList: [],
      typeList: [],
      tabList: ["基本信息", "产品信息"],
      curNow: 0,
      stickyPlaceholderHeight: 0,
      stickyTop: 44,
      options: [
        { name: "一般", value: 1 },
        { name: "紧急", value: 2 },
      ],
    };
  },
  computed: {
    typeLabel() {
      if (!this.form.type && this.form.type !== 0) return "";
      const item = this.typeList.find((i) => i.value == this.form.type);
      return item ? item.label : "";
    },
    priorityLabel() {
      const item = this.options.find((i) => i.value == this.form.priority);
      return item ? item.name : "";
    },
  },
  async mounted() {
    await this.getTypeList();
    this.initStickyTop();
    await this.init();
    this.updateStickyPlaceholderHeight();
  },
  methods: {
    initStickyTop() {
      try {
        const systemInfo = uni.getSystemInfoSync();
        const statusBarHeight = Number(systemInfo.statusBarHeight || 0);
        this.stickyTop = statusBarHeight + 44;
      } catch (error) {
        this.stickyTop = 50;
      }
    },

    async getTypeList() {
      try {
        const res = await getDictByCode("entrust_type");
        if (res?.length != 0) {
          let list = res.map((item) => {
            let key = Object.keys(item)[0];
            return { value: Number(key), label: item[key] };
          });
          this.typeList = list;
        }
      } catch (error) {
        console.error("获取类型列表失败", error);
      }
    },

    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 init() {
      if (!this.businessId) return;
      try {
        const data = await pleaseEntrustDetail(this.businessId);
        const {
          applyDeptName,
          applyDeptId,
          createUserName,
          createUserId,
          applyFactoriesId,
          applyFactoriesName,
          beEntrustedDeptId,
          beEntrustedDeptName,
          beEntrustedFactoriesName,
          beEntrustedFactoriesId,
          name,
          type,
          priority,
          id: dataId,
        } = data;

        Object.assign(this.form, {
          pleaseEntrustDeptName: applyDeptName,
          pleaseEntrustDeptId: applyDeptId,
          pleaseEntrustUserName: createUserName,
          pleaseEntrustUserId: createUserId,
          factoriesId: applyFactoriesId,
          factoriesName: applyFactoriesName,
          beEntrustedDeptId,
          beEntrustedDeptName,
          beEntrustedFactoriesName,
          beEntrustedFactoriesId,
          name,
          type,
          priority,
          id: dataId,
        });

        const newData = {
          ...this.deepCopy(data),
          taskList: [],
        };
        this.orderList.push(newData);
        this.getOrderTaskList();
        this.form.type = this.form.type + "";
      } catch (e) {
        console.warn("获取请托详情失败", e);
      }
    },

    deepCopy(obj, hash = new WeakMap()) {
      if (obj === null) return null;
      if (obj instanceof Date) return new Date(obj);
      if (obj instanceof RegExp) return new RegExp(obj);
      if (typeof obj !== "object" && typeof obj !== "function") return obj;
      if (hash.has(obj)) return hash.get(obj);
      const result = Array.isArray(obj) ? [] : {};
      hash.set(obj, result);
      return Object.keys(obj).reduce((acc, key) => {
        acc[key] = this.deepCopy(obj[key], hash);
        return acc;
      }, result);
    },

    async getOrderTaskList() {
      for (const item of this.orderList) {
        try {
          const res = await getProduceTaskList({
            isDetail: true,
            pageNum: 1,
            routingId: item.produceRoutingId,
            size: -1,
          });
          item.taskList = res.list || [];
          if (item.taskId && item.taskList.length) {
            const matched = item.taskList.find((t) => t.id === item.taskId);
            if (matched) {
              this.$set(item, "taskName", matched.name);
            }
          }
        } catch (e) {
          console.warn("获取工序列表失败", e);
        }
      }
    },

    getPlanTypeLabel(val) {
      return PLAN_TYPE_MAP[val] || "";
    },
    getBomTypeLabel(val) {
      return BOM_TYPE_MAP[val] || "";
    },
    getBomVersionLabel(row) {
      if (row.bomCategoryName) {
        return `${row.bomCategoryName} (V${row.bomCategoryVersions}.0)`;
      }
      return "";
    },

    getTableValue() {
      return {
        form: this.form,
        orderList: this.orderList,
      };
    },
  },
};
</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;
}
</style>
