<template>
  <view class="bank-card-bind">
    <!-- 导航栏 -->
    <view class="nav-bar">
      <view class="back-btn" @click="navigateBack">
        <image  src="/src/static/pic/mark/more-left.png" mode="aspectFit"></image>
      </view>
      <text class="title">{{$t('bank.bindCard')}}</text>
      <view class="right-placeholder"></view>
    </view>
    
    <!-- 表单区域 -->
    <view class="form-container">
      <!-- 银行卡号 -->
      <view class="form-item">
        <text class="form-label">{{$t('bank.bankcardnum')}}</text>
        <view class="input-container">
          <input 
            v-model="formData.cardNumber"
            type="number"
            :placeholder="$t('bank.inputBankcardnum')"
            maxlength="19"
            @input="formatCardNumber"
            class="card-input"
          />
          <image 
            v-if="bankInfo.logo"
            :src="bankInfo.logo"
            class="bank-logo"
            mode="aspectFit"
          />
        </view>
      </view>
      
      <!-- 银行选择 -->
      <view class="form-item">
        <text class="form-label">{{$t('bank.bankname')}}</text>
        <picker 
          @change="handleBankChange"
          :value="bankIndex"
          :range="bankList"
          range-key="name"
        >
          <view class="picker">
            {{ bankList[bankIndex]?.name || $t('bank.selectBankcardname') }}
            <uni-icons type="arrowdown" size="16" color="#999"></uni-icons>
          </view>
        </picker>
      </view>
      
      <!-- 持卡人姓名 -->
      <view class="form-item">
        <text class="form-label">{{$t('bank.cardpersonname')}}</text>
        <input 
          v-model="formData.cardHolder"
          type="text"
          :placeholder="$t('bank.cardpersonnamePlaceholder')"
          maxlength="20"
          class="common-input"
        />
      </view>
      
      <!-- 身份证号 -->
      <view class="form-item">
        <text class="form-label">{{$t('bank.idCard')}}</text>
        <input 
          v-model="formData.idCard"
          type="idcard"
          :placeholder="$t('bank.idCardPlaceholder')"
          maxlength="18"
          class="common-input"
        />
      </view>
      
      <!-- 手机号 -->
      <view class="form-item">
        <text class="form-label">{{$t('bank.cardphone')}}</text>
        <input 
          v-model="formData.phone"
          type="number"
          :placeholder="$t('bank.phonePlaceholder')"
          maxlength="11"
          class="common-input"
        />
      </view>
      
      <!-- 验证码 -->
      <view class="form-item">
        <text class="form-label">{{$t('bank.bankvericode')}}</text>
        <view class="sms-container">
          <input 
            v-model="formData.smsCode"
            type="number"
            :placeholder="$t('bank.vericodePlaceholder')"
            maxlength="6"
            class="sms-input"
          />
          <button 
            class="sms-btn"
            :disabled="isCounting || !canSendSms"
            @click="handleSendSms"
          >
            {{ smsBtnText }}
          </button>
        </view>
      </view>
      
      <!-- 协议 -->
      <view class="agreement">
        <label class="agreement-item">
          <checkbox 
            :checked="formData.agreed"
            @click="formData.agreed = !formData.agreed"
            color="#2979FF"
          />
          <text class="agreement-text">
            {{$t('bank.readagreement')}}
            <text class="agreement-link" @click="viewAgreement(1)">{{ $t('bank.useragresment') }}</text>{{$t('bank.and')}}
            <text class="agreement-link" @click="viewAgreement(2)">{{ $t('bank.bindcardagreement') }}</text>
          </text>
        </label>
      </view>
      
      <!-- 提交按钮 -->
      <button 
        class="submit-btn"
        :disabled="!canSubmit"
        @click="handleSubmit"
      >
    {{ $t('bank.submit') }}
      </button>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      formData: {
        cardNumber: '',
        bankCode: '',
        cardHolder: '',
        idCard: '',
        phone: '',
        smsCode: '',
        agreed: false
      },
      bankList: [
        { name: '中国工商银行', code: 'ICBC', logo: '/static/bank/icbc.png' },
        { name: '中国建设银行', code: 'CCB', logo: '/static/bank/ccb.png' },
        { name: '中国银行', code: 'BOC', logo: '/static/bank/boc.png' },
        { name: '中国农业银行', code: 'ABC', logo: '/static/bank/abc.png' },
        { name: '招商银行', code: 'CMB', logo: '/static/bank/cmb.png' },
        { name: '交通银行', code: 'BOCOM', logo: '/static/bank/bocom.png' }
      ],
      bankIndex: 0,
      bankInfo: {},
      isCounting: false,
      countdown: 60,
      timer: null
    }
  },
  computed: {
    smsBtnText() {
      return this.isCounting ? `${this.countdown}s` : this.$t('bank.getverifycode')
    },
    canSendSms() {
      return /^1[3-9]\d{9}$/.test(this.formData.phone)
    },
    canSubmit() {
      return (
        this.formData.cardNumber.replace(/\s/g, '').length >= 16 &&
        this.formData.bankCode &&
        this.formData.cardHolder &&
        /^\d{17}[\dXx]$/.test(this.formData.idCard) &&
        /^1[3-9]\d{9}$/.test(this.formData.phone) &&
        /^\d{6}$/.test(this.formData.smsCode) &&
        this.formData.agreed
      )
    }
  },
  methods: {
    // 返回上一页
   navigateBack() {
      uni.navigateBack({
        delta: 1
      })
    },
    
    // 格式化银行卡号
    formatCardNumber(e) {
      let value = e.detail.value.replace(/\s/g, '')
      if (value.length > 0) {
        value = value.match(/.{1,4}/g).join(' ')
      }
      this.formData.cardNumber = value
      
      // 检测银行
      if (value.replace(/\s/g, '').length >= 6) {
        this.detectBank(value.replace(/\s/g, ''))
      } else {
        this.bankInfo = {}
      }
    },
    
    // 检测银行
    detectBank(cardNumber) {
      // 实际项目调用银行卡BIN接口
      const binMap = {
        '622202': 'ICBC',
        '622588': 'CMB',
        '622700': 'CCB',
        '621661': 'BOC',
        '622848': 'ABC',
        '622260': 'BOCOM'
      }
      
      const bin = cardNumber.substring(0, 6)
      const bankCode = binMap[bin]
      
      if (bankCode) {
        const bank = this.bankList.find(item => item.code === bankCode)
        if (bank) {
          this.bankInfo = bank
          this.formData.bankCode = bankCode
          this.bankIndex = this.bankList.findIndex(item => item.code === bankCode)
        }
      }
    },
    
    // 选择银行
    handleBankChange(e) {
      this.bankIndex = e.detail.value
      this.formData.bankCode = this.bankList[this.bankIndex].code
      this.bankInfo = this.bankList[this.bankIndex]
    },
    
    // 发送验证码
    handleSendSms() {
      if (!this.canSendSms) {
        uni.showToast({
          title: "$t('bank.inputcorrectphone')",
          icon: 'none'
        })
        return
      }
      
      uni.showLoading({ title: "$t('bank.sendingcode')" })
      
      // 模拟发送验证码
      setTimeout(() => {
        uni.hideLoading()
        uni.showToast({
          title: "$t('bank.codesent')",
          icon: 'success'
        })
        this.startCountdown()
      }, 1500)
    },
    
    // 开始倒计时
    startCountdown() {
      this.isCounting = true
      this.countdown = 60
      
      this.timer = setInterval(() => {
        this.countdown--
        
        if (this.countdown <= 0) {
          clearInterval(this.timer)
          this.isCounting = false
        }
      }, 1000)
    },
    
    // 查看协议
    viewAgreement(type) {
      const url = type === 1 ? '/pages/agreement/user' : '/pages/agreement/bank'
      uni.navigateTo({ url })
    },
    
    // 提交表单
    handleSubmit() {
      if (!this.validateForm()) return
      
      uni.showLoading({ title: "$t(bank.binding)" })
      
      // 模拟API请求
      setTimeout(() => {
        uni.hideLoading()
        uni.showToast({
          title: "$t('bank.bindSuccess')",
          icon: 'success'
        })
        
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
      }, 2000)
    },
    
    // 表单验证
    validateForm() {
      if (!this.formData.cardNumber || this.formData.cardNumber.replace(/\s/g, '').length < 16) {
        uni.showToast({ title: "$t('bank.inputcorrectcardnum')", icon: 'none' })
        return false
      }
      
      if (!this.formData.bankCode) {
        uni.showToast({ title: "$t('bank.selectbank')", icon: 'none' })
        return false
      }
      
      if (!this.formData.cardHolder) {
        uni.showToast({ title: "$t('bank.inputcorrectcardpersonname')", icon: 'none' })
        return false
      }
      
      if (!/^\d{17}[\dXx]$/.test(this.formData.idCard)) {
        uni.showToast({ title: "$t('bank.inputcorrectidcardnum')", icon: 'none' })
        return false
      }
      
      if (!/^1[3-9]\d{9}$/.test(this.formData.phone)) {
        uni.showToast({ title: "$t('bank.inputcorrectphone')", icon: 'none' })
        return false
      }
      
      if (!/^\d{6}$/.test(this.formData.smsCode)) {
        uni.showToast({ title: "$t('bank.inputcorrectcode')", icon: 'none' })
        return false
      }
      
      if (!this.formData.agreed) {
        uni.showToast({ title: "$t('bank.inputcorrectcode')", icon: 'none' })
        return false
      }
      
      return true
    }
  },
  beforeDestroy() {
    if (this.timer) {
      clearInterval(this.timer)
    }
  }
}
</script>

<style lang="scss" scoped>
.bank-card-bind {
  background-color: #f7f7f7;
  min-height: 100vh;
  padding-bottom: 40rpx;
}

.nav-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20rpx;
  padding-top: var(--status-bar-height);
  
  .back-btn {
    width: 100rpx;
    height: 100rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    image {
      width: 40rpx;
      height: 40rpx;
      filter: invert(1);
    }
  }
  
  .title {
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
    flex: 1;
    text-align: center;
  }
  
  .right-placeholder {
    width: 60rpx;
  }
}

.form-container {
  padding: 30rpx;
}

.form-item {
  margin-bottom: 30rpx;
  
  .form-label {
    display: block;
    font-size: 28rpx;
    color: #666;
    margin-bottom: 20rpx;
    font-weight: 500;
  }
  
  .input-container {
    position: relative;
    
    .card-input {
      height: 90rpx;
      background-color: #fff;
      border-radius: 12rpx;
      padding: 0 30rpx;
      font-size: 32rpx;
      border: 1rpx solid #eee;
      width: 100%;
      box-sizing: border-box;
    }
    
    .bank-logo {
      position: absolute;
      right: 20rpx;
      top: 50%;
      transform: translateY(-50%);
      width: 50rpx;
      height: 50rpx;
    }
  }
  
  .picker {
    height: 90rpx;
    line-height: 90rpx;
    background-color: #fff;
    border-radius: 12rpx;
    padding: 0 30rpx;
    font-size: 32rpx;
    border: 1rpx solid #eee;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  
  .common-input {
    height: 90rpx;
    background-color: #fff;
    border-radius: 12rpx;
    padding: 0 30rpx;
    font-size: 32rpx;
    border: 1rpx solid #eee;
    width: 100%;
    box-sizing: border-box;
  }
  
  .sms-container {
    display: flex;
    
    .sms-input {
      flex: 1;
      height: 90rpx;
      background-color: #fff;
      border-radius: 12rpx;
      padding: 0 30rpx;
      font-size: 32rpx;
      border: 1rpx solid #eee;
      margin-right: 20rpx;
    }
    
    .sms-btn {
      width: 220rpx;
      height: 90rpx;
      line-height: 90rpx;
      font-size: 28rpx;
      background-color: #f0f7ff;
      color: #2979FF;
      border-radius: 12rpx;
      margin: 0;
      padding: 0;
      
      &[disabled] {
        background-color: #f5f5f5;
        color: #999;
      }
    }
  }
}

.agreement {
  margin: 40rpx 0;
  
  .agreement-item {
    display: flex;
    align-items: center;
    font-size: 26rpx;
  }
  
  .agreement-text {
    color: #666;
    margin-left: 10rpx;
  }
  
  .agreement-link {
    color: #2979FF;
  }
}

.submit-btn {
  height: 90rpx;
  line-height: 90rpx;
  background-color: #2979FF;
  color: #fff;
  font-size: 34rpx;
  border-radius: 45rpx;
  margin-top: 20rpx;
  
  &[disabled] {
    background-color: #a0c0ff;
  }
}
</style>