// 调用预约API
const { museumApi } = require('../../../utils/api.js');
Page({
  data: {
    selectedDate: '',
    title: '', // 活动标题
    activityId: 0, // 活动ID，type=2时需要
    type: 1, // 预约类型：1-普通预约，2-活动预约
    visitors: [], // 参观人列表
    showExistingPage: false,
    showSuccessModal: false,
    isFormValid: false,
    idTypes: [{value: 1, name: '身份证'}],
    existingVisitors: [], // 我的联系人列表
    appointmentServices: [], // 讲解服务列表
    selectedServiceId: 0 // 选中的讲解服务ID，默认为0（不需要讲解服务）
  },

  onLoad(options) {
    this.addNewVisitor();
    // 获取页面参数
    if (options.date) {
      this.setData({
        selectedDate: options.date
      });
    }
    
    // 获取活动标题
    if (options.title) {
      this.setData({
        title: decodeURIComponent(options.title)
      });
    }
    
    // 保存activityId和type用于后续提交
    if (options.activityId) {
      this.setData({
        activityId: parseInt(options.activityId)
      });
    }
    if (options.type) {
      this.setData({
        type: parseInt(options.type)
      });
    }
    
    // 加载已有参观人数据
    this.loadExistingVisitors();
    
    // 加载讲解服务列表
    this.loadAppointmentServices();
  },

  // 新增参观人
  addNewVisitor() {
      const visitors = this.data.visitors;
      visitors.unshift({
        id: 0, // 新增参观人ID为0
        name: '',
        phone: '',
        cardType: this.data.idTypes[0].value, // 证件类型
        idCard: '', // 证件号码
        idType: this.data.idTypes[0].name, // 用于显示
        idTypeIndex: 0,
        idCard: '', // 用于显示
        nameError: '',
        phoneError: '',
        idNumberError: '',
        isFromContacts: false // 标识是否来自联系人
      });
      this.setData({
        visitors: visitors
      });
      this.checkFormValid();
    },

    // 删除参观人
    removeVisitor(e) {
      const index = e.currentTarget.dataset.index;
      const visitors = this.data.visitors;
      visitors.splice(index, 1);
      this.setData({
        visitors: visitors
      });
      this.checkFormValid();
    },

    // 姓名输入
    onNameInput(e) {
      const index = e.currentTarget.dataset.index;
      const value = e.detail.value;
      const visitors = this.data.visitors;
      visitors[index].name = value;
      this.setData({
        visitors: visitors
      });
    },

    // 电话输入
    onPhoneInput(e) {
      const index = e.currentTarget.dataset.index;
      const value = e.detail.value;
      const visitors = this.data.visitors;
      visitors[index].phone = value;
      this.setData({
        visitors: visitors
      });
    },

    // 证件号码输入
    onIdNumberInput(e) {
      const index = e.currentTarget.dataset.index;
      const value = e.detail.value;
      const visitors = this.data.visitors;
      visitors[index].idCard = value;
      visitors[index].idCard = value; // 同步更新API字段
      this.setData({
        visitors: visitors
      });
    },

    // 证件类型选择
    onIdTypeChange(e) {
      const index = e.currentTarget.dataset.index;
      const value = e.detail.value;
      const visitors = this.data.visitors;
      const selectedIdType = this.data.idTypes[value];
      visitors[index].idTypeIndex = value;
      visitors[index].idType = selectedIdType.name;
      visitors[index].cardType = selectedIdType.value; // 同步更新API字段
      this.setData({
        visitors: visitors
      });
    },

    // 验证姓名
    validateName(e) {
      const index = e.currentTarget.dataset.index;
      const visitors = this.data.visitors;
      const visitor = visitors[index];
      
      if (!visitor.name.trim()) {
        visitor.nameError = '请输入姓名';
      } else if (visitor.name.length < 2) {
        visitor.nameError = '姓名至少2个字符';
      } else {
        visitor.nameError = '';
      }
      
      this.setData({
        visitors: visitors
      });
      this.checkFormValid();
    },

    // 验证电话
    validatePhone(e) {
      const index = e.currentTarget.dataset.index;
      const visitors = this.data.visitors;
      const visitor = visitors[index];
      const phoneRegex = /^1[3-9]\d{9}$/;
      
      if (!visitor.phone) {
        visitor.phoneError = '请输入电话号码';
      } else if (!phoneRegex.test(visitor.phone)) {
        visitor.phoneError = '请输入正确的11位手机号码';
      } else {
        visitor.phoneError = '';
      }
      
      this.setData({
        visitors: visitors
      });
      this.checkFormValid();
    },

    // 验证证件号码
    validateIdNumber(e) {
      const index = e.currentTarget.dataset.index;
      const visitors = this.data.visitors;
      const visitor = visitors[index];
      const idRegex = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
      
      if (!visitor.idCard) {
        visitor.idNumberError = '请输入证件号码';
      } else if (!idRegex.test(visitor.idCard)) {
        visitor.idNumberError = '请输入正确的18位身份证号码';
      } else {
        visitor.idNumberError = '';
      }
      
      this.setData({
        visitors: visitors
      });
      this.checkFormValid();
    },

    // 检查表单是否有效
    checkFormValid() {
      const visitors = this.data.visitors;
      if (visitors.length === 0) {
        this.setData({ isFormValid: false });
        return;
      }
      
      const isValid = visitors.every(visitor => 
        visitor.name && 
        visitor.phone && 
        visitor.idCard && 
        !visitor.nameError && 
        !visitor.phoneError && 
        !visitor.idNumberError
      );
      
      this.setData({ isFormValid: isValid });
    },

    // 加载已有参观人数据
    loadExistingVisitors() {
      museumApi.getMyVisitors()
        .then(response => {
          console.log('获取参观人列表成功:', response);
          if (response && response.length > 0) {
            const existingVisitors = response.map(visitor => ({
              id: visitor.id,
              name: visitor.name,
              idCard: visitor.idCard,
              phone: visitor.phone,
              selected: false
            }));
            this.setData({ existingVisitors });
          }
        })
        .catch(error => {
          console.error('获取参观人列表失败:', error);
          // 如果接口失败，可以使用模拟数据
          this.setData({
            existingVisitors: [
              {
                name: '周明明',
                idCard: '210112196705041430',
                phone: '18416573665',
                selected: false
              },
              {
                name: '李明',
                idCard: '621124199504251508',
                phone: '13902376115',
                selected: false
              }
            ]
          });
        });
    },

    // 显示已有参观人
    showExistingVisitors() {
      // 每次显示前重新加载数据
      this.loadExistingVisitors();
      this.setData({
        showExistingPage: true
      });
    },

    // 切换已有参观人选择状态
    toggleExistingVisitor(e) {
      const index = e.currentTarget.dataset.index;
      const existingVisitors = this.data.existingVisitors;
      existingVisitors[index].selected = !existingVisitors[index].selected;
      this.setData({
        existingVisitors: existingVisitors
        });
    },

    // 加载讲解服务列表
    loadAppointmentServices() {
      museumApi.getAppointmentServiceList()
        .then(response => {
          console.log('获取讲解服务列表成功:', response);
          if (response && response.length > 0) {
            // 确保第一个是"不需要讲解服务"
            const services = response;
            // 默认选中第一个服务（通常是"不需要讲解服务"）
            this.setData({ 
              appointmentServices: services,
              selectedServiceId: services[0].id
            });
          }
        })
        .catch(error => {
          console.error('获取讲解服务列表失败:', error);
          // 如果接口失败，使用默认数据
          const defaultServices = [
            { id: 0, name: '不需要讲解服务', price: 0 },
            { id: 1, name: '展厅基本列', price: 120 },
            { id: 2, name: '展厅基本列、黑油山地貌、外景文物', price: 150 },
            { id: 3, name: '展厅基本列、黑油山地貌、外景文物、临展厅', price: 180 }
          ];
          this.setData({ 
            appointmentServices: defaultServices,
            selectedServiceId: defaultServices[0].id
          });
        });
    },

    // 选择讲解服务
    selectAppointmentService(e) {
      const serviceId = e.currentTarget.dataset.serviceId;
      this.setData({
        selectedServiceId: parseInt(serviceId)
      });
    },

    // 确认选择已有参观人
    confirmExistingVisitors() {
      const selectedVisitors = this.data.existingVisitors.filter(visitor => visitor.selected);
      const visitors = this.data.visitors;
      
      selectedVisitors.forEach(existingVisitor => {
        // if (visitors.length < 5) {
          visitors.unshift({
            id: existingVisitor.id, // 使用联系人的真实ID
            name: existingVisitor.name,
            phone: existingVisitor.phone,
            cardType: this.data.idTypes[0].value, // 证件类型
            idCard: existingVisitor.idCard, // 证件号码
            idType: this.data.idTypes[0].name, // 用于显示
            idTypeIndex: 0,
            idCard: existingVisitor.idCard, // 用于显示
            nameError: '',
            phoneError: '',
            idNumberError: '',
            isFromContacts: true // 标识来自联系人
          });
        // }
      });
      
      // 重置选择状态
      const existingVisitors = this.data.existingVisitors;
      existingVisitors.forEach(visitor => {
        visitor.selected = false;
      });
      
      this.setData({
        visitors: visitors,
        existingVisitors: existingVisitors,
        showExistingPage: false
      });
      
      this.checkFormValid();
    },

    // 提交预约
    submitReservation() {
      if (!this.data.isFormValid) {
        wx.showToast({
          title: '请完善所有参观人信息',
          icon: 'none'
        });
        return;
      }
      
      wx.showLoading({
        title: '提交中...',
        mask: true
      });
      
      // 构建API参数
      const requestData = {
        activityId: this.data.activityId || 0,
        appointmentSlotsId: this.data.appointmentSlotsId || 0,
        appointmentTime: this.data.selectedDate,
        appointmentServiceId: this.data.selectedServiceId, // 添加讲解服务ID
        type: this.data.type,
        visitors: this.data.visitors.map(visitor => ({
          cardType: this.data.idTypes[visitor.idTypeIndex].value,
          id: visitor.id, // 新增参观人为0，联系人为真实ID
          idCard: visitor.idCard,
          name: visitor.name,
          phone: visitor.phone
        }))
      };
      
      console.log('提交预约参数:', requestData);
      museumApi.submitReservation(requestData)
        .then(response => {
          console.log('预约提交成功:', response);
          
          this.setData({
            showSuccessModal: true
          });
          wx.hideLoading();
        })
        .catch(error => {
          wx.hideLoading();
          console.error('预约提交失败:', error);
          wx.showToast({
            title: error.message || '预约失败，请重试',
            icon: 'none'
          });
        });
    },

    // 关闭成功弹窗
    closeSuccessModal() {
      this.setData({
        showSuccessModal: false
      });
      // 跳转到我的预约页面
      wx.reLaunch({
        url: '/pages/user/my-preview/index'
      })
    },

  // 阻止事件冒泡
  stopPropagation() {
    // 空函数，用于阻止事件冒泡
  }
});