<template>
  <view class="sell-materials-page">
    <!-- 导航栏（若需添加导航可在此处补充，如uni-nav-bar） -->
    <!-- <view class="sell-postend-banner"></view> -->
    <view class="page-content">
      <!-- 标签栏 -->
      <view class="tabs-container">
        <view
          class="tabs-item"
          :class="{ active: activeTabId === item.id }"
          v-for="item in tabList"
          :key="item.id"
          @click="handleTabChange(item)"
        >
          {{ item.name }}
        </view>
      </view>

      <!-- 约价回收（activeTabId=1） -->
      <view class="recycle-container" v-show="activeTabId === 1">
        <!-- 金料类型选择 -->
        <view class="gold-category-list">
          <view
            class="gold-category-item"
            v-for="item in goldCategoryList"
            :key="item.key"
            :class="{ active: activeGoldCategoryKey === item.key }"
            @click="handleGoldCategoryChange(item)"
          >
            {{ item.title }}
          </view>
        </view>

        <!-- 卖料信息表单 -->
        <view class="recycle-info-card">
          <view class="price-info">
            {{ goldName
            }}{{ `${!appStore.$wxConfig?.auditModeEnabled ? "回收" : ""}` }}价格
            <text class="current-price">{{ realprice?.toFixed(2) || 0 }}</text>
            元/g
            <view class="equity-tag"
              >权益 +{{ benefitPrice?.toFixed(2) || 0 }}</view
            >
          </view>

          <!-- 克重输入（动态校验提示） -->
          <view class="weight-input-container">
            <view class="weight-input">
              <input
                type="text"
                placeholder="请输入克重"
                v-model="weight"
                @input="handleWeightInput"
              />
            </view>
            <!-- 动态错误提示 -->
            <view class="weight-tip" v-if="!isWeightValid">
              {{ weightTipText }}
            </view>
          </view>

          <!-- 金额信息（动态计算） -->
          <view class="amount-info-group">
            <view class="amount-info-item">
              <view class="info-label">{{
                `预计${!appStore.$wxConfig?.auditModeEnabled ? "回收" : ""}金额`
              }}</view>
              <view class="info-value"
                >¥{{ recylePrice?.toFixed(2) || 0 }}</view
              >
            </view>
            <view class="amount-info-item">
              <view class="info-label">定金比例</view>
              <view class="info-value">{{ currentDepositPerGram }}元/g</view>
            </view>
            <view class="amount-info-item">
              <view class="info-label">预付定金</view>
              <view class="info-value"
                >¥{{ advanceDeposit?.toFixed(2) || 0 }}</view
              >
              <!-- 余额不足警告：动态判断 -->
              <view
                class="balance-warning small"
                v-if="appStore?.isLogin && !isBalanceEnough"
              >
                余额不足，需充值{{ isNeedchargePrice?.toFixed(2) || 0 }}元
              </view>
            </view>
          </view>
        </view>

        <!-- 余额支付信息（动态判断余额不足） -->
        <view class="balance-pay-section">
          <view class="balance-info">
            <image
              class="balance-icon"
              src="https://my-go-easy-im.oss-cn-shenzhen.aliyuncs.com/goeasy-im-%E6%B0%B4%E8%B4%9D%E5%95%86%E5%9F%8E/xz1_20251008142738_748_6.png"
              mode="widthFix"
            ></image>
            <view class="balance-detail">
              <view class="balance-title">余额支付</view>
              <view class="balance-content">
                <view class="balance-amount">
                  当前余额:
                  <text class="amount-num">{{
                    appStore.userInfo?.nowMoney || 0
                  }}</text>
                </view>
                <view
                  class="balance-awrning"
                  v-if="appStore?.isLogin && !isBalanceEnough"
                >
                  余额不足
                </view>
              </view>
            </view>
          </view>
          <!-- <view
            class="recharge-btn"
            @click="jumpToSBei"
            v-if="!isBalanceEnough && !wxConfig?.auditModeEnabled"
          >
            前往充值
          </view> -->
        </view>

        <!-- 确认按钮（禁用逻辑：克重不合法或余额不足） -->
        <view class="btn-box" @click="handleConfirmSell">
          <!-- <view
            class="confirm-btn"
            @click="handleConfirmSell"
            :class="{ disabled: !isWeightValid || !isBalanceEnough }"
            :disabled="!isWeightValid || !isBalanceEnough"
          >
          
          </view> -->
          <image class="confirm-btn" src="/static/images/sb_btn.png"></image>
          <view class="confirm-btn-text">确认卖料</view>
        </view>

        <!-- 规则说明（若有配置则显示） -->
        <view class="rule-desc" v-if="setting?.recycleText">
          <rich-text :nodes="setting?.recycleText"></rich-text>
        </view>
      </view>

      <!-- 余料出售（activeTabId=2） -->
      <view class="gold-container" v-show="activeTabId === 2">
        <!-- 金料类型选择 -->
        <view class="gold-category-list">
          <view
            class="gold-category-item"
            v-for="item in goldRecyleCategoryList"
            :key="item.key"
            :class="{ active: activeGoldCategoryKey === item.key }"
            @click="handleGoldCategoryChange(item, true)"
          >
            {{ item.title }}
          </view>
        </view>

        <view class="recycle-info-card">
          <view class="price-info">
            {{ goldName }}
            <text class="current-price">{{ realprice?.toFixed(2) || 0 }}</text>
            元/g
            <view class="equity-tag"
              >权益 +{{ benefitPrice?.toFixed(2) || 0 }}</view
            >
          </view>

          <!-- 克重输入（余料专属校验） -->
          <view class="weight-input-container">
            <view class="weight-input">
              <input
                type="text"
                placeholder="请输入克重"
                v-model="rmbExtract"
                @input="rmbOnKeyInput"
                @keypress="(e) => !/[0-9.]/.test(e.key) && e.preventDefault()"
              />
            </view>
            <!-- 动态提示 -->
            <view class="weight-tip" v-if="rmbIsLowest">
              {{ goldName }}最低{{ currentMinWeight }}g起出售，且最多两位小数
            </view>
            <view class="weight-tip" v-if="rmbIsOut">
              输入克重超过可出售克重，当前可售{{
                currentAvailableWeight?.toFixed(2) || 0
              }}g
            </view>
          </view>

          <!-- 金额信息（动态计算） -->
          <view class="amount-info-group">
            <view class="amount-info-item">
              <view class="info-label">预计金额</view>
              <view class="info-value"
                >¥{{ rmbNeedPrice?.toFixed(2) || 0 }}</view
              >
            </view>
            <view class="amount-info-item">
              <view class="info-label">当前可售克重</view>
              <view class="info-value"
                >{{ currentAvailableWeight?.toFixed(2) || 0 }}g</view
              >
            </view>
          </view>
        </view>

        <!-- 余料信息（动态显示） -->
        <view class="balance-pay-section">
          <view class="balance-info">
            <image
              class="balance-icon"
              src="https://my-go-easy-im.oss-cn-shenzhen.aliyuncs.com/goeasy-im-%E6%B0%B4%E8%B4%9D%E5%95%86%E5%9F%8E/xz1_20251008142738_748_6.png"
              mode="widthFix"
            ></image>
            <view class="balance-detail">
              <view class="balance-title">余料</view>
              <view class="balance-content">
                <view class="balance-amount">
                  当前余料:
                  <text class="amount-num"
                    >{{ currentAvailableWeight?.toFixed(2) || 0 }}g</text
                  >
                </view>
                <view class="balance-warning" v-if="rmbIsOut">余料不足</view>
              </view>
            </view>
          </view>
        </view>

        <!-- 协议确认 -->
        <view class="agreement-section">
          <view class="aggregate" @click="rmbAggregate = !rmbAggregate">
            <image
              class="choose"
              :src="
                rmbAggregate
                  ? '/static/recycle/choose.png'
                  : '/static/recycle/nochoose.png'
              "
              mode="scaleToFill"
              style="width: 30rpx; height: 30rpx"
            ></image>
            <view class="aggre">
              阅读并同意
              <span class="aggre-text" @click="rmbShowAggre"
                >《余料出售协议》</span
              >
            </view>
          </view>
        </view>

        <!-- 确认按钮（禁用逻辑：未同意协议/克重不合法） -->
        <view class="btn-box" @click="rmbHandleConfirmSell()">
          <!-- <view
            class="confirm-btn"
            @click="rmbHandleConfirmSell()"
            :class="{ disabled: !rmbAggregate || !rmbIsPost }"
            :disabled="!rmbAggregate || !rmbIsPost"
          >
            确认出售
            
          </view> -->
          <image class="confirm-btn" src="/static/images/sb_btn.png"></image>
          <view class="confirm-btn-text">确认出售</view>
        </view>

        <!-- 出售协议弹窗 -->
        <uni-popup
          ref="rmbSingPopupRef"
          type="bottom"
          borderRadius="10px 10px 0 0"
          maskBackgroundColor="rgba(0,0,0,0.5)"
        >
          <view class="signContent">
            <scroll-view scrollY class="scroll" style="height: 500rpx">
              <up-parse :content="rmbAgreement"></up-parse>
            </scroll-view>
            <view
              class="comfireBtn footer"
              @click="
                rmbAggregate = true;
                rmbSingPopupRef.close();
              "
            >
              我已详细知悉
            </view>
          </view>
        </uni-popup>
      </view>
    </view>
    <!-- 约价回收规则 -->
    <view class="up-content" v-if="activeTabId === 1">
      <up-parse :content="recyleContent"></up-parse>
    </view>
    <!-- 页面内 容结束 -->
    <PayPop ref="paypopRef" :pwdlength="6" @pwd_e="handlerPwd"></PayPop>
  </view>
</template>

<script setup>
import { ref, computed, watch } from "vue";
import PayPop from "../../../../components/pay-pop/pay-pop.vue";
import { onShow, onLoad } from "@dcloudio/uni-app";
import { getUserInfo, userPayPasswordConfirmAPI } from "@/api/user";
import { useAppStore } from "@/stores/app";
import useRealGoldPrice from "@/hooks/useRealGoldPrice";
import { useStoreRights } from "@/stores/rights";
import { exchangeGoldAPI, recycleCreateAPI } from "@/api/functions";
import { agreementGetoneApi } from "@/api/user";
import { getMiniProgramData } from "@/api/api";

// 1. 全局状态与工具
const appStore = useAppStore();
const rightsStore = useStoreRights();
const paypopRef = ref(null);
const {
  realGoldRecyclePrice,
  realKGoldRecyclePrice,
  realPtRecyclePrice,
  realAgRecyclePrice,
} = useRealGoldPrice({});

// 2. 页面基础响应式数据
const activeTabId = ref(1);
const tabList = ref([]);
// 约价回收金料分类（含K金）
const goldCategoryList = ref([
  { key: "au", title: "黄金", metalType: 1 },
  { key: "kau", title: "K金", metalType: 4 },
  { key: "pt", title: "铂金", metalType: 2 },
  { key: "ag", title: "白银", metalType: 3 },
]);
// 余料出售金料分类（无K金）
const goldRecyleCategoryList = ref([
  { key: "au", title: "黄金", metalType: 1 },
  { key: "pt", title: "铂金", metalType: 2 },
  { key: "ag", title: "白银", metalType: 3 },
]);
const activeGoldCategoryKey = ref("au");
const goldName = ref("黄金");
const setting = ref(appStore.setting || {}); // 全局配置（如回收规则）
const wxConfig = ref(appStore.$wxConfig || {});

// 3. 约价回收相关响应式数据
const weight = ref("");
const isWeightValid = ref(true);
const weightTipText = ref("");
const metalRecyleType = ref(1); // 金料类型（提交订单用）

// 4. 余料出售相关响应式数据
const rmbExtract = ref("");
const rmbIsOut = ref(false); // 超过可售克重
const rmbIsLowest = ref(false); // 低于最小克重
const rmbIsPost = ref(false); // 输入合法
const rmbNeedPrice = ref(0); // 预计出售金额
const rmbAggregate = ref(false); // 同意协议
const recyleContent = ref(""); // 约价回收规则
const rmbAgreement = ref(""); // 余料出售协议
const rmbSingPopupRef = ref(null); // 协议弹窗ref

// 5. 金料定金映射（核心规则）
const GOLD_DEPOSIT_MAP = ref({
  au: {
    depositPerGram: 30,
    minimumWeight: 5,
    minirecycleWeight: 0.01,
    svipDiscountEnabled: false,
  },
  kau: {
    depositPerGram: 30,
    minimumWeight: 5,
    minirecycleWeight: 1,
    svipDiscountEnabled: false,
  },
  pt: {
    depositPerGram: 30,
    minimumWeight: 5,
    minirecycleWeight: 0.01,
    svipDiscountEnabled: false,
  },
  ag: {
    depositPerGram: 1,
    minimumWeight: 10,
    minirecycleWeight: 0.01,
    svipDiscountEnabled: false,
  },
});
// 17. 生命周期：页面显示时同步数据
onShow(() => {
  getAgreementContent();
  appStore.isLogin && updateUserInfo();
  appStore.isLogin && updateWxSettingInfo();
});

onLoad(() => {
  // setGoldDeposit();
  if (!appStore.$wxConfig?.auditModeEnabled) {
    tabList.value = [
      { id: 1, name: "约价回收" },
      { id: 2, name: "余料出售" },
    ];
  } else {
    tabList.value = [
      // { id: 1, name: "金价咨询" },
      // { id: 2, name: "余料出售" },
    ];
  }
});

// 6. 计算属性（精简冗余逻辑）
// 每克定金金额
const currentDepositPerGram = computed(
  () =>
    GOLD_DEPOSIT_MAP.value[activeGoldCategoryKey.value]?.depositPerGram || 40
);
// 最小起收克重（统一1g）
const currentMinWeight = computed(() => {
  const glodInfo = GOLD_DEPOSIT_MAP.value[activeGoldCategoryKey.value];
  if (activeTabId.value === 1) return glodInfo.minimumWeight;
  else return glodInfo.minirecycleWeight || 0.01;
});
// 当前金料回收价（约价/余料通用）
const realprice = computed(() => {
  switch (activeGoldCategoryKey.value) {
    case "au":
      return vipRealGoldRecyclePrice.value;
    case "kau":
      return viprealKGoldRecyclePrice.value;
    case "pt":
      return viprealPtRecyclePrice.value;
    case "ag":
      return viprealAgRecyclePrice.value;
    default:
      return 0;
  }
});

// 权益金额（会员额外加成）
const benefitPrice = computed(() => {
  const soldBenefit = Number(rightsStore.userBenefits?.sold || 0);
  return appStore.userInfo?.svip ? soldBenefit + 0.3 : soldBenefit;
});
// 约价回收：预计回收金额
const recylePrice = computed(() => Number(weight.value) * realprice.value || 0);
// 约价回收：预付定金
const advanceDeposit = computed(
  () => Number(weight.value) * currentDepositPerGram.value || 0
);
// 约价回收：余额是否充足
const isBalanceEnough = computed(() => {
  const userBalance = Number(appStore.userInfo?.nowMoney) || 0;
  return userBalance >= (advanceDeposit.value).toFixed(2);
});
// 约价回收：需充值金额
const isNeedchargePrice = computed(() => {
  return advanceDeposit.value - Number(appStore.userInfo?.nowMoney) || 0;
});
// 余料出售：当前可售克重（直接从用户信息读取，移除冗余的preciousMetal）
const currentAvailableWeight = computed(() => {
  const balanceKeyMap = { au: "goldBalance", pt: "ptBalance", ag: "agBalance" };
  return (
    Number(appStore.userInfo[balanceKeyMap[activeGoldCategoryKey.value]]) || 0
  );
});
// 黄金调整价
const adjustGoldprice = computed(() => {
  const res = rightsStore.userBenefits.nobleMeta?.find(
    (gold) => gold.name == "黄金"
  );
  return res;
});
// K金调整价
const adjustKprice = computed(() => {
  const res = rightsStore.userBenefits.nobleMeta?.find(
    (gold) => gold.name == "K金"
  );
  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;
});

// 7. 会员权益价计算（复用逻辑）
const vipRealGoldRecyclePrice = computed(() => {
  const base = Number(realGoldRecyclePrice.value || 0);
  const benefit = Number(rightsStore.userBenefits?.sold || 0);
  const adjustBuy = Number(adjustGoldprice.value?.buyPriceAdjust || 0);
  const svipDiscount = appStore.userInfo?.svip ? 0.3 : 0;
  // console.log("融通金价 ===========>", base);
  // console.log("等级权益 ===========>", benefit);
  // console.log("调整价 ===========>", adjustBuy);
  // console.log("svip权益 ===========>", svipDiscount);

  return base - adjustBuy + benefit + svipDiscount;
});
const viprealKGoldRecyclePrice = computed(() => {
  const base = Number(realKGoldRecyclePrice.value || 0);
  const benefit = Number(rightsStore.userBenefits?.sold || 0);
  const adjustBuy = Number(adjustKprice.value?.buyPriceAdjust || 0);
  const svipDiscount = appStore.userInfo?.svip ? 0.3 : 0;

  return base - adjustBuy + benefit + svipDiscount;
});
const viprealPtRecyclePrice = computed(() => {
  const base = Number(realPtRecyclePrice.value || 0);
  const benefit = Number(rightsStore.userBenefits?.sold || 0);
  const adjustBuy = Number(adjustPtprice.value?.buyPriceAdjust || 0);
  const svipDiscount = appStore.userInfo?.svip ? 0.3 : 0;

  return base - adjustBuy + benefit + svipDiscount;
});
const viprealAgRecyclePrice = computed(() => {
  const base = Number(realAgRecyclePrice.value || 0);
  const benefit = Number(rightsStore.userBenefits?.sold || 0);
  const adjustBuy = Number(adjustAgprice.value?.buyPriceAdjust || 0);
  const svipDiscount = appStore.userInfo?.svip ? 0.3 : 0;

  return base - adjustBuy + benefit + svipDiscount;
});

// 8. 约价回收克重校验
const handleWeightInput = () => {
  const input = weight.value.trim();
  const weightNum = Number(input);
  const min = currentMinWeight.value;

  // 重置状态
  isWeightValid.value = true;
  weightTipText.value = "";

  if (!input) return;
  if (isNaN(weightNum)) {
    isWeightValid.value = false;
    weightTipText.value = "请输入有效数字";
  } else if (weightNum < min) {
    isWeightValid.value = false;
    weightTipText.value = `${goldName.value}起收克重为${min}g`;
  } else if ((input.split(".")[1] || "").length > 2) {
    isWeightValid.value = false;
    weightTipText.value = `${goldName.value}最多两位小数`;
  }
};

// 9. 余料出售克重校验（移除冗余的rmbRecyclePrice，直接用realprice）
const rmbOnKeyInput = () => {
  const input = rmbExtract.value.trim();
  const extractNum = Number(input);
  const min = currentMinWeight.value;
  const max = currentAvailableWeight.value;

  // 重置状态
  rmbIsOut.value = false;
  rmbIsLowest.value = false;
  rmbIsPost.value = false;
  rmbNeedPrice.value = 0;

  if (!input || isNaN(extractNum)) return;

  if (extractNum < min) {
    rmbIsLowest.value = true;
  } else if (extractNum > max) {
    rmbIsOut.value = true;
  } else if ((input.split(".")[1] || "").length > 2) {
    return;
  } else {
    rmbIsPost.value = true;
    rmbNeedPrice.value = extractNum * realprice.value; // 直接用realprice
  }
};

// 10. 切换金料类型（移除调试log和无用注释）
const handleGoldCategoryChange = (item, isRemain = false) => {
  metalRecyleType.value = item.metalType;
  activeGoldCategoryKey.value = item.key;
  goldName.value = item.title;

  // 重置约价回收状态
  weight.value = "";
  isWeightValid.value = true;
  weightTipText.value = "";

  // 重置余料出售状态
  if (isRemain) {
    rmbExtract.value = "";
    rmbIsOut.value = false;
    rmbIsLowest.value = false;
    rmbIsPost.value = false;
    rmbNeedPrice.value = 0;
  }
};

// 11. 切换标签页
const handleTabChange = (item) => {
  activeTabId.value = item.id;
  // 重置金料类型为黄金
  handleGoldCategoryChange(
    { key: "au", title: "黄金", metalType: 1 },
    item.id === 2
  );
};

// 12. 约价回收提交
const handleConfirmSell = async () => {
  if (!weight.value.trim()) {
    uni.showToast({ title: "请输入克重", icon: "none" });
    return;
  }
  if (!isWeightValid.value) {
    uni.showToast({ title: weightTipText.value, icon: "none" });
    return;
  }
  if (!isBalanceEnough.value) {
    uni.showToast({ title: "余额不足，请先充值", icon: "none" });
    return;
  }
  paypopRef.value.Open();
};
// 判断密码是否正确
const handlerPwd = async (e) => {
  const res = await userPayPasswordConfirmAPI({ payPassword: e });

  if (!res.data) {
    return uni.showToast({
      title: "支付密码错误",
      duration: 2000,
      icon: "error",
    });
  }

  // if()
  try {
    uni.showLoading({
      title: "下单中",
    });
    console.log("金价 ===========>", realprice);
    console.log("融通金价 ===========>", realGoldRecyclePrice.value);
    console.log("等级权益 ===========>", rightsStore.userBenefits?.sold);
    console.log("调整价 ===========>", adjustGoldprice.value?.buyPriceAdjust);
    console.log("svip权益 ===========>", appStore.userInfo?.svip);

    const res = await recycleCreateAPI({
      deposit:
        GOLD_DEPOSIT_MAP.value[activeGoldCategoryKey.value].depositPerGram,
      svipDiscountEnabled:
        GOLD_DEPOSIT_MAP.value[activeGoldCategoryKey.value].svipDiscountEnabled,
      estimatedWeight: weight.value,
      metalType: metalRecyleType.value,
    });
    if (!res.data.flag) {
      uni.showToast({
        title: "您还有暂未寄出的订单，请寄出后再下单",
        icon: "none",
      });
    }
    uni.hideLoading();
    // 延迟跳转确保提示可见
    setTimeout(() => {
      uni.navigateTo({
        url: `/pages/users/vault/recycle/index?order=${JSON.stringify(
          res.data
        )}`,
      });
    }, 500);
  } finally {
  }
};

// 13. 余料出售提交
const rmbHandleConfirmSell = async () => {
  if (!rmbAggregate.value) {
    uni.showToast({ title: "请阅读并同意出售协议", icon: "none" });
    return;
  }
  if (currentAvailableWeight.value < rmbExtract.value) {
    uni.showToast({ title: "余料不足", icon: "none" });
    return;
  }
  if (!rmbIsPost.value) {
    uni.showToast({ title: "请输入克重", icon: "none" });
    return;
  }
  uni.showLoading({
    title: "出售中",
  });
  const res = await exchangeGoldAPI({
    metalType: metalRecyleType.value,
    weight: rmbExtract.value,
  });

  if (res.code === 200) {
    uni.showToast({ title: "出售成功，余额已更新", icon: "none" });
    setTimeout(() => {
      uni.navigateTo({
        url: "/pages/users/vault/index",
      });
    }, 500);
    // 重置输入
    rmbExtract.value = "";
  }
  uni.hideLoading();
};

// 14. 打开协议弹窗
const rmbShowAggre = () => {
  rmbSingPopupRef.value?.open();
};

// 16. 数据同步方法
async function updateUserInfo() {
  const { data } = await getUserInfo();
  appStore.UPDATE_USERINFO(data);
}

// 16. 数据同步方法
async function updateWxSettingInfo() {
  const { data } = await getMiniProgramData();
  setGoldDeposit(data);
}

// 获取协议内容
function getAgreementContent() {
  // 约价回收规则
  agreementGetoneApi({ name: "recyle" }).then((res) => {
    recyleContent.value = res.data?.content || "";
  });
  // 余料出售协议
  agreementGetoneApi({ name: "soldGold" }).then((res) => {
    rmbAgreement.value = res.data?.content || "";
  });
}

const setGoldDeposit = (data) => {
  if (!data?.metalConfigs) return;
  const initDate = {};
  data.metalConfigs.map((item) => {
    initDate[item.metalType] = item;
  });
  GOLD_DEPOSIT_MAP.value = initDate;
};

// 18. 监听价格/克重变化，实时更新余料出售金额
watch([realprice, rmbExtract], ([newPrice, newWeight]) => {
  const priceNum = Number(newPrice) || 0;
  const weightNum = Number(newWeight) || 0;
  const min = currentMinWeight.value;
  const max = currentAvailableWeight.value;

  // 仅在输入合法时更新（避免重复计算）
  if (weightNum >= min && weightNum <= max && !isNaN(weightNum)) {
    rmbNeedPrice.value = Number((priceNum * weightNum)?.toFixed(2)) || 0;
  }
});
</script>

<style scoped lang="scss">
/* 样式保持不变，此处省略（与原代码一致） */
.sell-materials-page {
  min-height: 100vh;
  padding: 10rpx 30rpx;
  position: relative;
  background: linear-gradient(180deg, #ffe079 0%, #ffffff 50%);

  .sell-postend-banner {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 50vh;
    z-index: -1;
  }

  .page-content {
    .tabs-container {
      width: 100%;
      display: flex;
      justify-content: space-around;
      margin: 45rpx 0;
      font-size: 30rpx;

      .tabs-item {
        padding: 10rpx 0;
        color: #484848;

        &.active {
          border-bottom: 6rpx solid #f8c007;
          color: #000000;
          font-weight: bold;
        }
      }
    }

    .gold-category-list {
      display: flex;
      width: 100%;

      .gold-category-item {
        flex: 1;
        display: flex;
        justify-content: center;
        align-items: center;
        position: relative;
        font-size: 30rpx;
        color: #000000;
        &.active::after {
          position: absolute;
          bottom: -36rpx;
          left: 50%;
          transform: translateX(-50%);
          content: "";
          z-index: 100;
          border-style: solid;
          border-width: 0 23rpx 23rpx 23rpx;
          border-color: transparent transparent #ffffff transparent;
          width: 0;
          height: 0;
          transform-origin: center top;
          animation: showTriangle 0.3s ease-out forwards;
        }
      }
    }

    .recycle-info-card {
      width: 682rpx;
      background-color: #ffffff;
      box-shadow: 0rpx 3rpx 13rpx 0rpx rgba(0, 0, 0, 0.13);
      border-radius: 20rpx;
      display: flex;
      flex-direction: column;
      align-items: center;
      box-sizing: border-box;
      padding: 35rpx 40rpx;
      margin-top: 36rpx;

      .price-info {
        font-size: 28rpx;
        color: #000000;
        position: relative;
        margin-top: 20rpx;

        .equity-tag {
          position: absolute;
          top: -35rpx;
          right: 0;
          padding: 2rpx 20rpx;
          font-size: 20rpx;
          color: #000;
          background: #ffd034;
          border-radius: 10rpx;
          border-top-left-radius: 60rpx;
          border-bottom-right-radius: 60rpx;
        }

        .current-price {
          font-size: 37rpx;
          color: #f96400;
          margin: 0 10rpx;
        }
      }

      .weight-input-container {
        margin: 25rpx 0;

        .weight-input {
          width: 572rpx;
          height: 80rpx;
          background-color: #f3f3f3;
          border-radius: 10rpx;
          display: flex;
          justify-content: center;
          align-items: center;

          input {
            text-align: center;
            width: 100%;
            font-size: 26rpx;
            color: #000;
          }
        }

        .weight-tip {
          margin-top: 5rpx;
          font-size: 21rpx;
          color: red;
        }
      }

      .amount-info-group {
        width: 100%;
        margin-top: 10rpx;

        .amount-info-item {
          display: flex;
          justify-content: space-between;
          font-size: 26rpx;
          color: #000000;
          margin-bottom: 15rpx;

          .info-label {
            color: #000000;
          }

          .info-value {
            color: #000;
          }
        }
      }
    }

    .balance-pay-section {
      margin-top: 25rpx;
      width: 682rpx;
      height: 165rpx;
      background-color: #ffffff;
      box-shadow: 0rpx 3rpx 13rpx 0rpx rgba(0, 0, 0, 0.13);
      border-radius: 20rpx;
      display: flex;
      justify-content: space-between;
      align-items: center;
      box-sizing: border-box;
      padding: 20rpx 26rpx;

      .balance-info {
        display: flex;
        align-items: center;

        .balance-icon {
          width: 53rpx;
        }

        .balance-detail {
          display: flex;
          flex-direction: column;
          margin-left: 20rpx;

          .balance-title {
            font-size: 26rpx;
            color: #000000;
          }

          .balance-content {
            display: flex;
            margin-top: 6rpx;

            .balance-amount {
              font-size: 26rpx;
              color: #f96400;

              text {
                margin-left: 10rpx;
              }
            }

            .balance-warning {
              font-size: 24rpx;
              color: #7c7c7c;
              margin-left: 10rpx;
            }
          }
        }
      }

      .recharge-btn {
        width: 200rpx;
        height: 55rpx;
        position: relative;
        .recharge-btn-img {
          width: 100%;
          height: 100%;
        }
        .recharge-btn-text {
          color: #000000;
          font-size: 22rpx;
          position: absolute;
          top: 50%;
          left: 50%;
          transform: translate(-50%, -50%);
        }
      }
    }

    .btn-box {
      width: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
      position: relative;

      .confirm-btn {
        width: 292rpx;
        height: 80rpx;
        margin: 70rpx 0;
      }
      .confirm-btn-text {
        font-size: 33rpx;
        color: #000000;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
      }
    }

    .recycle-container {
      .rule-desc {
        width: 100%;
        padding: 20rpx;
        box-sizing: border-box;
      }
    }

    .gold-container {
      .quick-select-section {
        width: 682rpx;
        margin-top: 25rpx;
        background-color: #ffffff;
        box-shadow: 0rpx 3rpx 13rpx 0rpx rgba(0, 0, 0, 0.13);
        border-radius: 20rpx;
        padding: 20rpx;
        box-sizing: border-box;

        .quick-select-title {
          font-size: 26rpx;
          color: #000000;
          margin-bottom: 20rpx;
        }

        .quick-select-grid {
          display: flex;
          flex-wrap: wrap;
          justify-content: center;
          gap: 20rpx;

          .quick-select-item {
            border: 2rpx solid #c9c9c9;
            width: calc(33% - 20rpx);
            height: 120rpx;
            background-color: #efefef;
            border-radius: 10rpx;
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 32rpx;
            color: #bbbbbb;
            transition: all 0.2s ease;
            box-sizing: border-box;

            &.active {
              color: #cc9933;
              border: 2rpx solid #cf9a31;
              background: #f8f4e9;
            }
          }
        }
      }

      .agreement-section {
        width: 682rpx;
        margin-top: 25rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        .aggregate {
          display: flex;
          align-items: center;

          .choose {
            width: 30rpx;
            height: 30rpx;
            margin-right: 10rpx;
          }

          .aggre {
            font-size: 24rpx;
            color: #666666;

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

.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);
  }
}

@keyframes showTriangle {
  0% {
    transform: translateX(-50%) scale(0);
  }
  100% {
    transform: translateX(-50%) scale(1);
  }
}
</style>
