const { bookingDraft } = require("../../mock/photoBook");

function cloneDraft() {
  return JSON.parse(JSON.stringify(bookingDraft));
}

function formatHour(hour) {
  return `${hour < 10 ? "0" : ""}${hour}:00`;
}

Page({
  data: {
    form: cloneDraft(),
    remark: "",
    contact: "",
    errors: {},
    submitState: "idle",
    startHour: 14,
  },

  onLoad() {
    this.syncTimeByHour(this.data.startHour);
  },

  syncTimeByHour(startHour) {
    const endHour = Math.min(startHour + 3, 23);
    this.setData({
      startHour,
      "form.startTime": formatHour(startHour),
      "form.endTime": formatHour(endHour),
      "form.validation.timeValid": true,
      "errors.time": "",
    });
  },

  onTapDate(e) {
    const picked = e.currentTarget.dataset.date;
    const dateList = this.data.form.dateList.map((item) => ({
      ...item,
      active: item.date === picked,
    }));

    this.setData({
      "form.dateList": dateList,
      "form.validation.dateValid": true,
      "errors.date": "",
    });
  },

  onChangeTime(e) {
    const startHour = Number(e.detail.value || 9);
    this.syncTimeByHour(startHour);
  },

  onTapDevice(e) {
    const id = e.currentTarget.dataset.id;
    const devices = this.data.form.devices.map((item) => ({
      ...item,
      active: item.id === id,
    }));
    this.setData({
      "form.devices": devices,
    });
  },

  onInputRemark(e) {
    this.setData({
      remark: e.detail.value,
    });
  },

  onInputContact(e) {
    const contact = e.detail.value;
    const valid = this.isContactValid(contact);
    this.setData({
      contact,
      "form.validation.contactValid": valid,
      "errors.contact": valid || !contact ? "" : "请填写有效手机号或微信号",
    });
  },

  isContactValid(contact) {
    return /(^1\d{10}$)|(^[a-zA-Z0-9_-]{5,}$)/.test((contact || "").trim());
  },

  getSelectedDate() {
    return (this.data.form.dateList || []).find((item) => item.active);
  },

  validateBeforeSubmit() {
    const errors = {};
    const selectedDate = this.getSelectedDate();
    const contactValid = this.isContactValid(this.data.contact);

    if (!selectedDate) {
      errors.date = "请选择拍摄日期";
    }

    if (!contactValid) {
      errors.contact = "请填写有效手机号或微信号";
    }

    this.setData({
      errors,
      "form.validation.dateValid": !errors.date,
      "form.validation.contactValid": contactValid,
      "form.submitState": Object.keys(errors).length ? "error" : "idle",
    });

    return Object.keys(errors).length === 0;
  },

  onTapSubmit() {
    if (this.data.submitState === "loading") {
      return;
    }

    if (!this.validateBeforeSubmit()) {
      wx.showToast({
        title: "请先完善预约信息",
        icon: "none",
      });
      return;
    }

    const selectedDate = this.getSelectedDate();
    const dateText = `2026年03月${selectedDate.date}日 ${selectedDate.day}`;
    const timeText = `${this.data.form.startTime} - ${this.data.form.endTime}`;
    const contactText = this.data.contact;

    this.setData({
      submitState: "loading",
      "form.submitState": "loading",
    });

    setTimeout(() => {
      this.setData({
        submitState: "idle",
        "form.submitState": "idle",
      });
      wx.navigateTo({
        url: `/pages/booking-confirm/index?date=${encodeURIComponent(dateText)}&time=${encodeURIComponent(timeText)}&contact=${encodeURIComponent(contactText)}`,
      });
    }, 700);
  },
});
