<template>
  <view class="loan-apply-page">
    <!-- 进度指示器 -->
    <view class="progress-section">
      <view class="progress-bar">
        <view
          class="progress-step"
          :class="{ active: currentStep >= index + 1, completed: currentStep > index + 1 }"
          v-for="(step, index) in steps"
          :key="index"
        >
          <view class="step-number">{{ index + 1 }}</view>
          <text class="step-title">{{ step.title }}</text>
        </view>
      </view>
    </view>
    
    <!-- 表单内容 -->
    <Form ref="formRef" :model="formData" :rules="formRules">
      <!-- 第一步：基本信息 -->
      <view class="step-content" v-if="currentStep === 1">
        <Card title="申请人基本信息" class="form-section">
          <FormItem label="姓名" prop="name" required>
            <input
              class="form-input"
              v-model="formData.name"
              placeholder="请输入真实姓名"
              maxlength="20"
            />
          </FormItem>
          
          <FormItem label="身份证号" prop="idCard" required>
            <input
              class="form-input"
              v-model="formData.idCard"
              placeholder="请输入身份证号码"
              maxlength="18"
            />
          </FormItem>
          
          <FormItem label="手机号码" prop="phone" required>
            <input
              class="form-input"
              v-model="formData.phone"
              placeholder="请输入手机号码"
              type="number"
              maxlength="11"
            />
          </FormItem>
          
          <FormItem label="职业" prop="occupation" required>
            <Picker
              mode="selector"
              :range="occupationOptions"
              range-key="label"
              v-model="formData.occupation"
              placeholder="请选择职业"
              @change="handleOccupationChange"
            />
          </FormItem>
          
          <FormItem label="年收入" prop="annualIncome" required>
            <view class="income-input">
              <input
                class="form-input"
                type="digit"
                v-model="formData.annualIncome"
                placeholder="请输入年收入"
              />
              <text class="income-unit">万元</text>
            </view>
          </FormItem>
          
          <FormItem label="联系地址" prop="address" required>
            <textarea
              class="form-textarea"
              v-model="formData.address"
              placeholder="请输入详细联系地址"
              maxlength="200"
            />
          </FormItem>
        </Card>
      </view>
      
      <!-- 第二步：贷款信息 -->
      <view class="step-content" v-if="currentStep === 2">
        <Card title="贷款申请信息" class="form-section">
          <FormItem label="贷款类型" prop="loanType" required>
            <Picker
              mode="selector"
              :range="loanTypeOptions"
              range-key="label"
              v-model="formData.loanType"
              placeholder="请选择贷款类型"
              @change="handleLoanTypeChange"
            />
          </FormItem>
          
          <FormItem label="贷款金额" prop="loanAmount" required>
            <view class="amount-input">
              <input
                class="form-input"
                type="digit"
                v-model="formData.loanAmount"
                placeholder="请输入贷款金额"
              />
              <text class="amount-unit">万元</text>
            </view>
          </FormItem>
          
          <FormItem label="贷款期限" prop="loanTerm" required>
            <Picker
              mode="selector"
              :range="loanTermOptions"
              range-key="label"
              v-model="formData.loanTerm"
              placeholder="请选择贷款期限"
              @change="handleLoanTermChange"
            />
          </FormItem>
          
          <FormItem label="还款方式" prop="repaymentMethod" required>
            <Picker
              mode="selector"
              :range="repaymentOptions"
              range-key="label"
              v-model="formData.repaymentMethod"
              placeholder="请选择还款方式"
              @change="handleRepaymentChange"
            />
          </FormItem>
          
          <FormItem label="贷款用途" prop="loanPurpose" required>
            <textarea
              class="form-textarea"
              v-model="formData.loanPurpose"
              placeholder="请详细说明贷款用途"
              maxlength="500"
            />
          </FormItem>
        </Card>
        
        <!-- 利率预估 -->
        <Card title="利率预估" class="rate-section" v-if="estimatedRate">
          <view class="rate-info">
            <view class="rate-item">
              <text class="rate-label">预估年利率</text>
              <text class="rate-value">{{ estimatedRate.annualRate }}%</text>
            </view>
            <view class="rate-item">
              <text class="rate-label">月还款额</text>
              <text class="rate-value">¥{{ estimatedRate.monthlyPayment }}</text>
            </view>
            <view class="rate-item">
              <text class="rate-label">总利息</text>
              <text class="rate-value">¥{{ estimatedRate.totalInterest }}</text>
            </view>
          </view>
          <view class="rate-note">
            *以上数据仅供参考，实际利率以银行审批为准
          </view>
        </Card>
      </view>
      
      <!-- 第三步：抵押物信息 -->
      <view class="step-content" v-if="currentStep === 3">
        <Card title="抵押物信息" class="form-section">
          <FormItem label="抵押物类型" prop="collateralType" required>
            <Picker
              mode="selector"
              :range="collateralTypeOptions"
              range-key="label"
              v-model="formData.collateralType"
              placeholder="请选择抵押物类型"
              @change="handleCollateralTypeChange"
            />
          </FormItem>
          
          <FormItem label="抵押物描述" prop="collateralDescription" required>
            <textarea
              class="form-textarea"
              v-model="formData.collateralDescription"
              placeholder="请详细描述抵押物情况"
              maxlength="500"
            />
          </FormItem>
          
          <FormItem label="评估价值" prop="collateralValue" required>
            <view class="value-input">
              <input
                class="form-input"
                type="digit"
                v-model="formData.collateralValue"
                placeholder="请输入评估价值"
              />
              <text class="value-unit">万元</text>
            </view>
          </FormItem>
          
          <FormItem label="抵押物照片" prop="collateralImages" required>
            <Upload
              :file-list="formData.collateralImages"
              :max-count="9"
              accept="image"
              multiple
              @change="handleCollateralImagesChange"
            >
              <view class="upload-btn">
                <text class="upload-icon">📷</text>
                <text class="upload-text">上传抵押物照片</text>
              </view>
            </Upload>
            <view class="upload-tip">
              请上传抵押物的清晰照片，包括正面、侧面等多角度
            </view>
          </FormItem>
          
          <FormItem label="产权证明" prop="ownershipCertificate" required>
            <Upload
              :file-list="formData.ownershipCertificate"
              :max-count="5"
              accept="image"
              multiple
              @change="handleOwnershipCertificateChange"
            >
              <view class="upload-btn">
                <text class="upload-icon">📄</text>
                <text class="upload-text">上传产权证明</text>
              </view>
            </Upload>
          </FormItem>
        </Card>
      </view>
      
      <!-- 第四步：资料上传 -->
      <view class="step-content" v-if="currentStep === 4">
        <Card title="申请资料上传" class="form-section">
          <FormItem label="身份证" prop="idCardImages" required>
            <Upload
              :file-list="formData.idCardImages"
              :max-count="2"
              accept="image"
              multiple
              @change="handleIdCardImagesChange"
            >
              <view class="upload-btn">
                <text class="upload-icon">🆔</text>
                <text class="upload-text">上传身份证正反面</text>
              </view>
            </Upload>
          </FormItem>
          
          <FormItem label="收入证明" prop="incomeProof" required>
            <Upload
              :file-list="formData.incomeProof"
              :max-count="5"
              accept="image"
              multiple
              @change="handleIncomeProofChange"
            >
              <view class="upload-btn">
                <text class="upload-icon">💰</text>
                <text class="upload-text">上传收入证明</text>
              </view>
            </Upload>
            <view class="upload-tip">
              可上传工资单、银行流水、营业执照等收入证明材料
            </view>
          </FormItem>
          
          <FormItem label="征信报告" prop="creditReport">
            <Upload
              :file-list="formData.creditReport"
              :max-count="3"
              accept="image"
              multiple
              @change="handleCreditReportChange"
            >
              <view class="upload-btn">
                <text class="upload-icon">📊</text>
                <text class="upload-text">上传征信报告</text>
              </view>
            </Upload>
            <view class="upload-tip">
              可选上传，有助于提高审批通过率
            </view>
          </FormItem>
          
          <FormItem label="其他材料" prop="otherDocuments">
            <Upload
              :file-list="formData.otherDocuments"
              :max-count="10"
              accept="image"
              multiple
              @change="handleOtherDocumentsChange"
            >
              <view class="upload-btn">
                <text class="upload-icon">📎</text>
                <text class="upload-text">上传其他材料</text>
              </view>
            </Upload>
          </FormItem>
        </Card>
        
        <!-- 申请确认 -->
        <Card title="申请确认" class="confirm-section">
          <view class="confirm-item">
            <checkbox
              v-model="formData.agreeTerms"
              color="#2e8b57"
            />
            <text class="confirm-text">
              我已阅读并同意
              <text class="link-text" @click="handleViewTerms">《贷款申请协议》</text>
            </text>
          </view>
          
          <view class="confirm-item">
            <checkbox
              v-model="formData.agreePrivacy"
              color="#2e8b57"
            />
            <text class="confirm-text">
              我同意银行查询我的征信信息
            </text>
          </view>
          
          <view class="confirm-item">
            <checkbox
              v-model="formData.confirmAccuracy"
              color="#2e8b57"
            />
            <text class="confirm-text">
              我确认以上信息真实准确，如有虚假承担相应法律责任
            </text>
          </view>
        </Card>
      </view>
    </Form>
    
    <!-- 底部操作栏 -->
    <view class="bottom-actions">
      <button
        class="action-btn prev-btn"
        v-if="currentStep > 1"
        @click="handlePrevStep"
      >
        上一步
      </button>
      
      <button
        class="action-btn next-btn"
        v-if="currentStep < 4"
        @click="handleNextStep"
      >
        下一步
      </button>
      
      <button
        class="action-btn submit-btn"
        v-if="currentStep === 4"
        @click="handleSubmit"
        :disabled="!canSubmit"
      >
        提交申请
      </button>
    </view>
  </view>
</template>

<script>
import { ref, reactive, computed, watch, onMounted } from 'vue'
import Form from '@/common/components/form/form.vue'
import FormItem from '@/common/components/form/form-item.vue'
import Card from '@/common/components/card/card.vue'
import Picker from '@/common/components/picker/picker.vue'
import Upload from '@/common/components/upload/upload.vue'
import { financeApi } from '@/common/api'

export default {
  name: 'LoanApplyPage',
  components: {
    Form,
    FormItem,
    Card,
    Picker,
    Upload
  },
  setup() {
    const formRef = ref(null)
    const currentStep = ref(1)
    const estimatedRate = ref(null)
    
    // 步骤配置
    const steps = [
      { title: '基本信息' },
      { title: '贷款信息' },
      { title: '抵押物' },
      { title: '资料上传' }
    ]
    
    // 表单数据
    const formData = reactive({
      // 基本信息
      name: '',
      idCard: '',
      phone: '',
      occupation: '',
      annualIncome: '',
      address: '',
      
      // 贷款信息
      loanType: '',
      loanAmount: '',
      loanTerm: '',
      repaymentMethod: '',
      loanPurpose: '',
      
      // 抵押物信息
      collateralType: '',
      collateralDescription: '',
      collateralValue: '',
      collateralImages: [],
      ownershipCertificate: [],
      
      // 资料上传
      idCardImages: [],
      incomeProof: [],
      creditReport: [],
      otherDocuments: [],
      
      // 确认项
      agreeTerms: false,
      agreePrivacy: false,
      confirmAccuracy: false
    })
    
    // 表单验证规则
    const formRules = {
      name: [
        { required: true, message: '请输入姓名' },
        { pattern: /^[\u4e00-\u9fa5]{2,20}$/, message: '请输入正确的中文姓名' }
      ],
      idCard: [
        { required: true, message: '请输入身份证号码' },
        { pattern: /^[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]$/, message: '请输入正确的身份证号码' }
      ],
      phone: [
        { required: true, message: '请输入手机号码' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码' }
      ],
      occupation: [
        { required: true, message: '请选择职业' }
      ],
      annualIncome: [
        { required: true, message: '请输入年收入' },
        { pattern: /^\d+(\.\d+)?$/, message: '请输入正确的收入金额' }
      ],
      address: [
        { required: true, message: '请输入联系地址' }
      ],
      loanType: [
        { required: true, message: '请选择贷款类型' }
      ],
      loanAmount: [
        { required: true, message: '请输入贷款金额' },
        { pattern: /^\d+(\.\d+)?$/, message: '请输入正确的贷款金额' }
      ],
      loanTerm: [
        { required: true, message: '请选择贷款期限' }
      ],
      repaymentMethod: [
        { required: true, message: '请选择还款方式' }
      ],
      loanPurpose: [
        { required: true, message: '请说明贷款用途' }
      ],
      collateralType: [
        { required: true, message: '请选择抵押物类型' }
      ],
      collateralDescription: [
        { required: true, message: '请描述抵押物情况' }
      ],
      collateralValue: [
        { required: true, message: '请输入评估价值' },
        { pattern: /^\d+(\.\d+)?$/, message: '请输入正确的价值金额' }
      ],
      collateralImages: [
        { required: true, message: '请上传抵押物照片' }
      ],
      ownershipCertificate: [
        { required: true, message: '请上传产权证明' }
      ],
      idCardImages: [
        { required: true, message: '请上传身份证照片' }
      ],
      incomeProof: [
        { required: true, message: '请上传收入证明' }
      ]
    }
    
    // 选项数据
    const occupationOptions = [
      { label: '农民', value: 'farmer' },
      { label: '养殖户', value: 'breeder' },
      { label: '个体工商户', value: 'individual' },
      { label: '企业员工', value: 'employee' },
      { label: '公务员', value: 'civil_servant' },
      { label: '其他', value: 'other' }
    ]
    
    const loanTypeOptions = [
      { label: '养殖贷款', value: 'breeding_loan' },
      { label: '农业贷款', value: 'agriculture_loan' },
      { label: '经营贷款', value: 'business_loan' },
      { label: '消费贷款', value: 'consumer_loan' }
    ]
    
    const loanTermOptions = [
      { label: '6个月', value: '6' },
      { label: '12个月', value: '12' },
      { label: '24个月', value: '24' },
      { label: '36个月', value: '36' },
      { label: '60个月', value: '60' }
    ]
    
    const repaymentOptions = [
      { label: '等额本息', value: 'equal_payment' },
      { label: '等额本金', value: 'equal_principal' },
      { label: '按月付息到期还本', value: 'interest_only' }
    ]
    
    const collateralTypeOptions = [
      { label: '牲畜', value: 'livestock' },
      { label: '农机设备', value: 'equipment' },
      { label: '土地使用权', value: 'land_use_right' },
      { label: '房产', value: 'real_estate' },
      { label: '其他', value: 'other' }
    ]
    
    // 计算属性
    const canSubmit = computed(() => {
      return formData.agreeTerms && 
             formData.agreePrivacy && 
             formData.confirmAccuracy &&
             formData.idCardImages.length > 0 &&
             formData.incomeProof.length > 0
    })
    
    // 监听贷款信息变化，计算利率
    watch(
      () => [formData.loanAmount, formData.loanTerm, formData.loanType],
      () => {
        if (formData.loanAmount && formData.loanTerm && formData.loanType) {
          calculateEstimatedRate()
        }
      }
    )
    
    // 方法
    const calculateEstimatedRate = async () => {
      try {
        const response = await financeApi.calculateLoanRate({
          loanAmount: formData.loanAmount,
          loanTerm: formData.loanTerm,
          loanType: formData.loanType
        })
        estimatedRate.value = response.data
      } catch (error) {
        console.error('计算利率失败:', error)
      }
    }
    
    const handleOccupationChange = (e) => {
      formData.occupation = e.value
    }
    
    const handleLoanTypeChange = (e) => {
      formData.loanType = e.value
    }
    
    const handleLoanTermChange = (e) => {
      formData.loanTerm = e.value
    }
    
    const handleRepaymentChange = (e) => {
      formData.repaymentMethod = e.value
    }
    
    const handleCollateralTypeChange = (e) => {
      formData.collateralType = e.value
    }
    
    const handleCollateralImagesChange = (fileList) => {
      formData.collateralImages = fileList
    }
    
    const handleOwnershipCertificateChange = (fileList) => {
      formData.ownershipCertificate = fileList
    }
    
    const handleIdCardImagesChange = (fileList) => {
      formData.idCardImages = fileList
    }
    
    const handleIncomeProofChange = (fileList) => {
      formData.incomeProof = fileList
    }
    
    const handleCreditReportChange = (fileList) => {
      formData.creditReport = fileList
    }
    
    const handleOtherDocumentsChange = (fileList) => {
      formData.otherDocuments = fileList
    }
    
    const handleViewTerms = () => {
      uni.navigateTo({
        url: '/pages/agreement/loan-terms'
      })
    }
    
    const handlePrevStep = () => {
      if (currentStep.value > 1) {
        currentStep.value--
      }
    }
    
    const handleNextStep = async () => {
      try {
        // 验证当前步骤的表单
        const stepFields = getStepFields(currentStep.value)
        const valid = await validateStepFields(stepFields)
        
        if (valid && currentStep.value < 4) {
          currentStep.value++
        }
      } catch (error) {
        console.error('表单验证失败:', error)
      }
    }
    
    const getStepFields = (step) => {
      const fieldMap = {
        1: ['name', 'idCard', 'phone', 'occupation', 'annualIncome', 'address'],
        2: ['loanType', 'loanAmount', 'loanTerm', 'repaymentMethod', 'loanPurpose'],
        3: ['collateralType', 'collateralDescription', 'collateralValue', 'collateralImages', 'ownershipCertificate'],
        4: ['idCardImages', 'incomeProof']
      }
      return fieldMap[step] || []
    }
    
    const validateStepFields = async (fields) => {
      // 简化的验证逻辑
      for (const field of fields) {
        const rule = formRules[field]
        if (rule && rule.some(r => r.required)) {
          const value = formData[field]
          if (!value || (Array.isArray(value) && value.length === 0)) {
            uni.showToast({
              title: rule.find(r => r.required)?.message || '请填写必填项',
              icon: 'none'
            })
            return false
          }
        }
      }
      return true
    }
    
    const handleSubmit = async () => {
      try {
        if (!canSubmit.value) {
          uni.showToast({
            title: '请完成所有必填项并同意相关协议',
            icon: 'none'
          })
          return
        }
        
        // 提交申请
        await financeApi.submitLoanApplication(formData)
        
        uni.showModal({
          title: '申请提交成功',
          content: '您的贷款申请已提交，我们将在3个工作日内完成初审并联系您。',
          showCancel: false,
          success: () => {
            uni.navigateBack()
          }
        })
        
      } catch (error) {
        uni.showToast({
          title: '提交失败，请重试',
          icon: 'error'
        })
      }
    }
    
    return {
      formRef,
      currentStep,
      steps,
      formData,
      formRules,
      estimatedRate,
      occupationOptions,
      loanTypeOptions,
      loanTermOptions,
      repaymentOptions,
      collateralTypeOptions,
      canSubmit,
      handleOccupationChange,
      handleLoanTypeChange,
      handleLoanTermChange,
      handleRepaymentChange,
      handleCollateralTypeChange,
      handleCollateralImagesChange,
      handleOwnershipCertificateChange,
      handleIdCardImagesChange,
      handleIncomeProofChange,
      handleCreditReportChange,
      handleOtherDocumentsChange,
      handleViewTerms,
      handlePrevStep,
      handleNextStep,
      handleSubmit
    }
  }
}
</script>

<style lang="scss" scoped>
.loan-apply-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 120rpx;
}

.progress-section {
  background-color: #fff;
  padding: 32rpx;
  margin-bottom: 16rpx;
}

.progress-bar {
  display: flex;
  justify-content: space-between;
  position: relative;
  
  &::before {
    content: '';
    position: absolute;
    top: 32rpx;
    left: 64rpx;
    right: 64rpx;
    height: 4rpx;
    background-color: #e5e5e5;
    z-index: 1;
  }
}

.progress-step {
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
  z-index: 2;
  
  .step-number {
    width: 64rpx;
    height: 64rpx;
    border-radius: 50%;
    background-color: #e5e5e5;
    color: #999;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 24rpx;
    font-weight: 600;
    margin-bottom: 12rpx;
  }
  
  .step-title {
    font-size: 24rpx;
    color: #666;
  }
  
  &.active {
    .step-number {
      background-color: #2e8b57;
      color: #fff;
    }
    
    .step-title {
      color: #2e8b57;
    }
  }
  
  &.completed {
    .step-number {
      background-color: #52c41a;
      color: #fff;
    }
    
    .step-title {
      color: #52c41a;
    }
  }
}

.step-content {
  animation: fadeIn 0.3s ease-in-out;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateX(20rpx); }
  to { opacity: 1; transform: translateX(0); }
}

.form-section {
  margin: 16rpx 32rpx;
}

.form-input {
  width: 100%;
  height: 80rpx;
  padding: 0 24rpx;
  border: 2rpx solid #e5e5e5;
  border-radius: 8rpx;
  font-size: 28rpx;
  background-color: #fff;
  
  &:focus {
    border-color: #2e8b57;
  }
}

.form-textarea {
  width: 100%;
  min-height: 120rpx;
  padding: 16rpx 24rpx;
  border: 2rpx solid #e5e5e5;
  border-radius: 8rpx;
  font-size: 28rpx;
  background-color: #fff;
  resize: none;
  
  &:focus {
    border-color: #2e8b57;
  }
}

.income-input,
.amount-input,
.value-input {
  display: flex;
  align-items: center;
  gap: 16rpx;
  
  .form-input {
    flex: 1;
  }
  
  .income-unit,
  .amount-unit,
  .value-unit {
    font-size: 28rpx;
    color: #666;
  }
}

.upload-btn {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 200rpx;
  height: 200rpx;
  border: 2rpx dashed #d9d9d9;
  border-radius: 8rpx;
  background-color: #fafafa;
  
  .upload-icon {
    font-size: 48rpx;
    margin-bottom: 16rpx;
  }
  
  .upload-text {
    font-size: 24rpx;
    color: #666;
  }
  
  &:active {
    border-color: #2e8b57;
    background-color: #f6ffed;
  }
}

.upload-tip {
  font-size: 24rpx;
  color: #999;
  margin-top: 16rpx;
  line-height: 1.4;
}

.rate-section {
  margin: 16rpx 32rpx;
}

.rate-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 16rpx;
}

.rate-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8rpx;
  
  .rate-label {
    font-size: 24rpx;
    color: #666;
  }
  
  .rate-value {
    font-size: 32rpx;
    color: #2e8b57;
    font-weight: 600;
  }
}

.rate-note {
  font-size: 22rpx;
  color: #999;
  text-align: center;
  padding: 16rpx;
  background-color: #f8f9fa;
  border-radius: 8rpx;
}

.confirm-section {
  margin: 16rpx 32rpx;
}

.confirm-item {
  display: flex;
  align-items: flex-start;
  gap: 16rpx;
  margin-bottom: 24rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
  
  .confirm-text {
    flex: 1;
    font-size: 28rpx;
    color: #333;
    line-height: 1.4;
  }
  
  .link-text {
    color: #2e8b57;
    text-decoration: underline;
  }
}

.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  padding: 24rpx 32rpx;
  background-color: #fff;
  border-top: 2rpx solid #f0f0f0;
  gap: 24rpx;
  z-index: 100;
}

.action-btn {
  flex: 1;
  height: 88rpx;
  border-radius: 8rpx;
  font-size: 32rpx;
  font-weight: 600;
  
  &.prev-btn {
    border: 2rpx solid #d9d9d9;
    background-color: #fff;
    color: #666;
  }
  
  &.next-btn,
  &.submit-btn {
    border: 2rpx solid #2e8b57;
    background-color: #2e8b57;
    color: #fff;
    
    &:disabled {
      opacity: 0.5;
      cursor: not-allowed;
    }
  }
  
  &:active:not(:disabled) {
    opacity: 0.8;
  }
}
</style>