<template>
  <u-popup
    :show="show"
    mode="bottom"
    :round="10"
    closeable
    @close="cancel"
    bgColor="#fff"
    :customStyle="{ maxHeight: '85vh', overflowY: 'auto' }"
  >
    <view class="nc_wrap">
      <view class="title">{{ title }}</view>

      <view class="section_title">报工信息</view>
      <view class="form_row">
        <view class="label required">实际开始时间</view>
        <view class="picker_box" @click="!isDetail && openTimePicker('realStartTime')">
          <text v-if="form.realStartTime" class="val">{{ form.realStartTime }}</text>
          <text v-else class="placeholder">请选择实际开始时间</text>
        </view>
      </view>
      <view class="form_row">
        <view class="label required">实际结束时间</view>
        <view class="picker_box" @click="!isDetail && openTimePicker('realEndTime')">
          <text v-if="form.realEndTime" class="val">{{ form.realEndTime }}</text>
          <text v-else class="placeholder">请选择实际结束时间</text>
        </view>
      </view>

      <view class="info_grid">
        <view class="info_item" v-for="item in fields" :key="item.prop">
          <view class="info_label">{{ item.label }}</view>
          <view class="info_val">{{ form[item.prop] || '-' }}</view>
        </view>
      </view>

      <view class="form_row" v-if="form.remark">
        <view class="label">订单备注</view>
        <view class="readonly_text">{{ form.remark }}</view>
      </view>

      <view class="form_row">
        <view class="label">附件</view>
        <view class="file_list">
          <view
            v-for="(f, idx) in form.fileParam"
            :key="(f && f.id) || idx"
            class="file_item"
          >
            <text class="file_name">{{ f.name || f.fileName || ("附件" + (idx + 1)) }}</text>
            <text v-if="!isDetail" class="file_del" @click="removeFile(idx)">删除</text>
          </view>
          <button v-if="!isDetail" class="upload_btn" @click="chooseFile">+ 上传附件</button>
        </view>
      </view>

      <view class="form_row">
        <view class="label">{{ isDetail ? '报备注' : '备注' }}</view>
        <textarea
          class="ipt textarea"
          v-model="form.reportRemark"
          :disabled="isDetail"
          placeholder="请输入"
          maxlength="-1"
        />
      </view>

      <view class="btns">
        <button class="btn cancel" @click="cancel">关闭</button>
        <button v-if="!isDetail" class="btn confirm" @click="submit">报工</button>
      </view>
    </view>

    <u-datetime-picker
      :show="timeShow"
      v-model="timeValue"
      mode="datetime"
      @confirm="onTimeConfirm"
      @cancel="timeShow = false"
      @close="timeShow = false"
      :closeOnClickOverlay="true"
    ></u-datetime-picker>
  </u-popup>
</template>

<script>
import { ncTaskReport } from "@/api/pda/workReport.js";

export default {
  data() {
    return {
      show: false,
      title: "NC任务报工",
      type: "",
      form: {
        realStartTime: "",
        realEndTime: "",
        brandNum: "",
        categoryName: "",
        categoryCode: "",
        code: "",
        productionPlanCode: "",
        produceRoutingName: "",
        taskName: "",
        modelType: "",
        specification: "",
        fileParam: [],
        remark: "",
        reportRemark: "",
      },
      fields: [
        { label: "牌号", prop: "brandNum" },
        { label: "名称", prop: "categoryName" },
        { label: "编码", prop: "categoryCode" },
        { label: "任务编号", prop: "code" },
        { label: "计划编号", prop: "productionPlanCode" },
        { label: "工艺路线", prop: "produceRoutingName" },
        { label: "工序名称", prop: "taskName" },
        { label: "型号", prop: "modelType" },
        { label: "规格", prop: "specification" },
      ],
      timeShow: false,
      timeField: "",
      timeValue: Date.now(),
    };
  },
  computed: {
    isDetail() {
      return this.type === "detail";
    },
  },
  methods: {
    open(item, type) {
      this.type = type || "";
      this.title = this.isDetail ? "NC任务详情" : "NC任务报工";
      this.form = {
        realStartTime: "",
        realEndTime: "",
        fileParam: [],
        remark: "",
        reportRemark: "",
        ...JSON.parse(JSON.stringify(item || {})),
      };
      this.show = true;
    },
    cancel() {
      this.show = false;
    },
    openTimePicker(field) {
      this.timeField = field;
      const cur = this.form[field];
      this.timeValue = cur ? new Date(cur.replace(/-/g, "/")).getTime() : Date.now();
      this.timeShow = true;
    },
    onTimeConfirm(e) {
      const d = new Date(e.value);
      const pad = (n) => String(n).padStart(2, "0");
      this.form[this.timeField] =
        d.getFullYear() +
        "-" +
        pad(d.getMonth() + 1) +
        "-" +
        pad(d.getDate()) +
        " " +
        pad(d.getHours()) +
        ":" +
        pad(d.getMinutes()) +
        ":" +
        pad(d.getSeconds());
      this.timeShow = false;
    },
    chooseFile() {
      const max = 9;
      const cur = this.form.fileParam || [];
      const remain = max - cur.length;
      if (remain <= 0) {
        return uni.showToast({ title: "最多上传9个附件", icon: "none" });
      }
      uni.chooseImage({
        count: remain,
        sizeType: ["compressed"],
        sourceType: ["camera", "album"],
        success: (res) => this.uploadFiles(res.tempFilePaths),
      });
    },
    uploadFiles(paths) {
      uni.showLoading({ title: "上传中..." });
      const tasks = paths.map(
        (p) =>
          new Promise((resolve, reject) => {
            uni.uploadFile({
              url: this.apiUrl + "/main/file/upload",
              filePath: p,
              name: "multiPartFile",
              header: { authorization: uni.getStorageSync("token") },
              success: (r) => {
                try {
                  const data = JSON.parse(r.data);
                  if (data.code == 0) resolve(data.data);
                  else reject(data.message || "上传失败");
                } catch (e) {
                  reject("上传失败");
                }
              },
              fail: () => reject("上传失败"),
            });
          }),
      );
      Promise.all(tasks)
        .then((arr) => {
          if (!this.form.fileParam) this.form.fileParam = [];
          this.form.fileParam.push(...arr);
          uni.hideLoading();
          uni.showToast({ title: "上传成功", icon: "success" });
        })
        .catch((err) => {
          uni.hideLoading();
          uni.showToast({ title: err || "上传失败", icon: "none" });
        });
    },
    removeFile(idx) {
      this.form.fileParam.splice(idx, 1);
    },
    submit() {
      if (!this.form.realStartTime)
        return uni.showToast({ title: "请选择实际开始时间", icon: "none" });
      if (!this.form.realEndTime)
        return uni.showToast({ title: "请选择实际结束时间", icon: "none" });
      if (!this.form.reportRemark)
        return uni.showToast({ title: "请输入备注", icon: "none" });

      const payload = {
        ...this.form,
        fileParam: (this.form.fileParam || []).map((f) =>
          f && typeof f === "object" ? { id: f.id } : { id: f },
        ),
      };

      ncTaskReport(payload)
        .then(() => {
          uni.showToast({ title: "报工成功", icon: "success" });
          this.$emit("refreshList");
          this.cancel();
        })
        .catch((err) => {
          uni.showToast({ title: err.message || "报工失败", icon: "none" });
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.nc_wrap {
  padding: 30rpx;
  .title {
    font-size: 32rpx;
    font-weight: 600;
    text-align: center;
    margin-bottom: 20rpx;
  }
  .section_title {
    font-size: 28rpx;
    font-weight: 600;
    color: #333;
    margin: 20rpx 0 16rpx;
    padding-left: 16rpx;
    border-left: 6rpx solid $theme-color;
  }
  .form_row {
    margin-bottom: 20rpx;
    .label {
      font-size: 26rpx;
      color: #333;
      margin-bottom: 8rpx;
      &.required::before {
        content: "*";
        color: red;
        margin-right: 4rpx;
      }
    }
    .picker_box {
      border: 1rpx solid #e0e0e0;
      border-radius: 6rpx;
      padding: 14rpx 16rpx;
      font-size: 26rpx;
      min-height: 60rpx;
      .placeholder { color: #aaa; }
    }
    .ipt {
      border: 1rpx solid #e0e0e0;
      border-radius: 6rpx;
      padding: 14rpx 16rpx;
      font-size: 26rpx;
      width: 100%;
      box-sizing: border-box;
    }
    .textarea { min-height: 120rpx; }
    .readonly_text {
      padding: 14rpx 16rpx;
      background: #f7f9fa;
      border-radius: 6rpx;
      font-size: 26rpx;
      color: #666;
      line-height: 40rpx;
      word-break: break-all;
    }
    .file_list {
      display: flex;
      flex-wrap: wrap;
      gap: 12rpx;
      .file_item {
        display: flex;
        align-items: center;
        background: #f7f9fa;
        padding: 8rpx 14rpx;
        border-radius: 6rpx;
        font-size: 24rpx;
        max-width: 100%;
        .file_name {
          color: #333;
          word-break: break-all;
          margin-right: 10rpx;
        }
        .file_del {
          color: #f5222d;
          font-size: 22rpx;
        }
      }
      .upload_btn {
        height: 56rpx;
        line-height: 56rpx;
        padding: 0 22rpx;
        background: #fff;
        color: $theme-color;
        border: 1rpx dashed $theme-color;
        border-radius: 6rpx;
        font-size: 24rpx;
        margin: 0;
      }
    }
  }
  .info_grid {
    display: flex;
    flex-wrap: wrap;
    background: #f7f9fa;
    padding: 16rpx;
    border-radius: 8rpx;
    margin-bottom: 20rpx;
    .info_item {
      width: 50%;
      padding: 8rpx 6rpx;
      font-size: 24rpx;
      box-sizing: border-box;
      .info_label { color: #999; margin-bottom: 4rpx; }
      .info_val { color: #333; word-break: break-all; }
    }
  }
  .btns {
    display: flex;
    gap: 20rpx;
    margin-top: 30rpx;
    .btn {
      flex: 1;
      height: 80rpx;
      line-height: 80rpx;
      border-radius: 8rpx;
      font-size: 28rpx;
    }
    .cancel { background: #f5f5f5; color: #333; }
    .confirm { background: $theme-color; color: #fff; }
  }
}
</style>
