<template>
    <view class="container">
        <!-- 顶部提示 -->
        <view class="notice">
            <text class="notice-text">需绑定本人I类银行账户借记卡，否则无法发放佣金</text>
        </view>

        <!-- 表单区域 -->
        <view class="form-section">
            <!-- 银行卡号 -->
            <view class="form-item">
                <text class="label">银行卡号</text>
                <view class="input-wrapper">
                    <input
                        class="input"
                        v-model="bankInfo.cardNumber"
                        placeholder="请输入银行卡号"
                        @input="onFieldChange"
                    />
                    <view class="camera-icon" @click="scanBankCard">
                        <uni-icons type="camera-filled" size="30"></uni-icons>
                    </view>
                </view>
            </view>

            <!-- 开户行 -->
            <view class="form-item">
                <text class="label">开户行</text>
                <input
                    class="input"
                    v-model="bankInfo.bankName"
                    placeholder="请输入开户行"
                    @input="onFieldChange"
                />
            </view>

            <!-- 预留手机号 -->
            <view class="form-item">
                <text class="label">预留手机号</text>
                <input
                    class="input"
                    v-model="bankInfo.phone"
                    placeholder="请输入银行预留手机号"
                    @input="onFieldChange"
                />
            </view>
        </view>

        <!-- 底部按钮 -->
        <view class="action-buttons">
            <button class="btn secondary" @click="handleBack">返回</button>
            <button
                class="btn primary"
                @click="handleSubmit"
                :disabled="loading"
            >
                {{ isEditMode ? '已认证' : loading ? '提交中...' : '去认证' }}
            </button>
        </view>
    </view>
</template>

<script>
import UniIcons from "@/uni_modules/uni-icons/components/uni-icons/uni-icons.vue";
import { authApi } from "@/api/auth";

export default {
    components: { UniIcons },
    data() {
        return {
            loading: false,
            isEditMode: false, // 编辑/查看模式
            originalData: null, // 原始数据
            bankInfo: {
                cardNumber: '',
                bankName: '',
                phone: ''
            }
        };
    },
    computed: {
        canSubmit() {
            return (
                this.bankInfo.cardNumber &&
                this.bankInfo.bankName &&
                /^1[3-9]\d{9}$/.test(this.bankInfo.phone)
            );
        },
    },
    onLoad(options) {
        this.initData(options);
    },
    methods: {
        // 初始化数据
        initData(options) {
            if (options.payload) {
                try {
                    const payload = JSON.parse(decodeURIComponent(options.payload));
                    this.originalData = payload.fourAuthInfo || {};

                    // 自动识别编辑模式
                    this.isEditMode = !!this.originalData.cardNumber;

                    // 数据映射
                    this.bankInfo = {
                        cardNumber: this.originalData.cardNumber || '',
                        bankName: this.originalData.bankName || '',
                        phone: this.originalData.phone || this.originalData.reservedPhone || ''
                    };

                    // 处理真实银行卡号显示
                    if (this.isEditMode) {
                        this.bankInfo.cardNumber = this.maskCardNumber(this.bankInfo.cardNumber);
                    }
                } catch (e) {
                    console.error('参数解析失败:', e);
                    uni.showToast({ title: '数据加载失败', icon: 'none' });
                }
            }
        },

        // 银行卡号脱敏处理
        maskCardNumber(card) {
            return card;
            return card.replace(/^(\d{4})\d+(\d{4})$/, '$1 ​**** ​**** $2');
        },

        // 扫描银行卡
        async scanBankCard() {
            if (this.isEditMode) return;

            try {
                const res = await uni.chooseImage({
                    count: 1,
                    sourceType: ['camera'],
                    sizeType: ['compressed']
                });

                // 调用OCR识别接口
                const ocrRes = await authApi.bankCardOcr({
                    image: res.tempFilePaths[0]
                });

                if (ocrRes.code === 0) {
                    this.bankInfo = {
                        ...this.bankInfo,
                        cardNumber: ocrRes.data.cardNumber,
                        bankName: ocrRes.data.bankName
                    };
                    uni.showToast({ title: '识别成功', icon: 'success' });
                }
            } catch (error) {
                uni.showToast({ title: '识别失败', icon: 'none' });
            }
        },
        onFieldChange() {
            this.isEditMode = false;

            if (this.isEditMode) {
                // this.isEditMode = true;
            }
        },

        // 表单验证
        validateForm() {
            const rules = {
                cardNumber: {
                    test: val => /^\d{16,19}$/.test(val),
                    message: '银行卡号格式错误'
                },
                bankName: {
                    test: val => val.length >= 2,
                    message: '开户行名称过短'
                },
                phone: {
                    test: val => /^1[3-9]\d{9}$/.test(val),
                    message: '手机号格式错误'
                }
            };

            for (const [key, rule] of Object.entries(rules)) {
                if (!rule.test(this.bankInfo[key])) {
                    uni.showToast({ title: rule.message, icon: 'none' });
                    return false;
                }
            }
            return true;
        },

        // 提交认证
        async handleSubmit() {
            if (this.isEditMode || !this.validateForm() || this.loading) return;

            try {
                this.loading = true;

                // 合并原始数据
                const submitData = {
                    ...this.originalData,
                    ...this.bankInfo,
                    // 恢复真实卡号（如果脱敏处理）
                    cardNumber: this.originalData?.cardNumber || this.bankInfo.cardNumber
                };

                const res = await authApi.fourElementApi(submitData);

                if (res.code === 0) {
                    uni.showToast({ title: '认证成功' });

                    // 更新上级页面
                    const eventChannel = this.getOpenerEventChannel();
                    eventChannel.emit('updateBankInfo', submitData);

                    setTimeout(() => uni.navigateBack(), 1500);
                } else {
                    uni.showToast({ title: res.msg || '认证失败', icon: 'none' });
                }
            } catch (error) {
                uni.showToast({ title: '请求失败，请检查网络', icon: 'none' });
            } finally {
                this.loading = false;
            }
        },

        // 返回操作
        handleBack() {
            uni.navigateBack();
        }
    }
};
</script>


<style lang="scss" scoped>
.container {
  background: #fff;
  min-height: 100vh;
  padding: 40rpx;
}

.notice {
  padding: 20rpx;
  background: #fff7e6;
  border-radius: 8rpx;
  margin-bottom: 40rpx;

  &-text {
    color: #fa8c16;
    font-size: 26rpx;
  }
}

.form-section {
  .form-item {
    display: flex;
    align-items: center;
    min-height: 96rpx;
    //margin-bottom: 40rpx;
    //padding: 20rpx 0;
    border-bottom: 1rpx solid #eee;

    .label {
      width: 160rpx;
      font-size: 28rpx;
      color: #666;
      flex-shrink: 0;
    }

    .input-wrapper {
      flex: 1;
      position: relative;
      display: flex;
      align-items: center;
    }

    .input {
      flex: 1;
      height: 60rpx;
      font-size: 28rpx;
      color: #333;
      padding-right: 80rpx;
    }

    .camera-icon {
      position: absolute;
      right: 0;
      width: 60rpx;
      height: 60rpx;
      display: flex;
      align-items: center;
      justify-content: center;

      .icon {
        width: 40rpx;
        height: 40rpx;
      }
    }
  }
}

.action-buttons {
  position: fixed;
  bottom: 40rpx;
  left: 40rpx;
  right: 40rpx;
  display: flex;
  gap: 20rpx;

  .btn {
    flex: 1;
    height: 88rpx;
    line-height: 88rpx;
    border-radius: 44rpx;
    font-size: 32rpx;

    &.secondary {
      background: #f5f5f5;
      color: #666;
    }

    &.primary {
      background: #007aff;
      color: #fff;
    }
  }
}


</style>
