const app = getApp();
Page({
  data: {
    address: app.globalData.currentAccountInfo.address,
    contact: '',
    phone: '',
    repairType: '',
    repairTypeValue: '',
    repairTypeMap: [
      {name: '换表', value: '1'},
      {name: '换前阀', value: '2'},
      {name: '换后阀', value: '3'},
      {name: '换前后阀', value: '4'},
      {name: '其他', value: '5'}
    ],
    description: '',
    imageList: [],
    showNotification: true,
    countDown: 3,
    isFormValid: false,
    isPreviewMode: false,
    replyTime: '',
    replyContent: '',
    id: '',
    mode: '',
    isReplied: false,
    formSubmitted: false,
    isSubmitting: false, // 新增保存标志位
    lastSubmitTime: 0, // 上次提交时间（通过防抖（Debounce）技术，限制用户在一定时间内只能提交一次。）
  },

  onLoad: function (options) {
    const isReplied = options.isReplied === 'true';

    if (options.mode === 'preview') {
      this.setData({
        isPreviewMode: true,
        showNotification: false,
        id: options.id,
        mode: options.mode,
        isReplied: isReplied
      });
      this.loadPreviewData(options.id);
    } else {
      this.startCountDown();
      this.setData({
        id: options.id || '',
        mode: options.mode || '',
        isReplied: isReplied
      });
    }
  },

  startCountDown: function () {
    let that = this;
    let timer = setInterval(function () {
      if (that.data.countDown > 0) {
        that.setData({
          countDown: that.data.countDown - 1
        });
      } else {
        clearInterval(timer);
      }
    }, 1000);
  },

  closeNotification: function () {
    if (this.data.countDown <= 0) {
      this.setData({
        showNotification: false
      });
    }
  },

  goBack: function () {
    wx.navigateBack();
  },

  inputContact: function (e) {
    this.setData({
      contact: e.detail.value
    });
    this.checkFormValidity();
  },

  inputPhone: function (e) {
    const value = e.detail.value;
    const phoneNumber = value.replace(/\D/g, '');
    this.setData({
      phone: phoneNumber
    });
    this.checkFormValidity();
  },

  validatePhone: function (phone) {
    const phoneReg = /^1[3-9]\d{9}$/;
    return phoneReg.test(phone);
  },

  showRepairTypeSelector: function () {
    let that = this;
    // 只显示名称列表
    const typeNames = this.data.repairTypeMap.map(item => item.name);
    
    wx.showActionSheet({
      itemList: typeNames,
      success: function (res) {
        const selectedType = that.data.repairTypeMap[res.tapIndex];
        that.setData({
          repairType: selectedType.name,
          repairTypeValue: selectedType.value
        });
        that.checkFormValidity();
      }
    });
  },

  inputDescription: function (e) {
    this.setData({
      description: e.detail.value
    });
    this.checkFormValidity();
  },

  chooseImage: function () {
    let that = this;
    if (that.data.imageList.length >= 10) {
      wx.showToast({
        title: '最多只能上传10张图片',
        icon: 'none'
      });
      return;
    }

    wx.chooseMedia({
      count: 10 - that.data.imageList.length,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      sizeType: ['compressed'],
      success: function (res) {
        let tempFiles = res.tempFiles;
        let validFiles = [];
        for (let i = 0; i < tempFiles.length; i++) {
          const file = tempFiles[i];
          if (file.size <= 10 * 1024 * 1024) {
            validFiles.push(file);
          } else {
            wx.showToast({
              title: '图片大小不能超过10M',
              icon: 'none'
            });
          }
        }

        if (validFiles.length > 0) {
          let newImageList = that.data.imageList.concat(validFiles);
          that.setData({
            imageList: newImageList
          });
        }
      }
    });
  },

  previewImage: function (e) {
    let index = e.currentTarget.dataset.index;
    wx.previewImage({
      current: this.data.imageList[index],
      urls: this.data.imageList
    });
  },

  deleteImage: function (e) {
    let index = e.currentTarget.dataset.index;
    let imageList = this.data.imageList;
    imageList.splice(index, 1);
    this.setData({
      imageList: imageList
    });
  },

  checkFormValidity: function () {
    const {
      contact,
      phone,
      address,
      repairType,
      repairTypeValue,
      description
    } = this.data;

    const hasAddress = address && address.trim() !== '';
    const hasContact = contact && contact.trim() !== '';
    const hasPhone = phone && phone.trim() !== '';
    const hasValidPhone = this.validatePhone(phone);
    const hasRepairType = repairType && repairType.trim() !== '';
    const hasRepairTypeValue = repairTypeValue && repairTypeValue.trim() !== '';
    const hasDescription = description && description.trim() !== '';

    const isValid = hasAddress && hasContact && hasPhone && hasValidPhone && hasRepairType && hasRepairTypeValue && hasDescription;

    this.setData({
      isFormValid: isValid
    });

    return isValid;
  },

  onInputChange: function (e) {
    const {
      field
    } = e.currentTarget.dataset;
    const {
      value
    } = e.detail;

    this.setData({
      [field]: value
    });

    this.checkFormValidity();
  },

  bindPickerChange: function (e) {
    this.checkFormValidity();
  },

  submitRepair: function () {
    if (!this.checkFormValidity()) {
      wx.showToast({
        title: '请填写完整信息',
        icon: 'none'
      });
      return;
    }

    if (!this.validatePhone(this.data.phone)) {
      wx.showToast({
        title: '请输入正确的手机号',
        icon: 'none'
      });
      return;
    }

    const submitData = {
      address: this.data.address,
      contact: this.data.contact,
      phone: this.data.phone,
      repairType: this.data.repairType,
      repairTypeValue: this.data.repairTypeValue,
      description: this.data.description,
      images: this.data.imageList
    };

    console.log('提交的数据:', submitData);

    wx.showLoading({
      title: '提交中...',
    });

    setTimeout(() => {
      wx.hideLoading();
      wx.showToast({
        icon: 'success',
        duration: 2000,
        success: function () {
          setTimeout(() => {
            wx.navigateTo({
              url: '/pages/baoxiuSuccess/baoxiuSuccess',
            });
          }, 2000);
        }
      });
    }, 1500);
  },

  loadPreviewData: function (id) {
    wx.showLoading({
      title: '加载中...',
    });

    // 从上一个页面获取数据
    const pages = getCurrentPages();
    const prevPage = pages[pages.length - 2]; // 获取上一个页面

    if (prevPage && prevPage.data && prevPage.data.noticeList) {
      // 根据id查找对应的报修项
      const item = prevPage.data.noticeList.find(item => item.id == id);
      debugger
      if (item) {
        // 找到对应的报修类型名称
        let repairTypeName = '';
        const repairTypeValue = item.repairtype || '';
        const repairTypeItem = this.data.repairTypeMap.find(type => type.name === repairTypeValue);
        if (repairTypeItem) {
          repairTypeName = repairTypeItem.name;
        }

        // 格式化时间
        const formatTime = (timeString) => {
          if (!timeString) return ''; // 如果时间为空，返回空字符串
          const date = new Date(timeString);
          const year = date.getFullYear();
          const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份补零
          const day = String(date.getDate()).padStart(2, '0'); // 日期补零
          return `${year}-${month}-${day}`;
        };

        this.setData({
          address: item.address || '',
          contact: item.contact || '',
          phone: item.contactnumber || '',
          repairType: repairTypeName,
          repairTypeValue: repairTypeValue,
          description: item.faultdescription || '',
          imageList: item.attachments || [],
          replyTime: item.isReplied ? formatTime(item.repairtime) : '',
          replyContent: item.isReplied ? item.remark : ''
        });
      }
    }

    wx.hideLoading();
  },

  submitForm: function () {
    // 如果正在提交中，直接返回
    if (this.data.isSubmitting) {
      return;
    }

    if (!this.data.address || this.data.address.trim() === '') {
      wx.showToast({
        title: '请填写地址',
        icon: 'none'
      });
      this.setData({
        isSubmitting: false
      });
      return;
    }

    if (!this.data.contact || this.data.contact.trim() === '') {
      wx.showToast({
        title: '请填写联系人',
        icon: 'none'
      });
      this.setData({
        isSubmitting: false
      });
      return;
    }

    if (!this.data.phone || this.data.phone.trim() === '') {
      wx.showToast({
        title: '请填写联系电话',
        icon: 'none'
      });
      this.setData({
        isSubmitting: false
      });
      return;
    }

    if (!this.validatePhone(this.data.phone)) {
      wx.showToast({
        title: '请输入正确的手机号',
        icon: 'none'
      });
      this.setData({
        isSubmitting: false
      });
      return;
    }

    if (!this.data.repairType || this.data.repairType.trim() === '') {
      wx.showToast({
        title: '请选择报修类型',
        icon: 'none'
      });
      this.setData({
        isSubmitting: false
      });
      return;
    }

    if (!this.data.repairTypeValue || this.data.repairTypeValue.trim() === '') {
      wx.showToast({
        title: '请选择报修类型',
        icon: 'none'
      });
      this.setData({
        isSubmitting: false
      });
      return;
    }

    if (!this.data.description || this.data.description.trim() === '') {
      wx.showToast({
        title: '请填写故障说明',
        icon: 'none'
      });
      this.setData({
        isSubmitting: false
      });
      return;
    }

    const now = Date.now();
    const lastSubmitTime = this.data.lastSubmitTime;
    // 如果距离上次提交时间小于 2 秒，直接返回
    if (now - lastSubmitTime < 2000) {
      // wx.showToast({
      //   title: '请勿重复提交',
      //   icon: 'none',
      // });
      return;
    }

    // 更新上次提交时间
    this.setData({
      lastSubmitTime: now,
    });

    const fileManager = wx.getFileSystemManager();
    this.data.imageList.map(imgInfo => {
      const base64 = fileManager.readFileSync(imgInfo.tempFilePath, 'base64');
      imgInfo.base64 = base64;
      return imgInfo;
    })

    const submitData = {
      address: this.data.address,
      contact: this.data.contact,
      phone: this.data.phone,
      repairType: this.data.repairTypeValue,
      description: this.data.description,
      images: this.data.imageList
    };
    // 设置正在提交中 防止重复点击提交按钮
    this.setData({
      isSubmitting: true,
    });
    console.log('提交的数据:', submitData);

    wx.showLoading({
      title: '提交中...',
      mask: true
    });

    const that = this;
    wx.request({
      url: app.globalData.interfaceUrls.repairRegistration,
      method: 'POST',
      header: {
        'content-type': 'application/json', // 默认值
        'token': app.globalData.userWxInfo.token,
        'source': "wc",
        '!SAAS_LOGIN_TOKEN_!': app.globalData.currentAccountInfo.dsKey
      },
      data: submitData,
      success(res) {
        wx.hideLoading();
        if (res.data.code == '200') {
          wx.navigateTo({
            url: '/pages/baoxiuSuccess/baoxiuSuccess',
          });
        }
        that.setData({
          isSubmitting: false
        });
      },
      fail(error) {
        wx.hideLoading();
        wx.showToast({
          title: '登记失败，请稍后再试',
          icon: 'none'
        });
        that.setData({
          isSubmitting: false
        });
      },
      complete: () => {
        this.setData({
          isSubmitting: false, // 提交完成，重置标志位，可继续提交
          formSubmitted: true // 在提交成功后设置标记，返回将重置表单
        });
      },
    })
  },

  inputAddress: function (e) {
    this.setData({
      address: e.detail.value
    });
  },

  onShow: function () {
    // 检查是否是从成功页面返回
    if (this.data.formSubmitted) {
      // 重置表单数据
      this.resetForm();
      // 重置提交状态标记
      this.setData({
        formSubmitted: false
      });
    }
  },

  // 添加重置表单的方法
  resetForm: function () {
    this.setData({
      contact: '',
      phone: '',
      repairType: '',
      repairTypeValue: '',
      description: '',
      imageList: []
    });
  },
});