<template>
  <div class="ml30 mr30" style="min-height:100vh;">
    <div class="">
      <van-form @submit="onSubmit" :rules="rules">
        <div class="fn-flex fn-flex-column" style="min-height:100vh;">
          <div class="fn-flex-item pt30">
            <div class="box-shadow-darkGray inner10 ulib-r20 pb30">
              <div class="text-center mt20 font-28 text-color-theme">
                <div>仅支持客户本人在中国境内开设的银行卡</div>
                <div class="mt10">若信息不一致，将导致补贴无法到账</div>
              </div>
              <!-- 上传银行卡照片（必填） -->
              <van-cell title="上传银行卡照片" :border="false">
              </van-cell>
              <div class="upload-box ml20 mr20">
                <van-field
                    name="bankFile"
                    :rules="rules.bankFile"
                    style="background: rgba(0, 0, 0, 0)"
                >
                  <template #input>
                    <van-uploader v-model="form.bankFile" :multiple="false" :max-count="1" accept="image/*"
                                  :after-read="onBankRead">
                      <template #preview-cover="{ file }" v-if="file && file.name">
                        <div class="preview-cover van-ellipsis">{{ file.name }}</div>
                      </template>
                      <div class="fn-flex fn-flex-column fn-flex-center mt30">
                        <i class="icon-custom icon-file"></i>
                        <div class="fn-flex fn-flex-center mt10" style="gap: 10px;">
                          <van-button type="default" size="mini" round style="padding:1.2vw 2vw;">上传银行卡照片
                          </van-button>
                        </div>
                      </div>
                    </van-uploader>
                  </template>
                </van-field>
              </div>
              <van-field
                  label="银行卡号"
                  :type="!form.id ? 'number':''"
                  input-align="right"
                  placeholder="请输入银行卡号"
                  v-model="form.bankCardNum"
                  :rules="[{ required: true, message: '请输入银行卡号' }]"
              />
              <van-field label="开户行名称" input-align="right" placeholder="请输入开户行名称"
                         v-model="form.bankName"
                         :rules="[{ required: true, message: '请输入开户行名称' }]"/>
              <van-field
                  :type="!form.id ? 'number':''"
                  input-align="right"
                  placeholder="请输入手机号"
                  v-model="form.mobile"
                  :rules="[{ required: true, message: '请输入手机号' }]"
              >
                <template #label>
                  <div style="white-space: normal; width: 100px;">银行预留手机号</div>
                </template>
              </van-field>
              <van-field
                  label="验证码"
                  input-align="right"
                  placeholder="请输入验证码"
                  v-model="form.code"
                  :rules="[{ required: true, message: '请输入验证码' }]"
                  v-if="!form.id"
                  type="number"
              >
                <template #button>
                  <van-button
                      size="small"
                      type="danger"
                      @click="getCode"
                      :disabled="isDisabled"
                  >
                    {{ buttonText }}
                  </van-button>
                </template>
              </van-field>
            </div>
          </div>
          <div class="text-center pt40 pb30" v-if="!form.id">
            <!-- 提交按钮 -->
            <van-button type="danger" round block native-type="submit" :loading="submitting">
              {{ submitting ? '提交中...' : '提交' }}
            </van-button>
          </div>
        </div>
      </van-form>
    </div>
    <SideMenu :name="'我的'"/>
  </div>

</template>

<script setup>
import {ref, reactive, onMounted} from 'vue';
import {useRoute, useRouter} from 'vue-router';
import {showConfirmDialog, showDialog, showToast} from 'vant';
import api from '../utils/api.js' // 导入API
import SideMenu from '@/components/SideMenu.vue' // 导入SideMenu组件
import WechatUtils,{ WechatShare } from '@/utils/wechat'


const route = useRoute();
const router = useRouter();
//补贴id
const subsidyId = ref(route.params.subsidyId || route.query.subsidyId || '');
// 表单数据
const form = reactive({
  id: '',
  mobile: '',
  bankCardNum: '',
  bankName: '',
  code: '',
  bankFile: [],
  bankUrl: ''
});

// 提交状态
const submitting = ref(false);

// 校验规则
const rules = {
  bankFile: [{validator: (val) => val && val.length > 0, message: '请上传银行卡照片'}],
};
//获取验证码
const isDisabled = ref(false);
const buttonText = ref('获取验证码');
const countdown = ref(60);

// 组件挂载ef(时检查补贴ID
onMounted(async () => {
  let appid = localStorage.getItem('app_id')
  if(appid) {
    await WechatUtils.init(appid);
    // 隐藏分享
    await WechatShare.hideAllNonBaseMenuItem();
  }
  const carInfo = await getCardInfo();
  console.info('银行卡信息', carInfo);
  Object.assign(form, carInfo);
  console.log("form表单数据:", form);
});

/**
 * 上传图片
 * @param {File} file - 图片文件
 */
const uploadImage = async (file) => {
  try {
    const formData = new FormData();
    formData.append('file', file);

    const response = await api.upload(formData, {headers: {'Content-Type': 'multipart/form-data'}});
    if (response.code === 200) {
      return response.data;
    } else {
      console.error('上传图片失败:', response.message);
      return null;
    }
  } catch (error) {
    console.error('上传图片异常:', error);
    return null;
  }
};

/**
 * 提交审核资料
 * @param {Object} submitData - 提交的数据
 */
const submitSubsidyData = async (submitData) => {
  try {
    const response = await api.post('/auto/ucenter/cardInfo', {
      ...submitData
    });
    if (response.code === 200) {
      return response;
    } else {
      throw new Error(response.message || '提交失败');
    }
  } catch (error) {
    console.error('提交审核资料异常:', error);
    throw error;
  }
};

/**
 * 获取银行卡信息
 */
const getCardInfo = async () => {
  try {
    const response = await api.get('/auto/ucenter/cardInfo');
    if (response.code === 200) {
      return response.data;
    } else {
      throw new Error(response.message || '提交失败');
    }
  } catch (error) {
    console.error('提交审核资料异常:', error);
    throw error;
  }
};

// 银行卡上传处理
const onBankRead = async (file) => {
  console.log('上传银行卡图片:', file);
  const uploadResult = await uploadImage(file.file);
  if (uploadResult) {
    form.bankUrl = uploadResult.url;
    console.log('银行卡图片上传成功:', uploadResult);
  } else {
    showToast('银行卡图片上传失败');
  }
};

// 验证表单数据
const validateForm = () => {
  const errors = [];
  if (!form.bankUrl) {
    errors.push('请上传银行卡照片');
  }
  return errors;
};

// 提交处理
const onSubmit = async (values) => {
  console.log('提交数据:', values);
  console.log('完整表单数据:', form);

  // 验证表单
  const errors = validateForm();
  if (errors.length > 0) {
    showToast(errors[0]);
    return;
  }

  // 显示确认弹窗
  try {
    await showConfirmDialog({
      title: '确定要提交吗？',
      message: '',
      confirmButtonText: '提交',
      cancelButtonText: '取消',
      confirmButtonColor: '#f84803'
    });

    // 用户确认后开始提交
    submitting.value = true;

    const result = await submitSubsidyData(form);
    let message = '';
    if(subsidyId.value>0){
      message = "您的补贴将在1个工作日内到账\n请您注意查收\n";
    }
    message += "若需修改信息，请联系客服";
    showDialog({
      title: '绑定成功',
      message: message,
      confirmButtonColor: '#f84803'
    }).then(() => {
      // 提交成功后跳转到我的补贴页面
      if(subsidyId.value>0){
        router.replace('/my/allowance');
      }else{
        //刷新当前页
        router.go(0);
      }
    });
  } catch (error) {
    if (error === 'cancel') {
      // 用户取消了提交
      return;
    }

    console.error('提交失败:', error);
    showToast(error.message || '提交失败，请重试');
  } finally {
    submitting.value = false;
  }
};
// 获取验证码
const getCode = async () => {
  if (!form.mobile) {
    showToast('请输入手机号');
    return;
  }
  // 模拟发送验证码请求
  console.log('发送验证码到:', form.mobile);
  try {
    const response = await api.post('/auto/sms', {mobile: form.mobile, type: 'bank'});
    if (response.code === 200) {
      showToast(response.message);
      isDisabled.value = true;
      let timer = setInterval(() => {
        if (countdown.value > 0) {
          buttonText.value = `重新发送(${countdown.value})`;
          countdown.value--;
        } else {
          clearInterval(timer);
          buttonText.value = '获取验证码';
          countdown.value = 60;
          isDisabled.value = false;
        }
      }, 1000);
    } else {
      throw new Error(response.message || '获取验证码失败');
    }
  } catch (error) {
    console.error('获取验证码异常:', error);
    showToast(error.message);
  }
};
</script>

<style scoped lang="scss">
.upload-box {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  /* width: 100%; */
  height: 260px;
  background-color: #f9f9f9;

  ::v-deep {
    .van-uploader {
      width: 100%;
      height: 100%;

      .van-uploader__wrapper {
        width: 100%;
        height: 100%;
        overflow: hidden;
      }

      .van-uploader__preview {
        // margin-top: 3vw;
        margin: 0;
      }

      .van-uploader__preview-image {
        width: 100%;
        height: 100%;
      }

      .van-uploader__input-wrapper {
        width: 100%;
      }

      // width: 100%;
    }
  }
}

.upload-text {
  margin-top: 10px;
}

.view-example {
  color: #527acc;
  font-size: 26px;
  display: block;
}

.agreement {
  text-align: center;
  // margin: 20px 0;
  font-size: 26px;
}

.agreement-link {
  color: #527acc;
  margin: 0 5px;
  display: inline-block;
}

.van-field__label {
  width: 100px;
}
</style>