<template>
  <view>
    <view class="title_box rx-bc">
      <view class="name">工单信息 </view>
      <view
        class="btn_box rx-bc"
        @click="handleScan(item.workOrderId)"
        v-if="!isDetails"
      >
        <image class="scan" src="@/static/pda/ScanIt.svg"></image>
        更换工单
      </view>
    </view>

    <view class="material">
      <view class="content_table">
        <view class="item">
          <view class="lable rx-cc">工单编号</view>
          <view class="content">
            {{ item.code }}
          </view>
        </view>

        <view class="item">
          <view class="lable rx-cc">编码</view>
          <view class="content">{{ item.productCode }}</view>
        </view>
        <view class="item">
          <view class="lable rx-cc">规格</view>
          <view class="content">{{ item.specification }}</view>
        </view>

        <view class="item">
          <view class="lable rx-cc">名称</view>
          <view class="content">{{ item.productName }}</view>
        </view>

        <view class="item">
          <view class="lable rx-cc">批次号</view>
          <view class="content">{{ item.batchNo }}</view>
        </view>

        <view class="item">
          <view class="lable rx-cc">牌号</view>
          <view class="content">{{
            item.brandNo ? item.brandNo : item.brandNum
          }}</view>
        </view>

        <view class="item">
          <view class="lable rx-cc">型号</view>
          <view class="content">{{
            item.modelType ? item.modelType : item.model
          }}</view>
        </view>
        <view class="item">
          <view class="lable rx-cc">生产编号</view>
          <view class="content">{{ item.productionCodes }}</view>
        </view>
        <view class="item rx-sc">
          <view class="rx ww55">
            <view class="lable rx-cc">生产数量</view>
            <view class="content rx-sc">
              <view>{{ item.formingNum }}</view>
              <view class="unit">{{ item.unit }}</view>
            </view>
          </view>

          <view class="rx ww45">
            <view class="lable rx-cc ww80">重量</view>
            <view class="content content_num">
              <view>{{ item.formingWeight }}</view>
              <view class="unit">{{ item.weightUnit }}</view>
            </view>
          </view>
        </view>

        <view class="item" v-if="isReportWork">
          <view class="lable rx-cc">生产要求</view>
          <!-- <view class="content" :disabled="isDetails">{{
            item.productionCodes
          }}</view> -->
          <view class="content content_num">
            <input
              style="width: 100%"
              :disabled="isDetails"
              class="uni-input"
              v-model="item.productionRequirements"
            />
          </view>
        </view>
      </view>
    </view>
    <!-- {{ clientEnvironmentId }} {{ pType }} -->
    <view class="title_box mt20 rx-bc" v-if="pType == 'feed'">
      <view class="name"> 实际投料时间 </view>
    </view>

    <view class="material" v-if="pType == 'feed'">
      <view class="content_table">
        <view class="item">
          <view class="content">
            <uni-datetime-picker
              type="datetime"
              :value="currentExecutorTime"
              @change="changeTime($event, item)"
            />
          </view>
        </view>
      </view>
    </view>

    <view class="title_box mt20 rx-bc" v-if="pType == 'job' && !isReportTime">
      <view class="name"> 实际报工时间 </view>
    </view>

    <view class="material" v-if="pType == 'job' && !isReportTime">
      <view class="content_table">
        <view class="item">
          <view class="content">
            <uni-datetime-picker
              type="datetime"
              :value="currentExecutorTime"
              @change="changeTime($event, item)"
            />
          </view>
        </view>
      </view>
    </view>

    <view class="title_box mt20 rx-bc" v-if="pType == 'job' && isReportTime">
      <view class="name"> 实际报工时间 </view>
    </view>

    <view class="material" v-if="pType == 'job' && isReportTime">
      <view class="content_table">
        <view class="item">
          <view class="content">
            <uni-datetime-picker
              v-model="datetimerange"
              type="datetimerange"
              rangeSeparator="至"
            />
          </view>
        </view>

        <view class="item" v-if="isReportWork && pType == 'job'">
          <view class="lable rx-cc">工时</view>

          <view class="content content_num">
            <input style="width: 40%" v-model="item.workTime" />小时
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { parameterGetByCode } from "@/api/mainData/index.js";
export default {
  props: {
    item: {
      type: Object,
      default: () => {},
    },
    isDetails: {
      type: Boolean,
      default: false,
    },

    isReportWork: {
      type: Boolean,
      default: false,
    },

    pType: {
      type: "",
      default: "",
    },

    taskType: {
      type: "",
      default: "",
    },
  },
  data() {
    return {
      clientEnvironmentId:
        uni.getStorageSync("userInfo") &&
        uni.getStorageSync("userInfo").clientEnvironmentId,
      currentExecutorTime: "",
      isReportTime: false,
      datetimerange: [],
    };
  },
  watch: {
    datetimerange: {
      deep: true,
      handler(val) {
        if (!(this.pType == "job" && this.isReportTime)) return;
        this.applyDateTimeRange(val);
      },
    },
    item: {
      immediate: true,
      deep: true,
      handler() {
        // 初始化/回显：当外部把 start/end 带进来时，同步到 range 组件
        if (!(this.pType == "job" && this.isReportTime)) return;
        const start =
          this.item?.workReportInfo?.executorStartTime ||
          this.item?.executorStartTime ||
          "";
        const end =
          this.item?.workReportInfo?.executorTime ||
          this.item?.executorTime ||
          "";
        if (start && end) {
          const range = [
            this.normalizeDateTime(start),
            this.normalizeDateTime(end),
          ];
          // 避免反复触发 watch 造成抖动
          if (
            !Array.isArray(this.datetimerange) ||
            this.datetimerange.length !== 2 ||
            this.datetimerange[0] !== range[0] ||
            this.datetimerange[1] !== range[1]
          ) {
            this.datetimerange = range;
          }
        }
      },
    },
  },
  // watch: {
  //   item: {
  //     immediate: true,
  //     deep: true,
  //     handler(newVal) {
  //       // this.deviceList = newVal
  //       //设备下拉框数据来源
  //       this.getByCode();
  //       // this.$set(this.item, "executorTime", this.currentExecutorTime);
  //       // this.$set(
  //       //   this.item.workReportInfo,
  //       //   "executorTime",
  //       //   this.currentExecutorTime
  //       // );
  //     },
  //   },
  // },

  created() {
    this.getByCode();
    this.getChooseEngrave();
  },
  methods: {
    changeTime(e, val) {
      let a = e.split(" ");
      console.log(a);
      if (a[1] !== "") {
        this.currentExecutorTime = e;
      } else {
        this.currentExecutorTime = `${e}00:00:00`;
      }
      this.item.executorTime = this.currentExecutorTime;
    },

    normalizeDateTime(value) {
      if (!value) return "";
      const v = String(value).trim();
      // yyyy-MM-dd => yyyy-MM-dd 00:00:00
      const dateOnly = /^\d{4}-\d{2}-\d{2}$/;
      if (dateOnly.test(v)) return `${v} 00:00:00`;
      return v;
    },

    parseDateTime(value) {
      const v = this.normalizeDateTime(value);
      if (!v) return null;
      // 兼容部分环境 Date("yyyy-MM-dd HH:mm:ss") 的解析问题
      const safe = v.replace(/-/g, "/");
      const d = new Date(safe);
      return Number.isNaN(d.getTime()) ? null : d;
    },

    hoursDiff(start, end) {
      const s = this.parseDateTime(start);
      const e = this.parseDateTime(end);
      if (!s || !e) return "";
      const ms = e.getTime() - s.getTime();
      if (ms < 0) return "";
      // 保留 2 位小数（小时）
      return (ms / 36e5).toFixed(2);
    },

    applyDateTimeRange(range) {
      // 清空时间范围时，同步清空开始/结束/工时，避免残留
      if (
        !Array.isArray(range) ||
        range.length !== 2 ||
        !range[0] ||
        !range[1]
      ) {
        this.clearReportTimesAndWorkTime();
        return;
      }
      const start = this.normalizeDateTime(range[0]);
      const end = this.normalizeDateTime(range[1]);
      if (!start || !end) {
        this.clearReportTimesAndWorkTime();
        return;
      }

      const s = this.parseDateTime(start);
      const e = this.parseDateTime(end);
      if (!s || !e) return;

      // 结束时间不能大于当前时间：超出则回填为当前时间
      const now = new Date();
      if (e.getTime() > now.getTime()) {
        const pad2 = (n) => String(n).padStart(2, "0");
        const nowStr = `${now.getFullYear()}-${pad2(now.getMonth() + 1)}-${pad2(now.getDate())} ${pad2(now.getHours())}:${pad2(now.getMinutes())}:${pad2(now.getSeconds())}`;
        this.datetimerange = [start, nowStr];
        uni.showToast({
          title: "结束时间不能大于当前时间",
          icon: "none",
        });
        this.setReportTimes(start, nowStr);
        this.setWorkTime(this.hoursDiff(start, nowStr));
        return;
      }

      if (e.getTime() < s.getTime()) {
        // 结束不能小于开始：直接把结束回填为开始，并提示
        this.datetimerange = [start, start];
        uni.showToast({
          title: "结束时间不能小于开始时间",
          icon: "none",
        });
        this.setReportTimes(start, start);
        this.setWorkTime(this.hoursDiff(start, start));
        return;
      }

      this.setReportTimes(start, end);
      this.setWorkTime(this.hoursDiff(start, end));
    },

    clearReportTimesAndWorkTime() {
      if (!this.item) return;
      if (!this.item.workReportInfo) {
        this.$set(this.item, "workReportInfo", {});
      }
      this.$set(this.item.workReportInfo, "executorStartTime", "");
      this.$set(this.item.workReportInfo, "executorTime", "");
      this.$set(this.item.workReportInfo, "workTime", "");

      this.$set(this.item, "executorStartTime", "");
      this.$set(this.item, "executorTime", "");
      this.$set(this.item, "workTime", "");
      this.$forceUpdate();
    },

    setReportTimes(start, end) {
      if (!this.item) return;
      if (!this.item.workReportInfo) {
        this.$set(this.item, "workReportInfo", {});
      }
      this.$set(this.item.workReportInfo, "executorStartTime", start);
      this.$set(this.item.workReportInfo, "executorTime", end);

      // 兼容页面上其他逻辑可能直接读 item 上的字段
      this.$set(this.item, "executorStartTime", start);
      this.$set(this.item, "executorTime", end);
    },

    setWorkTime(hours) {
      if (hours === "") return;
      if (!this.item) return;
      if (!this.item.workReportInfo) {
        this.$set(this.item, "workReportInfo", {});
      }
      this.$set(this.item.workReportInfo, "workTime", hours);
      this.$set(this.item, "workTime", hours);
      this.$forceUpdate();
    },
    async getByCode() {
      await parameterGetByCode({ code: "mes_order_feed_by_default_date" }).then(
        (res) => {
          console.log("res", res);
          if (res.value == "1") {
            if (!this.item.executorTime) {
              const now = new Date();
              const year = now.getFullYear();
              const month = String(now.getMonth() + 1).padStart(2, "0");
              const day = String(now.getDate()).padStart(2, "0");
              const hours = String(now.getHours()).padStart(2, "0");
              const minutes = String(now.getMinutes()).padStart(2, "0");
              const seconds = String(now.getSeconds()).padStart(2, "0");
              this.currentExecutorTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
              this.item.executorTime = this.currentExecutorTime;
              // this.item.workReportInfo.executorTime = this.currentExecutorTime;
              this.$set(this.item, "executorTime", this.currentExecutorTime);
              // 确保 workReportInfo 对象存在后再设置属性
              if (!this.item.workReportInfo) {
                this.$set(this.item, "workReportInfo", {});
              }
              this.$set(
                this.item.workReportInfo,
                "executorTime",
                this.currentExecutorTime,
              );
              this.$forceUpdate();
            }
          }
        },
      );
    },

    async getChooseEngrave() {
      await parameterGetByCode({
        code: "work_hour",
      }).then((res) => {
        this.isReportTime = res.value == "1" ? true : false;

        if (this.isReportTime) {
          // 第二个时间不能为空，否则组件会显示 NAN-NAN-NAN，默认用当前时间
          const start = this.item.feedLastTime || "";
          if (start) {
            const now = new Date();
            const pad2 = (n) => String(n).padStart(2, "0");
            const nowStr = `${now.getFullYear()}-${pad2(now.getMonth() + 1)}-${pad2(now.getDate())} ${pad2(now.getHours())}:${pad2(now.getMinutes())}:${pad2(now.getSeconds())}`;
            this.datetimerange = [start, nowStr];
            // 赋值后计算两个时间段的时间差并写入工时
            this.applyDateTimeRange(this.datetimerange);
          } else {
            this.datetimerange = [];
          }
        }
      });
    },
    handleScan(id) {
      this.$emit("handleScan", id, "wordOrder");
    },
  },
};
</script>

<style lang="scss" scoped>
.title_box {
  .name {
    font-size: 28rpx;
    font-style: normal;
    font-weight: 400;
    color: $theme-color;
    padding-left: 20rpx;

    position: relative;

    &:before {
      position: absolute;
      content: "";
      left: 0rpx;
      top: 0rpx;
      bottom: 0rpx;
      width: 4rpx;
      height: 28rpx;
      background: $theme-color;
      margin: auto;
    }
  }

  .btn_box {
    padding: 0 18rpx;
    height: 60rpx;
    background: $theme-color;
    font-size: 26rpx;
    font-style: normal;
    font-weight: 400;
    font-size: 24rpx;
    color: #fff;
    border-radius: 4rpx;

    .scan {
      width: 34rpx;
      height: 34rpx;
      margin-right: 12rpx;
    }
  }
}

.material {
  margin-top: 10rpx;

  .content_table {
    width: 100%;
    border: 2rpx solid $border-color;

    .item {
      display: flex;
      border-bottom: 2rpx solid $border-color;

      .lable {
        width: 132rpx;
        text-align: center;
        background-color: #f7f9fa;
        font-size: 26rpx;
        border-right: 2rpx solid $border-color;
        flex-shrink: 0;
      }

      .lable150 {
        width: 156rpx !important;
        font-size: 24rpx;
      }

      .ww80 {
        width: 80rpx;
      }

      .content {
        width: 518rpx;
        min-height: 64rpx;
        font-size: 28rpx;
        line-height: 28rpx;
        font-style: normal;
        font-weight: 400;
        padding: 18rpx 8rpx;
        box-sizing: border-box;
        word-wrap: break-word;
        flex-grow: 1 !important;

        .unit {
          padding: 0 4rpx;
          font-size: 24rpx;
          color: #404446;
        }
      }

      .content_num {
        display: flex;
        align-items: center;
        padding: 0 4rpx;

        /deep/ .uni-input-input {
          border: 2rpx solid #f0f8f2;
          background: #f0f8f2;
          color: $theme-color;
        }
      }

      .pd4 {
        padding: 4rpx 8rpx;
      }

      &:last-child {
        border-bottom: none;
      }
    }

    .ww55 {
      width: 55%;
    }

    .ww45 {
      width: 45%;
    }
  }
}

.mt20 {
  margin-top: 20rpx;
}
</style>
