<template>
  <view class="add-card-container">

    <!-- 主要内容 -->
    <view class="main-content">
      <!-- 卡片类型选择 -->
      <view class="card-type-section">
        <view class="section-title">卡片类型</view>
        <u-radio-group
          v-model="selectedType"
          placement="row"
          @change="groupChange"
        >
          <u-radio
            name="bank"
            label="银行卡"
            :disabled="bankDisable"
            activeColor="#4caf50"
          ></u-radio>
          <u-radio
            name="alipay"
            label="支付宝"
            :disabled="alipayDisable"
            activeColor="#4caf50"
          ></u-radio>
        </u-radio-group>
      </view>

      <!-- 表单区域 -->
      <view class="form-section">
        <u-form
          :model="bankForm"
          ref="formRef"
          :rules="rules"
          labelWidth="140"
          labelPosition="left"
        >
          <!-- 银行卡表单 -->
          <template v-if="selectedType === 'bank'">
            <u-form-item label="银行名" prop="bankName" :borderBottom="true">
              <u-input
                v-model="bankForm.bankName"
                placeholder="银行名"
                border="none"
                inputAlign="right"
              />
            </u-form-item>

            <u-form-item label="卡号" prop="cardNumber" :borderBottom="true">
              <u-input
                v-model="bankForm.cardNumber"
                placeholder="卡号"
                border="none"
                inputAlign="right"
                type="number"
              />
            </u-form-item>

            <u-form-item label="姓名" prop="holderName" :borderBottom="true">
              <u-input
                v-model="bankForm.holderName"
                placeholder="姓名"
                border="none"
                inputAlign="right"
              />
            </u-form-item>
          </template>

          <!-- 支付宝表单 -->
          <template v-else-if="selectedType === 'alipay'">
            <u-form-item label="支付宝账号" prop="alipayAccount" :borderBottom="true">
              <u-input
                v-model="bankForm.alipayAccount"
                placeholder="支付宝账号"
                border="none"
                inputAlign="right"
              />
            </u-form-item>

            <u-form-item label="姓名" prop="holderName" :borderBottom="true">
              <u-input
                v-model="bankForm.holderName"
                placeholder="姓名"
                border="none"
                inputAlign="right"
              />
            </u-form-item>
          </template>
        </u-form>
      </view>

      <!-- 设为默认 -->
      <view class="default-section">
        <view class="default-item">
          <text class="default-text">设为默认</text>
          <u-switch
            v-model="bankForm.isDefault"
            :activeColor="'#e9c279'"
            size="20"
          />
        </view>
      </view>

      <!-- 提交按钮 -->
      <view class="submit-section">
        <u-button
          type="primary"
          :customStyle="{
            background: 'linear-gradient(135deg, #e9c279 0%, #d4a853 100%)',
            border: 'none',
            borderRadius: '16rpx',
            height: '88rpx',
            fontSize: '32rpx',
          }"
          @click="submitForm"
        >
          {{ cardInfo?.id ? '保存' : '提交' }}
        </u-button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, computed } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import { saveAccount } from "@/api/user";

// 响应式数据
const selectedType = ref("bank");
const formRef = ref();
const bankDisable = ref(false)
const alipayDisable = ref(false)

const bankForm = reactive({
  bankName: "",
  cardNumber: "",
  alipayAccount: "",
  holderName: "",
  isDefault: false,
});

const cardInfo = ref(null)

onLoad((options) => {
  if (options.id) {
    cardInfo.value = options;
    if (options.accountType === '1') {
      selectedType.value = 'bank'
      bankForm.bankName = options.bankName
      bankForm.cardNumber = options.accountNumber
      bankForm.holderName = options.name
      bankForm.isDefault = options.isDefault === '1'
      alipayDisable.value = true
    } else if (options.accountType === '2'){
      selectedType.value = 'alipay'
      bankDisable.value = true
      bankForm.alipayAccount = options.accountNumber
      bankForm.holderName = options.name
    }
    console.log('cardInfo.value', cardInfo.value)
  }
})

// 表单验证规则
const rules = computed(() => {
  const baseRules = {
    holderName: [
      {
        required: true,
        message: "请输入姓名",
        trigger: "blur",
      },
    ],
  };

  if (selectedType.value === "bank") {
    return {
      ...baseRules,
      bankName: [
        {
          required: true,
          message: "请输入银行名称",
          trigger: "blur",
        },
      ],
      cardNumber: [
        {
          required: true,
          message: "请输入银行卡号",
          trigger: "blur",
        },
        {
          pattern: /^\d{16,19}$/,
          message: "请输入正确的银行卡号",
          trigger: "blur",
        },
      ],
    };
  } else {
    return {
      ...baseRules,
      alipayAccount: [
        {
          required: true,
          message: "请输入支付宝账号",
          trigger: "blur",
        },
        {
          pattern: /^1[3-9]\d{9}$|^[\w\.-]+@[\w\.-]+\.\w+$/,
          message: "请输入正确的手机号或邮箱",
          trigger: "blur",
        },
      ],
    };
  }
});

// 方法
const goBack = () => {
  uni.navigateBack();
};

const groupChange = (val) => {
  // 切换类型时清空表单
  bankForm.bankName = "";
  bankForm.cardNumber = "";
  bankForm.alipayAccount = "";
  bankForm.holderName = "";
};

const submitForm = async () => {
  try {
    const valid = await formRef.value.validate();
    if (valid) {
      // 构建提交数据
      const submitData = {
        type: selectedType.value,
        holderName: bankForm.holderName,
        isDefault: bankForm.isDefault,
      };

      if (selectedType.value === "bank") {
        submitData.bankName = bankForm.bankName;
        submitData.cardNumber = bankForm.cardNumber;
      } else {
        submitData.alipayAccount = bankForm.alipayAccount;
      }

      console.log("提交数据:", submitData);

      const accountType = selectedType.value === 'bank' ? 1 : 2
      const accountNumber = selectedType.value === 'bank' ? bankForm.cardNumber : bankForm.alipayAccount
      const params = {
        id: cardInfo.value?.id,
        bankName: bankForm.bankName,
        accountType,
        accountName: bankForm.holderName,
        accountNumber,
        isDefault: bankForm.isDefault ? 1 : 0
      }
      // 参数中的id不存在 需要把prams.id删掉
      if (!cardInfo.value?.id) {
        delete params.id
      }
      // 如果是支付宝 需要把银行名称字段删除
      if (selectedType.value === 'alipay') {
        delete params.bankName
      }
      // let params = cardInfo.value?.id ? editParams : addParams
      await saveAccount(params)
      const title = cardInfo.value?.id ? '保存成功' : '添加成功'
      uni.showToast({
        title,
        icon: "success",
      });
      // 延迟返回上一页
      setTimeout(() => {
        uni.navigateBack();
      }, 1000);
    }
  } catch (error) {
    console.log("表单验证失败:", error);
  }
};
</script>

<style lang="scss" scoped>
.add-card-container {
  min-height: 100vh;
  background: #f8f9fa;

  .main-content {
    padding: 0 30rpx;

    .card-type-section {
      background: #fff;
      border-radius: 16rpx;
      padding: 30rpx;
      margin: 30rpx 0;

      .section-title {
        color: #333;
        font-size: 32rpx;
        font-weight: 600;
        margin-bottom: 30rpx;
      }

      .type-options {
        display: flex;
        gap: 40rpx;

        .type-option {
          display: flex;
          align-items: center;
          gap: 16rpx;
          padding: 20rpx 0;

          .option-check {
            width: 40rpx;
            height: 40rpx;
            border: 2rpx solid #ddd;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.3s ease;

            .check-icon {
              color: #fff;
              font-size: 24rpx;
              font-weight: 600;
            }
          }

          .option-text {
            color: #333;
            font-size: 28rpx;
            font-weight: 500;
          }

          &.active {
            .option-check {
              background: #4caf50;
              border-color: #4caf50;
            }

            .option-text {
              color: #4caf50;
            }
          }
        }
      }
    }

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

      :deep(.u-form-item) {
        padding: 30rpx 0;

        .u-form-item__label {
          color: #333;
          font-size: 28rpx;
          font-weight: 500;
        }

        .u-input {
          color: #333;
          font-size: 28rpx;

          input {
            color: #333;

            &::placeholder {
              color: #999;
            }
          }
        }
      }
    }

    .default-section {
      background: #fff;
      border-radius: 16rpx;
      padding: 30rpx;
      margin-bottom: 60rpx;

      .default-item {
        display: flex;
        align-items: center;
        justify-content: space-between;

        .default-text {
          color: #333;
          font-size: 28rpx;
          font-weight: 500;
        }
      }
    }

    .submit-section {
      padding: 0 0 60rpx;

      :deep(.u-button) {
        box-shadow: 0 6rpx 20rpx rgba(233, 194, 121, 0.3);
      }
    }
  }
}
</style>
