<template>
  <view class="container">
    <!-- 顶部背景区域 -->
    <view class="header-bg">
      <view class="balance-info">
        <text class="balance-title">可用余额</text>
        <text class="balance-amount">{{ appStore.$userInfo.nowMoney }}</text>
      </view>
    </view>

    <!-- 主要内容区域 -->
    <view class="content">
      <!-- Tab栏（已移入content顶部） -->
      <view class="tab-container">
        <view
          class="tab-item"
          :class="{ active: activeTab.index === index }"
          v-for="(tab, index) in tabs"
          :key="index"
          @click="switchTab(tab)"
        >
          {{ tab.name }}
        </view>
      </view>

      <!-- 权益标签 -->
      <!-- <view class="rights-tag">权益 -0</view> -->

      <!-- 选择克重标题 -->
      <view class="section-title">
        <text class="title-text">选择克重</text>
        <view class="real-price-wrapper">
          <view class="label">
            <text class="real-price-label">实时金价</text>
            <text class="real-price-value" v-show="activeTab.index === 0">{{
              realGoldprice
            }}</text>
            <text class="real-price-value" v-show="activeTab.index === 1">{{
              realPtprice
            }}</text>
            <text class="real-price-value" v-show="activeTab.index === 2">{{
              realAgprice
            }}</text>
            <text class="real-price-unit">/g</text>
          </view>
          <view class="rights-tag-ellipse">
            <text v-show="activeTab.index === 0"
              >权益 -{{ goldAdjustPrice }}</text
            >
            <text v-show="activeTab.index === 1"
              >权益 -{{ PtAdjustPrice }}</text
            >
            <text v-show="activeTab.index === 2"
              >权益 -{{ AgAdjustPrice }}</text
            >
            <view class="ellipse-arrow"></view>
          </view>
        </view>
      </view>

      <!-- 克重选择按钮 -->
      <view class="weight-grid">
        <view
          class="weight-item"
          :class="{ active: selectedWeight === weight }"
          v-for="weight in weightOptions"
          :key="weight"
          @click="selectWeight(weight)"
        >
          {{ weight }}克
        </view>
      </view>

      <!-- 自定义输入区域 -->
      <view class="custom-input-section">
        <view class="input-container">
          <input
            class="custom-input"
            type="number"
            v-model="customWeight"
            placeholder="请输入克数"
            @input="onInputChange"
          />
          <text class="input-unit">g</text>
        </view>
      </view>

      <!-- 预计金额 -->
      <view class="total-amount">
        <text>预计金额 {{ estimatePrice }} 元</text>
      </view>

      <!-- 协议选择 -->
      <view
        class="agreement-section"
        style="display: flex; align-items: center"
      >
        <up-checkbox
          v-model:checked="agreedToTerms"
          shape="square"
          activeColor="#e9c279"
          usedAlone
          :customStyle="{ marginRight: '12rpx' }"
        >
          <template #label>
            <text class="agreement-text"> 阅读并同意 </text>
          </template>
        </up-checkbox>
        <view class="agreement-link" @click="showAgreement">《余料买入协议》</view>
      </view>

      <!-- 提交按钮 -->
      <view class="submit-section">
        <button
          class="submit-btn"
          :class="{ disabled: !canSubmit }"
          :disabled="!canSubmit"
          @click="handleSubmit"
        >
          立即购买
        </button>
      </view>
    </view>

    <!-- 协议弹窗 -->
    <up-popup
      :show="showAgreementPopup"
      mode="center"
      border-radius="20"
      width="80%"
      height="60%"
    >
      <view class="popup-content">
        <view class="popup-header">
          <!-- <text class="popup-title">买金协议</text> -->
          <!-- <text class="popup-close" @click="closeAgreement">×</text> -->
        </view>
        <scroll-view scroll-y scroll-left="50" class="popup-body">
          <view class="agreement-content">
            <Aggrement /> 
          </view>
        </scroll-view>
        <view class="popup-footer">
          <button class="popup-btn" @click="closeAgreement">
            我已详细知悉
          </button>
        </view>
      </view>
    </up-popup>

    <!-- 未实名提示 -->
    <up-modal
      :show="showDetectModal"
      title="当前用户未实名"
      :showCancelButton="true"
      confirmText="去认证"
      @confirm="toFaceVerify"
      @cancel="showDetectModal = false"
      @close="showDetectModal = false"
    />
  </view>
</template>

<script setup>
import { ref, computed, watch } from "vue";
import { onShow } from "@dcloudio/uni-app";
import useRealGoldPrice from "@/hooks/useRealGoldPrice";
import { buyGold } from "@/api/vault";
import { getUserInfo } from "@/api/user";
import { useAppStore } from "@/stores/app";
import { useToast } from '@/hooks/useToast'
import Aggrement from './aggrement.vue'

const appStore = useAppStore();
const { Toast } = useToast()

const {
  realGoldprice,
  realPtprice,
  realAgprice,
  fetchGoldPrice,
  goldAdjustPrice,
  PtAdjustPrice,
  AgAdjustPrice,
} = useRealGoldPrice();

onShow(() => {
  fetchGoldPrice();
});

// const tabs = ["黄金", "铂金", "白银"];
const tabs = [
  { name: "黄金", mentalType: 1, index: 0 },
  { name: "铂金", mentalType: 2, index: 1 },
  { name: "白银", mentalType: 3, index: 2 },
];
const activeTab = ref(tabs[0]);
const selectedWeight = ref(0);
const customWeight = ref("");
const currentPrice = ref("775.53");
const agreedToTerms = ref(false);
const showAgreementPopup = ref(false);
const showDetectModal = ref(false)

// 克重选项
const weightOptions = [10, 20, 30, 50, 100, 200, 300, 500, 1000];

// 计算总金额
const totalAmount = computed(() => {
  const weight = selectedWeight.value || parseFloat(customWeight.value) || 0;
  const price = parseFloat(currentPrice.value);
  return (weight * price).toFixed(1);
});

// 是否可以提交
const canSubmit = computed(() => {
  const hasWeight =
    selectedWeight.value > 0 ||
    (customWeight.value && parseFloat(customWeight.value) > 0);
  return hasWeight;
});

// 切换黄金类型
const switchTab = (tab) => {
  console.log("tab", tab.name);
  if (activeTab.value.name === tab.name) return;
  activeTab.value = tab;
  if (tab.name === "铂金" && PtAdjustPrice.value === 0) {
    fetchGoldPrice("RTJ_Pt");
  } else if (tab.name === "白银" && AgAdjustPrice.value === 0) {
    fetchGoldPrice("RTJ_Ag");
  }
};

const selectWeight = (weight) => {
  selectedWeight.value = weight;
  customWeight.value = "";
};

const onInputChange = (e) => {
  const value = e.detail.value;
  customWeight.value = value;
  if (value) {
    selectedWeight.value = 0;
  }
};

const realWeight = computed(() => {
  return selectedWeight.value === 0 ? customWeight.value : selectedWeight.value;
});

// 预估价
const estimatePrice = computed(() => {
  if (!realWeight.value) return 0;
  if (activeTab.value.name === "黄金") {
    return (realWeight.value * realGoldprice.value).toFixed(2);
  } else if (activeTab.value.name === "铂金") {
    return (realWeight.value * realPtprice.value).toFixed(2);
  } else if (activeTab.value.name === "白银") {
    return (realWeight.value * realAgprice.value).toFixed(2);
  }
  return 0;
});

const showAgreement = () => {
  showAgreementPopup.value = true;
};

const closeAgreement = () => {
  showAgreementPopup.value = false;
};

function toFaceVerify() {
  showDetectModal.value = false
  uni.navigateTo({ url: '/pages/users/face_detect/index' })
}

const handleSubmit = async () => {
  if (!canSubmit.value) return;
  try {
    const priceMap = {
      0: realGoldprice.value,
      1: realPtprice.value,
      2: realAgprice.value,
    };
    if (!agreedToTerms.value) {
      return Toast({ title: "请阅读并同意协议" });
    }

    // 判断是否认证
    if (!appStore.userPanelInfoGetter.realNameVerified) {
      showDetectModal.value = true
      return 
    }

    if (Number(priceMap[activeTab.value.index]) > Number(appStore.$userInfo.nowMoney)) {
      return Toast({ title: "余额不足" });
    }

    uni.showLoading({title: '加载中'})
    const weight = selectedWeight.value || parseFloat(customWeight.value);

    const params = {
      userId: appStore.uid,
      operationType: 4, // 4 - 买金
      weight,
      price: priceMap[activeTab.value.index],
      metalType: activeTab.value.mentalType,
      type: 1,
    };
    await buyGold(params);
    const { data } = await getUserInfo()
    appStore.UPDATE_USERINFO(data);
    uni.showToast({
      title: `购买成功`,
      icon: "success",
    });
    
  } catch (error) {
    console.error("buyGold", error);
    const title = typeof error === 'string' ? error : '购买失败'
    uni.showToast({
      title,
      icon: "error",
    });
  } finally {
    uni.hideLoading()
  }
};

// 监听自定义输入
watch(customWeight, (newVal) => {
  if (newVal) {
    selectedWeight.value = 0;
  }
});
</script>

<style lang="scss" scoped>
// $header-color: #e9c279;
// $primary-color: #e9c279;
// $text-color: #333;
// $light-text: #666;
// $border-color: #f0f0f0;

.container {
  min-height: 90vh;
  background-color: #f8f8f8;
}

.header-bg {
  background-image: linear-gradient(
    to bottom,
    #e9c279 0%,
    #e9c279 10%,
    #f0dab2 70%,
    transparent 100%
  );
  padding: 40rpx 30rpx 30rpx;
  height: 400rpx;
  position: relative;
}

.balance-info {
  text-align: center;
  margin-bottom: 60rpx;

  .balance-title {
    display: block;
    color: white;
    font-size: 28rpx;
    margin-bottom: 20rpx;
  }

  .balance-amount {
    display: block;
    color: white;
    font-size: 80rpx;
    font-weight: bold;
  }
}

.tab-container {
  display: flex;
  justify-content: center;
  gap: 60rpx;
  margin-top: 0;
  margin-bottom: 40rpx;
  // border-bottom: 2rpx solid #f0f0f0;
}

.tab-item {
  color: #333;
  font-size: 32rpx;
  padding: 20rpx 0;
  position: relative;
  cursor: pointer;
  background: transparent;
  font-weight: normal;
  transition: color 0.2s;

  &.active {
    font-weight: bold;
    color: #e9c279;

    &::after {
      content: "";
      position: absolute;
      left: 0;
      right: 0;
      bottom: -2rpx;
      height: 6rpx;
      background: #e9c279;
      border-radius: 3rpx 3rpx 0 0;
      z-index: 1;
    }
  }
}

.content {
  background: white;
  margin: -90rpx 0 0;
  border-radius: 20rpx;
  padding: 10rpx 30rpx;
  position: relative;
  z-index: 10;
  // box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
}

.section-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 40rpx;

  .title-text {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
  }
}

.real-price-wrapper {
  position: relative;
  align-items: center;
  height: 60rpx;

  .label {
    display: flex;
  }
}

.real-price-label {
  font-size: 28rpx;
  margin-right: 6rpx;
  color: #e9c279;
}

.real-price-value {
  font-size: 32rpx;
  color: #e9c279;
  font-weight: bold;
  margin: 0 2rpx;
}

.real-price-unit {
  font-size: 28rpx;
  margin-left: 2rpx;
  color: #e9c279;
}

.rights-tag-ellipse {
  position: absolute;
  display: inline-block;
  left: 70%;
  top: -100rpx;
  transform: translateX(-50%);
  background: #e9c279;
  color: white;
  padding: 0 14rpx;
  border-radius: 12rpx;
  font-size: 22rpx;
  z-index: 2;
  white-space: nowrap;
  text-align: center;
  min-width: 90rpx;
  min-height: 40rpx;
  line-height: 40rpx;
  position: relative;
}

.ellipse-arrow {
  position: absolute;
  left: 40%;
  bottom: -14rpx;
  transform: translateX(-50%) rotate(20deg);
  width: 0;
  height: 0;
  border-left: 16rpx solid transparent;
  border-right: 16rpx solid transparent;
  border-top: 28rpx solid #e9c279;
  z-index: -1;
}

.weight-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20rpx;
  margin-bottom: 40rpx;
}

.weight-item {
  background: #f8f8f8;
  border: 2rpx solid #f0f0f0;
  border-radius: 12rpx;
  padding: 30rpx;
  text-align: center;
  font-size: 32rpx;
  color: #666;
  cursor: pointer;
  transition: all 0.3s;

  &.active {
    background: #e9c279;
    color: white;
    border-color: #e9c279;
  }

  &:hover {
    border-color: #e9c279;
  }
}

.custom-input-section {
  margin-bottom: 40rpx;
}

.input-container {
  display: flex;
  align-items: center;
  background: #f8f8f8;
  border-radius: 12rpx;
  padding: 20rpx;

  .custom-input {
    flex: 1;
    background: transparent;
    border: none;
    font-size: 32rpx;
    color: #333;

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

  .input-unit {
    font-size: 32rpx;
    color: #666;
    margin-left: 20rpx;
  }
}

.total-amount {
  text-align: center;
  font-size: 36rpx;
  color: #e9c279;
  font-weight: bold;
  margin-bottom: 60rpx;
}

.agreement-section {
  margin-bottom: 40rpx;
  display: flex;
  align-items: center;
}

.agreement-text {
  font-size: 28rpx;
  color: #666;
}

.agreement-link {
  color: #e9c279;
  text-decoration: underline;
  margin-left: 4rpx;
}

.submit-section {
  margin-top: 40rpx;
}

.submit-btn {
  width: 100%;
  background: #e9c279;
  color: white;
  border: none;
  border-radius: 12rpx;
  padding: 30rpx;
  font-size: 32rpx;
  font-weight: bold;

  &.disabled {
    background: #ccc;
    cursor: not-allowed;
  }
}

// 弹窗样式
.popup-content {
  width: 80vw;
  padding: 40rpx;
  height: 80vh;
  // display: flex;
  // flex-direction: column;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;

  .popup-title {
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
  }

  .popup-close {
    font-size: 48rpx;
    color: #666;
    cursor: pointer;
  }
}

.popup-body {
  height: 62vh;
  // flex: 1;
  // min-height: 0; // 关键，防止flex塌陷

  .agreement-content {
    font-size: 28rpx;
    line-height: 1.6;
    color: #666;
  }
}

.popup-footer {
  margin-top: 30rpx;

  .popup-btn {
    width: 100%;
    background: #e9c279;
    color: white;
    border: none;
    border-radius: 12rpx;
    padding: 10rpx 30rpx;
    font-size: 32rpx;
  }
}
</style>
