<template>
  <view class="withdraw">
    <view class="recharge-header">
      <view class="title">账户余额</view>
      <view class="price">
        <view class="fh">¥</view>
        <view class="price-fh">{{
          formatNumber(appStore?.userInfo?.nowMoney) || 0
        }}</view>
      </view>
    </view>
    <view class="tabs">
      <view
        v-for="item in tabsList"
        :key="item.key"
        class="tabs-item"
        :class="[tabsIndex === item.key ? 'active' : '']"
        @click="tabsChange(item)"
      >
        {{ item.title }}
      </view>
    </view>
    <view class="contanier">
      <view class="contaniner-top">
        <view class="box-title">克重</view>
        <view class="price-box">
          <view class="price">
            实时金价
            <span class="tit">{{ realprice.toFixed(2) }}</span>
          </view>
          <view class="equity">权益 -{{ rightsStore.userBenefits.buy || 0 }}</view>
        </view>
      </view>
      <view class="input-box">
        <input
          type="text"
          placeholder="请输入克重"
          v-model.number="weight"
          @input="inputHandle"
        />
        <view class="g">g</view>
      </view>
      <view class="buy-price">
        <view class="buy-txt">买料价格</view>
        <view class="buy-num">{{ buyGoldPrice }}</view>
        <view class="t"> 元 </view>
      </view>

      <view class="btn-box" @click="submitHandle">
        <view class="btn">确认</view>
      </view>
      <view class="aggregate" @click="aggregate = !aggregate">
        <image
          class="choose"
          :src="
            aggregate
              ? '/static/recycle/choose.png'
              : '/static/recycle/nochoose.png'
          "
          mode="scaleToFill"
        ></image>
        <view class="aggre">
          阅读并同意
          <span class="aggre-text" @click.stop="showAggre">《买金协议》</span>
        </view>
      </view>
      <view class="white"></view>
    </view>
    <uni-popup
      ref="singPopup"
      type="bottom"
      borderRadius="10px 10px 0 0"
      maskBackgroundColor="rgba(0,0,0,0)"
    >
      <view class="signContent">
        <scroll-view scrollY class="scroll">
          <up-parse :content="content"></up-parse>
        </scroll-view>
        <view
          class="comfireBtn footer"
          @click="
            aggregate = true;
            $refs.singPopup.close();
          "
        >
          我已详细知悉
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup>
import { ref, computed, watch, onMounted } from "vue";
import { useAppStore } from "@/stores/app";
import useRealGoldPrice from "@/hooks/useRealGoldPrice";
import { rechargeGoldAPI } from "@/api/functions";
import { agreementGetoneApi } from "@/api/user";
const appStore = useAppStore();

// 响应式数据
const type = ref("余额");
const weight = ref("");
const buyGoldPrice = ref(0);

const aggregate = ref(false);
const content = ref("");
const tabsIndex = ref(1);

const selectedGender = ref("gold");

const tabsList = ref([
  { key: 1, label: "gold", title: "黄金" },
  { key: 2, label: "platinum", title: "铂金" },
  { key: 3, label: "silver", title: "白银" },
]);

// 实时价格处理
const {
  realGoldprice, // 黄金实时销售价（基础）
  realPtprice, // 铂金实时销售价（基础）
  realAgprice, // 白银实时销售价（基础）
} = useRealGoldPrice({});
import { useStoreRights } from "@/stores/rights";
const rightsStore = useStoreRights();
// 黄金调整价
const adjustGoldprice = computed(() => {
  const res = rightsStore.userBenefits.nobleMeta.find(
    (gold) => gold.name == "黄金"
  );
  return res;
});

// 铂金调整价
const adjustPtprice = computed(() => {
  const res = rightsStore.userBenefits.nobleMeta.find(
    (gold) => gold.name == "铂金"
  );
  return res;
});
// 白银调整价
const adjustAgprice = computed(() => {
  const res = rightsStore.userBenefits.nobleMeta.find(
    (gold) => gold.name == "白银"
  );
  return res;
});
const viprealGoldprice = computed(
  () =>
    Number(realGoldprice.value) -
    Number(rightsStore.userBenefits.buy) +
    Number(adjustGoldprice.value.sellPriceAdjust)
);
const viprealPtprice = computed(
  () =>
    Number(realPtprice.value) -
    Number(rightsStore.userBenefits.buy) +
    Number(adjustPtprice.value.sellPriceAdjust)
);
const viprealAgprice = computed(
  () =>
    Number(realAgprice.value) -
    Number(rightsStore.userBenefits.buy) +
    Number(adjustAgprice.value.sellPriceAdjust)
);
const realprice = computed(() => {
  if (tabsIndex.value == 1) {
    return viprealGoldprice.value;
  }
  if (tabsIndex.value == 2) {
    return viprealPtprice.value;
  }
  if (tabsIndex.value == 3) {
    return viprealAgprice.value;
  }
});

// 监听器
watch(realprice, (newData) => {
  buyGoldPrice.value = (weight.value * realprice.value).toFixed(2);
});
// 获取协议
function agreementGetoneFn() {
  // 资产说明
  agreementGetoneApi({ name: "buyGold" }).then((res) => {
    content.value = res.data?.content;
  });
}
// 生命周期钩子 - 替代onLoad
onMounted(() => {
  // 页面加载时执行的逻辑]
  agreementGetoneFn();
});
const inputHandle = () => {
  //   buyGoldPrice.value = vk.myfn.accMulDecimal(this.weight, this.realprice, 2);
  buyGoldPrice.value = (weight.value * realprice.value).toFixed(2);
};

// 提交
const submitHandle = async () => {
  if (checkInfo()) {
    uni.showLoading({
      title: "买料中",
    });
    const res = await rechargeGoldAPI({
      metalType: tabsIndex.value,
      weight: weight.value,
    });
    // console.log(res);
    if (res.code == 200) {
      uni.showToast({ title: "买料成功" });
      setTimeout(() => {
        uni.navigateTo({
          url: "/pages/users/vault/index",
        });
      }, 1500);
    }
    uni.hideLoading();
  }
};
const formatNumber = (num) => {
  if (isNaN(num)) return "0.00";
  const parts = num.toString().split(".");
  parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  if (parts.length > 1) {
    return parts[0] + "." + parts[1].padEnd(2, "0").slice(0, 2);
  }
  return parts[0] + ".00";
};

const checkInfo = () => {
  if (!weight.value) {
    uni.showToast({
      title: "请输入克重",
      duration: 1000,
      icon: "none",
    });
    return false;
  }
  if (!aggregate.value) {
    uni.showToast({
      title: "请阅读并同意协议",
      duration: 1000,
      icon: "none",
    });
    return false;
  }
  return true;
};
// 假设$refs.singPopup在模板中存在
const singPopup = ref(null);
const showAggre = () => {
  singPopup.value.open();
};

const tabsChange = (item) => {
  tabsIndex.value = item.key;
  weight.value = "";
  buyGoldPrice.value = 0;
};

const toDecimalP2 = (arg) => {};
</script>

<style lang="scss" scoped>
.withdraw {
  width: 750rpx;
  height: 100%;
  // background-image: linear-gradient(180deg, #b7ad94 0%, #fcfcfc 100%);
  background: $uni-bg-primary !important;
  display: flex;
  flex-direction: column;
  // align-items: center;
  .recharge-header {
    margin-left: 103rpx;
    margin-bottom: 50rpx;
    padding-top: 80rpx;

    .title {
      font-size: 29rpx;
      color: #ffffff;
    }
    .price {
      font-size: 56rpx;
      color: #ffffff;
      margin-top: 15rpx;
      display: flex;
      // height: ;
      align-items: flex-end;

      .fh {
        font-size: 36rpx;
        // color: #cc9933;
        margin-bottom: 8rpx;
      }
      .price-fh {
        margin-left: 15rpx;
      }
    }
  }
  .tabs {
    display: flex;
    height: 80rpx;
    border-radius: 40rpx;
    padding: 0 20rpx;
    color: #fff;
    font-size: 32rpx;
    font-weight: 300;
    // margin-bottom: 10rpx;

    .tabs-item {
      width: 50%;
      height: 100%;
      display: flex;
      justify-content: center;
      // align-items:;
      position: relative;
    }

    .active::after {
      position: absolute;
      bottom: -10rpx;
      left: 50%;
      transform: translateX(-50%);
      content: "";
      z-index: 100;
      border-style: solid;
      border-width: 0 25rpx 25rpx 25rpx;
      border-color: transparent transparent #ffffff transparent;
      width: 0;
      height: 0;
      transform-origin: center top;
      animation: showTriangle 0.3s ease-out forwards;
    }
  }

  .contanier {
    box-sizing: border-box;
    padding: 70rpx 70rpx;
    background-color: #ffffff;
    border-radius: 40rpx;

    .contaniner-top {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .price-box {
        // flex: 3;
        display: flex;
        align-items: center;
        position: relative;

        .price {
          font-size: 31rpx;
          color: #000000;

          .tit {
            color: #d8a235;
            font-size: 36rpx;
            margin-left: 10rpx;
          }
        }

        .equity {
          position: absolute;
          top: -35rpx;
          right: 0;
          padding: 2rpx 12rpx;
          font-size: 16rpx;
          color: #fff;
          background: #cd9933;
          // border-radius: 10rpx;
          border-top-left-radius: 30rpx;
          border-bottom-right-radius: 30rpx;

          &::after {
            position: absolute;
            bottom: -15rpx;
            left: 50%;
            width: 0;
            height: 0;
            z-index: 0;
            transform: translateX(-50%);
            content: "";
            // background: red;
            border-style: solid;
            border-width: 0 10px 10px 10px;
            border-color: transparent transparent transparent #cd9933;
          }
        }
      }
    }
    .input-box {
      width: 610rpx;
      height: 89rpx;
      background-color: #ededed;
      border-radius: 10rpx;
      padding: 0 30rpx;
      box-sizing: border-box;
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin: 20rpx 0;
      font-size: 25rpx;
      color: #999999;

      input {
        color: #000000;
        width: 99%;
      }
      .g {
        font-size: 32rpx;
        color: #cc9933;
      }
    }
    .buy-price {
      display: flex;
      justify-content: center;
      font-size: 25rpx;
      color: #000000;
      align-items: center;
      .buy-num {
        color: #cc9933;
        font-size: 28rpx;
        margin: 0 5rpx;
      }
    }
    .payment-method {
      margin-top: 120rpx;
      .method-box {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin: 50rpx 0;
        .box-left {
          display: flex;
          justify-content: center;
          image {
            height: 48rpx;
          }
          text {
            margin-left: 15rpx;
          }
        }
      }
    }
    .btn-box {
      display: flex;
      justify-content: center;
      width: 100%;
      margin-top: 200rpx;
      .btn {
        width: 300rpx;
        height: 71rpx;
        background-color: #cc9933;
        border-radius: 34rpx;
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 33rpx;
        color: #ffffff;
      }
    }
    .aggregate {
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 10px;

      .aggre {
        font-size: 14px;
        margin-left: 10px;

        .aggre-text {
          color: #cc9933;
        }
      }

      .choose {
        width: 16px;
        height: 16px;
      }
    }
    .white {
      height: 100rpx;
      background-color: #ffffff;
    }
    .box-title {
      height: 50rpx;
      padding-left: 19rpx;
      font-size: 31rpx;
      color: #000000;
      position: relative;
      display: flex;
      align-items: center;

      &::after {
        position: absolute;
        bottom: -10rpx;
        left: 5rpx;
        top: 23%;
        transform: translateX(-50%);
        content: "";
        background-color: #cc9933;
        width: 4rpx;
        height: 28rpx;
      }
    }
  }
  .signContent {
    background-color: #f8f8f8;
    padding: 20px;
    box-sizing: border-box;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    border-radius: 20px 20px 0 0;

    .scroll {
      background-color: #fff;
      padding: 4px;
      height: 300px;
      overflow-y: hidden;
      border: 1px solid #dfdfdf;
    }

    .footer {
      margin-top: 10px;
      color: #fff;
      padding: 4px 20px;
      border-radius: 20px;
      background: linear-gradient(to right, #8ed187, #5dd665);
    }
  }
}
</style>
