<template>
  <div class="community-request-container" @touchstart="handleTouchStart">
    <div class="request-card">
      <form @submit.prevent="submitRequest" class="request-form">
        <div class="form-group">
          <label for="communityName">小区名称</label>
          <input 
            type="text" 
            id="communityName" 
            v-model="formData.communityName" 
            placeholder="请输入小区名称" 
            required
          />
        </div>
        
        <div class="form-group">
          <label for="address">详细地址</label>
          <textarea 
            id="address" 
            v-model="formData.address" 
            placeholder="请输入详细地址信息，包括省市区、街道名称、门牌号等" 
            required
          ></textarea>
        </div>
        
        <div class="form-actions">
          <button type="button" class="btn-cancel" @click="goBack">取消</button>
          <button type="submit" class="btn-submit" :disabled="isSubmitting">
            {{ isSubmitting ? '提交中...' : '提交申请' }}
          </button>
        </div>
      </form>
    </div>
    
    <!-- 将成功弹窗改为通用模态弹窗 -->
    <div class="modal" v-if="showModal">
      <div class="modal-content">
        <div class="modal-icon" :class="{ 'success-icon': isSuccess, 'error-icon': !isSuccess }">
          <span v-if="isSuccess">✓</span>
          <span v-else>!</span>
        </div>
        <h3>{{ modalTitle }}</h3>
        <p>{{ modalMessage }}</p>
        <button @click="closeModal" class="btn-confirm">确定</button>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted, onBeforeUnmount } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import apiClient from '../services/api'

export default {
  name: 'CommunityRequest',
  setup() {
    const router = useRouter()
    const route = useRoute()
    const isSubmitting = ref(false)
    // 替换 showSuccessModal 为更通用的 showModal
    const showModal = ref(false)
    // 添加状态标志和消息内容
    const isSuccess = ref(true)
    const modalTitle = ref('')
    const modalMessage = ref('')
    const userId = ref('')
    const lastTouchEnd = ref(0)
    
    const formData = reactive({
      communityName: '',
      address: ''
    })
    
    onMounted(() => {
      // 从URL获取userId
      userId.value = route.query.userid || ''
      
      if (!userId.value) {
        console.warn('未找到用户ID，可能影响提交功能')
      }
      
      // 检测是否在小程序环境中
      checkMiniProgramEnvironment()
      
      // 设置页面标题
      document.title = '小区开通申请'
      
      // 添加额外的触摸事件处理
      const handleTouchEnd = (event) => {
        const now = Date.now()
        if (now - lastTouchEnd.value <= 300) {
          event.preventDefault()
        }
        lastTouchEnd.value = now
      }
      
      const handleTouchMove = (event) => {
        if (event.touches.length > 1) {
          event.preventDefault()
        }
      }
      
      document.addEventListener('touchend', handleTouchEnd, { passive: false })
      document.addEventListener('touchmove', handleTouchMove, { passive: false })
      
      // 保存引用以便在组件卸载时移除
      window._communityRequestTouchHandlers = {
        handleTouchEnd,
        handleTouchMove
      }
    })
    
    onBeforeUnmount(() => {
      // 移除事件监听器
      if (window._communityRequestTouchHandlers) {
        document.removeEventListener('touchend', window._communityRequestTouchHandlers.handleTouchEnd)
        document.removeEventListener('touchmove', window._communityRequestTouchHandlers.handleTouchMove)
        delete window._communityRequestTouchHandlers
      }
    })
    
    const handleTouchStart = (event) => {
      // 防止双击缩放
      if (event.touches.length > 1) {
        event.preventDefault()
      }
    }
    
    const checkMiniProgramEnvironment = () => {
      // 检测是否在微信小程序环境中
      const ua = navigator.userAgent.toLowerCase()
      const isMiniProgram = ua.indexOf('miniprogram') > -1 || window.__wxjs_environment === 'miniprogram'
      
      console.log('Is Mini Program:', isMiniProgram)
    }
    
    const submitRequest = async () => {
      if (isSubmitting.value) return
      
      isSubmitting.value = true
      
      try {
        // 构建请求数据 - 使用正确的参数格式
        const requestData = {
          user_id: userId.value || 0,
          community_name: formData.communityName,
          community_address: formData.address
        }
        
        // 发送请求
        const response = await apiClient.post('/api/feedback/community-apply', requestData)
        
        // 检查返回的状态码
        if (response.data && response.data.code === 200) {
          console.log('申请提交成功:', response.data)
          
          // 显示成功弹窗
          isSuccess.value = true
          modalTitle.value = '申请提交成功'
          modalMessage.value = '我们将尽快审核您的小区开通申请'
          showModal.value = true
          
          // 重置表单
          formData.communityName = ''
          formData.address = ''
        } else {
          // 显示错误弹窗
          const errorMessage = response.data?.message || '提交失败，请稍后重试'
          console.error('提交申请失败:', errorMessage)
          
          isSuccess.value = false
          modalTitle.value = '提交失败'
          modalMessage.value = errorMessage
          showModal.value = true
        }
      } catch (error) {
        console.error('提交申请失败:', error)
        
        // 尝试从错误响应中获取详细信息
        const errorMessage = error.response?.data?.message || '提交失败，请稍后重试'
        
        isSuccess.value = false
        modalTitle.value = '提交失败'
        modalMessage.value = errorMessage
        showModal.value = true
      } finally {
        isSubmitting.value = false
      }
    }
    
    // 替换 closeSuccessModal 为更通用的 closeModal
    const closeModal = () => {
      showModal.value = false
      
      // 如果是成功状态，关闭弹窗后返回上一页
      if (isSuccess.value) {
        goBack()
      }
    }
    
    const goBack = () => {
      // 如果在小程序环境中，调用小程序的返回方法
      if (window.wx && window.wx.miniProgram) {
        window.wx.miniProgram.navigateBack({ delta: 1 })
      } else {
        // 否则使用路由返回
        router.back()
      }
    }
    
    return {
      formData,
      isSubmitting,
      showModal,
      isSuccess,
      modalTitle,
      modalMessage,
      submitRequest,
      closeModal,
      goBack,
      handleTouchStart
    }
  }
}
</script>

<style scoped>
.community-request-container {
  /* 添加触摸相关样式 */
  -webkit-touch-callout: none;
  -webkit-user-select: none;
  -khtml-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  touch-action: manipulation;
  
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px 15px;
  background: linear-gradient(to bottom, #FFCC00, #FFFFFF);
}

.request-card {
  width: 100%;
  max-width: 98%;
  background-color: #FFFFFF;
  border-radius: 20px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  padding: 25px 20px;
}

.page-title {
  font-size: 22px;
  font-weight: bold;
  color: #333333;
  text-align: center;
  margin-bottom: 25px;
}

.request-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-group label {
  font-size: 16px;
  font-weight: 500;
  color: #333333;
}

.form-group input,
.form-group textarea {
  padding: 12px 15px;
  border: 1px solid #DDDDDD;
  border-radius: 8px;
  font-size: 16px;
  color: #333333;
  background-color: #F9F9F9;
  transition: border-color 0.3s, box-shadow 0.3s;
}

.form-group input:focus,
.form-group textarea:focus {
  border-color: #FFCC00;
  box-shadow: 0 0 0 2px rgba(255, 204, 0, 0.2);
  outline: none;
}

.form-group textarea {
  min-height: 120px;
  resize: vertical;
}

.form-actions {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
}

.btn-cancel,
.btn-submit,
.btn-confirm {
  padding: 12px 25px;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
}

.btn-cancel {
  background-color: #F5F5F5;
  color: #666666;
  border: 1px solid #DDDDDD;
}

.btn-submit {
  background-color: #FFCC00;
  color: #333333;
  border: none;
}

.btn-submit:disabled {
  background-color: #FFE580;
  cursor: not-allowed;
}

.btn-cancel:hover {
  background-color: #EEEEEE;
}

.btn-submit:hover:not(:disabled) {
  background-color: #FFD633;
}

/* 添加模态弹窗样式 */
.modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: #FFFFFF;
  border-radius: 15px;
  padding: 30px;
  width: 80%;
  max-width: 350px;
  text-align: center;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.modal-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 30px;
  color: white;
  margin-bottom: 20px;
}

.success-icon {
  background-color: #FFCC00;
}

.error-icon {
  background-color: #FF6B6B;
}

.modal-content h3 {
  font-size: 20px;
  margin-bottom: 10px;
  color: #333333;
}

.modal-content p {
  color: #666666;
  margin-bottom: 25px;
}

.btn-confirm {
  background-color: #FFCC00;
  color: #333333;
  border: none;
  border-radius: 8px;
  padding: 12px 15px;
  width: 100%;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.3s;
}

.btn-confirm:hover {
  background-color: #FFD633;
}

/* 响应式调整 */
@media (max-width: 480px) {
  .request-card {
    padding: 20px 15px;
  }
  
  .page-title {
    font-size: 20px;
    margin-bottom: 20px;
  }
  
  .form-group label {
    font-size: 15px;
  }
  
  .form-group input,
  .form-group textarea,
  .btn-cancel,
  .btn-submit {
    padding: 10px 12px;
    font-size: 15px;
  }
}
</style> 