<template>
  <view class="container">
    <!-- 产品信息卡片 -->
    <view v-if="product" class="product-card">
      <view class="product-header">
        <image :src="product.icon || '/static/images/default-product.png'" class="product-icon" />
        <view class="product-info">
          <text class="product-name">{{ product.name }}</text>
          <text class="product-desc">{{ product.description }}</text>
          <view class="product-price">
            <text class="price-range">保费：¥{{ product.min_premium }} - ¥{{ product.max_premium }}/年</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 投保表单 -->
    <view class="form-section">
      <view class="section-title">
        <text>投保信息</text>
        <text class="required-tip">* 为必填项</text>
      </view>

      <!-- 投保人信息 -->
      <view class="form-group">
        <text class="form-label">投保人姓名 *</text>
        <input 
          v-model="formData.customer_name"
          class="form-input" 
          placeholder="请输入真实姓名"
          @input="onInputChange('customer_name', $event)"
        />
      </view>

      <view class="form-group">
        <text class="form-label">身份证号 *</text>
        <input 
          v-model="formData.customer_id_card"
          class="form-input" 
          placeholder="请输入18位身份证号码"
          maxlength="18"
          @input="onInputChange('customer_id_card', $event)"
        />
      </view>

      <view class="form-group">
        <text class="form-label">手机号码 *</text>
        <input 
          v-model="formData.customer_phone"
          class="form-input" 
          placeholder="请输入11位手机号码"
          type="number"
          maxlength="11"
          @input="onInputChange('customer_phone', $event)"
        />
      </view>

      <view class="form-group">
        <text class="form-label">联系地址 *</text>
        <textarea 
          v-model="formData.customer_address"
          class="form-textarea" 
          placeholder="请输入详细联系地址"
          maxlength="200"
          @input="onInputChange('customer_address', $event)"
        />
      </view>

      <!-- 保险信息 -->
      <view class="form-group">
        <text class="form-label">保险金额 *</text>
        <view class="amount-input-wrapper">
          <input 
            v-model="formData.application_amount"
            class="form-input amount-input" 
            placeholder="请输入保险金额"
            type="digit"
            @input="onInputChange('application_amount', $event)"
          />
          <text class="amount-unit">万元</text>
        </view>
        <view class="amount-tips">
          <text>建议保额：{{ product?.min_amount }}万 - {{ product?.max_amount }}万</text>
        </view>
      </view>

      <!-- 受益人信息 -->
      <view class="beneficiary-section">
        <text class="section-subtitle">受益人信息（可选）</text>
        
        <view class="form-group">
          <text class="form-label">受益人姓名</text>
          <input 
            v-model="formData.beneficiary_name"
            class="form-input" 
            placeholder="请输入受益人姓名"
            @input="onInputChange('beneficiary_name', $event)"
          />
        </view>

        <view class="form-group">
          <text class="form-label">与投保人关系</text>
          <picker 
            :value="relationIndex" 
            :range="relationOptions"
            @change="onRelationChange"
          >
            <view class="picker-input">
              {{ formData.beneficiary_relation || '请选择与受益人关系' }}
              <text class="picker-arrow">></text>
            </view>
          </picker>
        </view>
      </view>

      <!-- 附加信息 -->
      <view class="form-group">
        <text class="form-label">备注信息</text>
        <textarea 
          v-model="formData.remarks"
          class="form-textarea" 
          placeholder="请输入其他需要说明的信息（可选）"
          maxlength="500"
          @input="onInputChange('remarks', $event)"
        />
      </view>
    </view>

    <!-- 保费预览 -->
    <view class="premium-preview" v-if="estimatedPremium">
      <view class="preview-header">
        <text>保费预览</text>
      </view>
      <view class="preview-content">
        <view class="preview-item">
          <text class="preview-label">保险金额</text>
          <text class="preview-value">{{ formData.application_amount }}万元</text>
        </view>
        <view class="preview-item">
          <text class="preview-label">预估年保费</text>
          <text class="preview-value primary">¥{{ estimatedPremium }}</text>
        </view>
      </view>
    </view>

    <!-- 条款确认 -->
    <view class="agreement-section">
      <view class="agreement-item" @tap="toggleAgreement">
        <image 
          :src="agreedToTerms ? '/static/images/checkbox-checked.png' : '/static/images/checkbox-unchecked.png'" 
          class="checkbox" 
        />
        <text class="agreement-text">
          我已阅读并同意
          <text class="agreement-link" @tap.stop="showTerms">《保险条款》</text>
          和
          <text class="agreement-link" @tap.stop="showPrivacy">《隐私政策》</text>
        </text>
      </view>
    </view>

    <!-- 提交按钮 -->
    <view class="submit-section">
      <button 
        class="submit-btn"
        :class="{ disabled: !canSubmit }"
        :disabled="!canSubmit || submitting"
        @tap="submitApplication"
      >
        {{ submitting ? '提交中...' : '提交申请' }}
      </button>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useInsuranceStore } from '@/store/insurance'
import { useUserStore } from '@/store/user'
import { auth } from '@/utils/auth'
import { BENEFICIARY_RELATIONS } from '@/utils/constants'

// 状态管理
const insuranceStore = useInsuranceStore()
const userStore = useUserStore()

// 获取路由参数
const pages = getCurrentPages()
const currentPage = pages[pages.length - 1]
const productId = ref(currentPage.options.productId)

// 响应式数据
const product = ref(null)
const submitting = ref(false)
const agreedToTerms = ref(false)
const relationIndex = ref(-1)

// 关系选项
const relationOptions = ref(BENEFICIARY_RELATIONS)

// 表单数据（使用reactive实现响应式）
const formData = reactive({
  customer_name: '',
  customer_id_card: '',
  customer_phone: '',
  customer_address: '',
  application_amount: '',
  beneficiary_name: '',
  beneficiary_relation: '',
  remarks: ''
})

// 计算属性
const canSubmit = computed(() => {
  return formData.customer_name && 
         formData.customer_id_card && 
         formData.customer_phone && 
         formData.customer_address && 
         formData.application_amount && 
         agreedToTerms.value &&
         !submitting.value
})

// 预估保费计算
const estimatedPremium = computed(() => {
  if (!formData.application_amount || !product.value) return 0
  
  const amount = parseFloat(formData.application_amount)
  const rate = product.value.premium_rate || 0.005 // 默认费率0.5%
  
  return Math.round(amount * 10000 * rate)
})

// 加载产品信息（动态调用保险端后端）
const loadProductInfo = async () => {
  try {
    if (!productId.value) {
      uni.showToast({
        title: '产品信息缺失',
        icon: 'none'
      })
      return
    }

    // 动态调用 /api/insurance-types/:id
    const productData = await insuranceStore.fetchProductDetail(productId.value)
    product.value = productData
    
    console.log('产品信息加载成功:', productData)
  } catch (error) {
    console.error('加载产品信息失败:', error)
    uni.showToast({
      title: '加载产品信息失败',
      icon: 'none'
    })
  }
}

// 表单输入处理（手动更新避免v-model问题）
const onInputChange = (field, event) => {
  const value = event.detail ? event.detail.value : event.target.value
  formData[field] = value
  
  // 特殊处理身份证号格式
  if (field === 'customer_id_card') {
    formData[field] = value.toUpperCase()
  }
}

// 关系选择处理
const onRelationChange = (event) => {
  const index = event.detail.value
  relationIndex.value = index
  formData.beneficiary_relation = relationOptions.value[index]
}

// 切换条款同意状态
const toggleAgreement = () => {
  agreedToTerms.value = !agreedToTerms.value
}

// 显示保险条款
const showTerms = () => {
  uni.navigateTo({
    url: '/pages/terms/terms?type=insurance'
  })
}

// 显示隐私政策
const showPrivacy = () => {
  uni.navigateTo({
    url: '/pages/terms/terms?type=privacy'
  })
}

// 表单验证
const validateForm = () => {
  if (!formData.customer_name.trim()) {
    uni.showToast({ title: '请输入姓名', icon: 'none' })
    return false
  }

  // 身份证号验证
  const idCardRegex = /^[1-9]\d{5}(19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[0-9Xx]$/
  if (!idCardRegex.test(formData.customer_id_card)) {
    uni.showToast({ title: '请输入正确的身份证号', icon: 'none' })
    return false
  }

  // 手机号验证
  const phoneRegex = /^1[3-9]\d{9}$/
  if (!phoneRegex.test(formData.customer_phone)) {
    uni.showToast({ title: '请输入正确的手机号', icon: 'none' })
    return false
  }

  if (!formData.customer_address.trim()) {
    uni.showToast({ title: '请输入联系地址', icon: 'none' })
    return false
  }

  const amount = parseFloat(formData.application_amount)
  if (!amount || amount <= 0) {
    uni.showToast({ title: '请输入正确的保险金额', icon: 'none' })
    return false
  }

  // 检查保额范围
  if (product.value) {
    if (amount < product.value.min_amount || amount > product.value.max_amount) {
      uni.showToast({ 
        title: `保险金额应在${product.value.min_amount}-${product.value.max_amount}万元之间`, 
        icon: 'none' 
      })
      return false
    }
  }

  if (!agreedToTerms.value) {
    uni.showToast({ title: '请先同意保险条款', icon: 'none' })
    return false
  }

  return true
}

// 提交申请（动态调用保险端后端）
const submitApplication = async () => {
  // 检查登录状态
  if (!auth.requireAuth()) {
    return
  }

  if (!validateForm()) return
  if (submitting.value) return

  submitting.value = true

  try {
    const applicationData = {
      ...formData,
      insurance_type_id: productId.value,
      application_amount: parseFloat(formData.application_amount) * 10000 // 转换为元
    }

    console.log('提交申请数据:', applicationData)

    // 动态调用保险端 /api/insurance/applications 接口
    const result = await insuranceStore.submitApplication(applicationData)

    uni.showToast({
      title: '申请提交成功',
      icon: 'success'
    })

    // 跳转到申请结果页面
    setTimeout(() => {
      uni.redirectTo({
        url: `/pages/application-result/application-result?id=${result.id}`
      })
    }, 1500)

  } catch (error) {
    console.error('提交申请失败:', error)
    
    let errorMessage = '提交失败，请重试'
    if (error.message) {
      errorMessage = error.message
    }
    
    uni.showToast({
      title: errorMessage,
      icon: 'none'
    })
  } finally {
    submitting.value = false
  }
}

// 生命周期
onMounted(() => {
  loadProductInfo()
})
</script>

<style scoped>
.container {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 120rpx;
}

.product-card {
  background: #fff;
  margin: 20rpx;
  border-radius: 12rpx;
  padding: 30rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
}

.product-header {
  display: flex;
}

.product-icon {
  width: 100rpx;
  height: 100rpx;
  border-radius: 8rpx;
  margin-right: 30rpx;
}

.product-info {
  flex: 1;
}

.product-name {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 10rpx;
}

.product-desc {
  font-size: 26rpx;
  color: #666;
  line-height: 1.4;
  margin-bottom: 15rpx;
}

.product-price {
  font-size: 28rpx;
  color: #1890ff;
  font-weight: 500;
}

.form-section {
  background: #fff;
  margin: 20rpx;
  border-radius: 12rpx;
  padding: 30rpx;
}

.section-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 40rpx;
  padding-bottom: 20rpx;
  border-bottom: 1px solid #f0f0f0;
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.required-tip {
  font-size: 24rpx;
  color: #999;
  font-weight: normal;
}

.section-subtitle {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 30rpx;
  padding-top: 20rpx;
}

.form-group {
  margin-bottom: 40rpx;
}

.form-label {
  display: block;
  font-size: 30rpx;
  color: #333;
  margin-bottom: 20rpx;
  font-weight: 500;
}

.form-input {
  width: 100%;
  height: 88rpx;
  padding: 0 30rpx;
  border: 1px solid #d9d9d9;
  border-radius: 8rpx;
  font-size: 30rpx;
  background: #fff;
  box-sizing: border-box;
}

.form-input:focus {
  border-color: #1890ff;
}

.form-textarea {
  width: 100%;
  min-height: 120rpx;
  padding: 20rpx 30rpx;
  border: 1px solid #d9d9d9;
  border-radius: 8rpx;
  font-size: 30rpx;
  background: #fff;
  box-sizing: border-box;
  resize: none;
}

.amount-input-wrapper {
  display: flex;
  align-items: center;
}

.amount-input {
  flex: 1;
  margin-right: 20rpx;
}

.amount-unit {
  font-size: 30rpx;
  color: #666;
}

.amount-tips {
  margin-top: 15rpx;
  font-size: 24rpx;
  color: #999;
}

.beneficiary-section {
  margin-top: 40rpx;
  padding-top: 40rpx;
  border-top: 1px solid #f0f0f0;
}

.picker-input {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 88rpx;
  padding: 0 30rpx;
  border: 1px solid #d9d9d9;
  border-radius: 8rpx;
  font-size: 30rpx;
  background: #fff;
  color: #333;
}

.picker-arrow {
  color: #999;
  font-size: 24rpx;
}

.premium-preview {
  background: #fff;
  margin: 20rpx;
  border-radius: 12rpx;
  padding: 30rpx;
}

.preview-header {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 30rpx;
}

.preview-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.preview-label {
  font-size: 28rpx;
  color: #666;
}

.preview-value {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.preview-value.primary {
  color: #1890ff;
  font-size: 36rpx;
}

.agreement-section {
  padding: 30rpx;
}

.agreement-item {
  display: flex;
  align-items: flex-start;
}

.checkbox {
  width: 32rpx;
  height: 32rpx;
  margin-right: 20rpx;
  margin-top: 4rpx;
}

.agreement-text {
  flex: 1;
  font-size: 26rpx;
  color: #666;
  line-height: 1.5;
}

.agreement-link {
  color: #1890ff;
  text-decoration: underline;
}

.submit-section {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #fff;
  padding: 20rpx 30rpx;
  border-top: 1px solid #f0f0f0;
}

.submit-btn {
  width: 100%;
  height: 88rpx;
  background: #1890ff;
  color: #fff;
  border: none;
  border-radius: 44rpx;
  font-size: 32rpx;
  font-weight: bold;
}

.submit-btn.disabled {
  background: #d9d9d9;
  color: #999;
}
</style>