<template>
  <view class="withdraw">
    <view class="content">
      <!-- 充值相关内容 -->
      <view style="height: auto">
        <view class="balance-box">
          <view>
            <view class="balance-title">可用余额</view>
            <view class="balance-rmb">
              <view style="display: flex; align-items: flex-end">￥</view>
              <view class="rmb">{{ userInfo?.nowMoney || 0 }}</view>
            </view>
          </view>
        </view>
        <view class="tabs">
          <view
            class="tabs-item"
            :class="[tabsIndex === item.key ? 'active' : '']"
            v-for="item in tabsList"
            :key="item.key"
            @click="tabsChange(item)"
          >
            {{ item.title }}
          </view>
        </view>
        <view class="box-list" v-if="tabsIndex === 0">
          <view class="box">
            <view class="title-tip">自主打款</view>
            <view class="item">
              <view class="targe">转</view>
              <view class="address">
                <view>用户名：深圳市水贝珠宝贸易有限公司</view>
                <view>账&nbsp;&nbsp;&nbsp;户：1223606060@qq.com</view>
              </view>
              <view class="end">
                <view class="copy" @click="copy('账户：1223606060@qq.com')"
                  >复制</view
                >
              </view>
            </view>
          </view>
        </view>
        <view class="box-list" v-else>
          <view class="box">
            <view class="title-tip">自主打款</view>
            <view class="item">
              <view class="targe">转</view>
              <view
                class="address"
                style="display: flex; flex-wrap: wrap; height: 140rpx"
              >
                <view>用户名：深圳市水贝珠宝贸易有限公司</view>
                <view>卡号：756279419662</view>
                <view>开户行：中国银行深圳水贝支行</view>
              </view>
              <view class="end">
                <view
                  class="copy"
                  @click="
                    copy(
                      '用户名：深圳市水贝珠宝贸易有限公司,开户行：中国银行深圳水贝支行,卡号：756279419662'
                    )
                  "
                >
                  复制
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
      <view style="padding: 0 30px; background-color: #fff; padding-top: 30rpx">
        <view class="withdraw-body">
          <view class="title-tip">金额</view>
          <view class="input-money">
            <view class="rmb">
              <view style="width: 20px">￥</view>
            </view>
            <view style="width: 100%">
              <input
                placeholder="请输入充值金额（最低100元起充）"
                v-model.number="extract"
                type="digit"
                class="t-input"
                @input="onKeyInput"
              />
            </view>
          </view>
          <view class="info-money">
            <view v-if="is_lowest">
              <text class="info-money-num" style="color: #ff1e0f"
                >最低{{ lowest }}元起充，账户充值{{ extract }}元</text
              >
            </view>
          </view>
          <view v-if="tabsIndex === 0" style="margin-top: 50rpx">
            <view class="title-tip">订单号</view>
            <view class="input-order">
              <view class="rmb">
                <view style="width: 20px"></view>
              </view>
              <view style="width: 100%">
                <input
                  placeholder="请输入订单号"
                  v-model="order_no"
                  class="t-input"
                />
              </view>
            </view>
          </view>
          <view style="margin-top: 50rpx">
            <view class="title-tip">转账图片</view>
            <view style="margin-top: 20px">
              <view class="upload-box">
                <up-upload
                  :fileList="imageList"
                  uploadIcon="plus"
                  @afterRead="afterRead"
                  @delete="deletePic"
                  name="1"
                  multiple
                  :maxCount="1"
                >
                  <template #trigger>
                    <view class="upload-block">
                      <uni-icons
                        size="38"
                        color="#ccc"
                        type="plusempty"
                      ></uni-icons>
                    </view>
                  </template>
                </up-upload>
              </view>
            </view>
          </view>
          <view :class="'btn-box tx' + (is_post ? '-active' : '')">
            <view class="btn" @click="handleShowModel">提交申请</view>
          </view>
          <view class="btn-tip" v-if="tabsIndex === 0">
            提交后无需审核，0秒到账！
            <span style="color: red">(推荐)</span>
          </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="showAggre">《充值协议》</span>
            </view>
          </view>
        </view>
        <view
          v-if="tabsIndex === 0 && !appStore?.$wxConfig?.auditModeEnabled"
          class="process-guidelines"
        >
          <view v-if="tabsIndex === 0" style="margin: 30rpx 0"
            >支付宝充值流程指引</view
          >
          <up-parse
            :content="process"
            @imgtap="handlePreviewImage"
          ></up-parse>
        </view>
      </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>

    <!-- 图片预览 -->
    <!-- <image
      src="https://mp-c7c90a6c-c53b-48dd-bd94-692abc111f89.cdn.bspapp.com/2025/08/07/65570280-62375873-0.png"
    ></image> -->

    <!-- 底部占位 -->
    <view style="width: 100%; height: 100rpx"></view>
  </view>
</template>

<script setup>
import { onLoad } from "@dcloudio/uni-app";
import { ref, computed, watch } from "vue";
import { useAppStore } from "@/stores/app";
import { useImageUpload } from "@/hooks/useImageUpload";
import { rechargeAlipayAPI, rechargeBankAPI } from "@/api/functions";
import { agreementGetoneApi } from "@/api/user";
// 引入uni-app API（无需额外import，直接使用uni.xxx即可）

// 1. 初始化图片上传钩子（解构响应式数据和方法）
const { imageList, afterRead, deletePic, uploadLoading } = useImageUpload({
  pid: 12,
  model: "zfb",
});

// 2. 获取Pinia Store实例
const appStore = useAppStore();

// 3. 定义响应式数据（替代Vue2的data选项）
// 基础类型用ref，复杂类型（对象/数组）也可用ref（Vue3推荐）
const transferImg = ref([]); // 转账图片
const agreement = ref("");
const extract = ref(null); // 充值金额
const is_lowest = ref(false); // 是否低于最低充值额
const is_post = ref(false); // 提交按钮是否可用
const lowest = ref(100); // 最低充值额
const aggregate = ref(false); // 是否同意协议
const tabsIndex = ref(0); // 当前选中的标签（支付宝/银行卡）
const tabsList = ref([
  { key: 0, title: "" },
  { key: 1, title: "" },
]); // 标签列表（固定数据，也可不用ref，直接const tabsList = [...]）
const order_no = ref(null); // 订单号
const showPreview = ref(false); // 是否显示图片预览
// const ImageUrl = ref([{ id: 1, src: "/static/logo.png" }]); // 预览图片列表
const previewImageUrl = ref(""); // 预览图片地址
const userInfo = ref({}); // 用户信息（从Store获取）
// tabs切换
const tabsChange = (item) => {
  if(appStore?.$wxConfig?.auditModeEnabled) return
  tabsIndex.value = item.key;
  extract.value = null;
  order_no.value = null;
  imageList.value = [];
};
// 4. 定义方法（替代Vue2的methods选项）
// 复制文本方法
const copy = (item) => {
  uni.setClipboardData({
    data: item,
    success: () => {
      uni.showToast({
        title: "复制成功",
        icon: "success",
      });
    },
    fail: (err) => {
      uni.showToast({
        title: "复制失败",
        icon: "none",
      });
      console.error("复制失败：", err);
    },
  });
};

// 输入框输入事件
const onKeyInput = () => {
  checkMoney();
};

// 检查充值金额是否符合要求
const checkMoney = () => {
  // 处理null/undefined情况
  const currentAmount = Number(extract.value);

  if (isNaN(currentAmount)) {
    is_post.value = false;
    is_lowest.value = true;
    return;
  }

  if (currentAmount >= lowest.value) {
    is_post.value = true;
    is_lowest.value = false;
  } else {
    is_lowest.value = true;
    is_post.value = false;
  }
};

// 提交申请（模板调用但原代码未实现，补充空函数避免报错）
const handleShowModel = async () => {
  // 此处可添加提交前的校验（如是否同意协议、是否上传图片等）
  // 示例：
  if (!aggregate.value) {
    uni.showToast({
      title: "请先阅读并同意《充值协议》",
      icon: "none",
    });
    return;
  }
  if (!extract.value || extract.value < lowest.value) {
    uni.showToast({
      title: `请输入不低于${lowest.value}元的充值金额`,
      icon: "none",
    });
    return;
  }
  // 支付宝
  if (tabsIndex.value == 0) {
    const res = await rechargeAlipayAPI({
      orderNo: order_no.value,
      price: extract.value,
      rechargeImage: imageList.value.map((v) => v.info.url),
    });
    // console.log(res);
    if (res.code == 200) {
      uni.showToast({ title: "提交成功!" });
    }
  } else {
    const res = await rechargeBankAPI({
      price: extract.value,
      rechargeImage: imageList.value.map((v) => v.info.url),
    });
    if (res.code == 200) {
      uni.showToast({ title: "提交成功!" });
      setTimeout(() => {
        uni.navigateTo({
          url: "/pages/users/vault/index",
        });
      });
    }
  }

  // 银行卡
};
const singPopup = ref(null); // 需在模板中给uni-popup添加ref="singPopup"

const showAggre = () => {
  singPopup.value?.open();
};

// 显示图片预览（模板调用但原代码未实现，补充空函数避免报错）
const showImage = (url) => {
  uni.previewImage({
    current: url, // 当前显示图片的URL
    urls: [url], // 需要预览的图片URL列表
    success: () => {},
    fail: (err) => {
      console.error("预览图片失败:", err);
    },
  });
};

// 处理图片预览
const handlePreviewImage = (e) => {
  console.log("e", e);

  const { src, urls } = e.detail;
  // 使用 uni-app 自带的图片预览 API
  uni.previewImage({
    current: src, // 当前点击的图片地址
    urls: urls, // 所有图片的数组（用于左右滑动预览）
  });
};

// 获取协议
const process = ref("");
const content = ref("123");
const agreementGetoneFn = () => {
  agreementGetoneApi({ name: "recharge_text" }).then((res) => {
    process.value = res.data?.content;
  });
  agreementGetoneApi({ name: "recharge_rule" }).then((res) => {
    content.value = res.data?.content;
  });
};

// 5. 生命周期钩子（uni-app的onLoad，Vue3中直接使用）
onLoad((options) => {
  agreementGetoneFn();
  if (appStore?.$wxConfig?.auditModeEnabled) {
    console.log("执行");
  } else {
    console.log("执行", appStore?.$wxConfig?.auditModeEnabled);
    tabsList.value = [
      { key: 0, title: "支付宝" },
      { key: 1, title: "银行卡" },
    ];
  }
  console.log("页面加载参数：", options);
  // 从Pinia Store获取用户信息（注意：Store中的userInfo若为响应式，需确保已加载）
  userInfo.value = appStore.userInfo;
  console.log("当前用户信息：", userInfo.value);

  // 可选：监听Store中userInfo的变化，实时更新本地userInfo
  watch(
    () => appStore.userInfo,
    (newUserInfo) => {
      userInfo.value = newUserInfo;
    },
    { immediate: true } // 立即执行一次
  );
});

// 6. 计算属性（替代Vue2的computed选项）
// 原代码中computed为空，此处示例如何定义（按需添加）
const computedExample = computed(() => {
  // 示例：计算充值金额的格式化显示
  return extract.value ? `¥${Number(extract.value).toFixed(2)}` : "¥0.00";
});

// 7. 监听器（替代Vue2的watch选项）
// 示例：监听extract变化，自动检查金额（也可通过@input触发，二选一）
watch(
  extract,
  (newVal) => {
    checkMoney();
  },
  { immediate: true } // 初始值也触发检查
);

// 监听tabsIndex变化（按需添加）
watch(tabsIndex, (newIndex) => {
  console.log("切换到标签：", newIndex === 0 ? "支付宝" : "银行卡");
  // 切换标签时的额外逻辑（如清空订单号等）
  if (newIndex !== 0) {
    order_no.value = null;
  }
});
</script>

<style lang="scss" scoped>
page {
  height: 100%;
  background-color: #f7f7f7;
}
::v-deep .file-list-row {
  background: #ededed;
  overflow: hidden;
  border-radius: 20rpx;
}

.upload-box {
  margin-top: 40rpx;
  .upload-block {
    width: 160rpx;
    height: 160rpx;
    border: 1px solid #ccc;
    border-radius: 10rpx;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    color: #ccc;
    font-weight: 700;
    font-size: 26rpx;
  }
}
.withdraw {
  height: 100%;
  // background-color: #f7f7f7;
  background-image: $uni-bg-primary !important;
  .content {
    // background: url('https://mp-ad17e5cd-05c1-4df9-b060-556e25dac130.cdn.bspapp.com/mini/static/20250529221733.jpg');
    background-size: 100% 500rpx;
    background-position: top center;
    background-repeat: no-repeat;
    box-sizing: border-box;
    // padding: 0 30rpx;
  }
  &-body {
    background-color: #fff;
    padding: 50rpx 0;
    font-size: 14px;

    .input-money,
    .input-order {
      box-sizing: border-box;
    }

    .input-money {
      display: flex;
      align-items: center;
      border-bottom: 1px solid #eaeef1;
      margin-top: 30rpx;
      background-color: #ededed;
      padding: 20rpx;
      border-radius: 15rpx;
      width: 100%;

      .rmb {
        font-size: 38rpx;
        // text-wrap: nowrap;
        font-weight: 300;
        font-family: "Calibri";
      }
      .t-input {
        height: 1.4em;
        width: 100%;
        font-size: 26rpx;
        border: none;
        position: relative;
        left: 1%;
        outline: none;
      }
    }
    .input-order {
      display: flex;
      align-items: center;
      border-bottom: 1px solid #eaeef1;
      margin-top: 30rpx;
      background-color: #ededed;
      padding: 20rpx;
      border-radius: 15rpx;
      width: 100%;

      .t-input {
        height: 1.4em;
        font-size: 30rpx;
        border: none;
        position: relative;
        left: 0;
        outline: none;
      }
    }
    .info-money {
      margin-top: 10px;
      font-size: 12px;
      margin-bottom: 20px;
      &-num {
        color: #b2b2b2;
      }
    }
    .tx {
      button {
        color: #b2b2b2;
      }
    }
    .tx-active {
      button {
        color: #fff;
        background: #c4bba6;
      }
    }
    .aggregate {
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 10px;
      .aggre {
        font-size: 14px;
        margin-left: 10px;
        .aggre-text {
          color: #3ab0ff;
        }
      }
    }
    .choose {
      width: 16px;
      height: 16px;
    }
  }

  .box {
    display: flex;
    flex-direction: column;
    background-color: #fff;
    padding: 50rpx;
    padding-top: 50rpx;
    width: 100%;
    padding-bottom: 0;
    box-sizing: border-box;
    &-title {
      font-size: 14px;
    }
  }

  .tabs {
    display: flex;
    height: 80rpx;
    border-radius: 40rpx;
    padding: 0 20rpx;
    color: #fff;
    font-size: 38rpx;
    font-weight: 300;
    box-sizing: border-box;

    .tabs-item {
      width: 50%;
      height: 100%;
      display: flex;
      justify-content: center;
      position: relative;
      box-sizing: border-box;
    }

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

  @keyframes showTriangle {
    0% {
      opacity: 0;
      transform: translateY(-50%) scaleX(0);
    }
    100% {
      opacity: 1;
      transform: translateY(-50%) scaleX(1);
    }
  }

  .box-list {
    width: 100%;
    box-sizing: border-box;
    .title {
      font-size: 14px;
    }
  }
  .box {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    justify-content: center;
    background-color: #f7f7f7;
    border-top-left-radius: 60rpx;
    border-top-right-radius: 60rpx;
    width: 100%;
    box-sizing: border-box;
    padding: 14px;
    padding-top: 60rpx;

    .head {
      font-size: 14px;
    }
    .item {
      width: 100%;
      display: flex;
      align-items: center;
      margin-top: 30px;
      .source {
        background-color: #f7af74;
      }
      .targe {
        background-color: #cd9933;
      }
      .source,
      .targe {
        display: flex;
        justify-content: center;
        align-items: center;
        color: #fff;
        width: 35px;
        height: 35px;
        border-radius: 50%;
        margin-right: 20rpx;
      }
      .address {
        height: 100rpx;
        display: flex;
        flex-wrap: wrap;
        align-items: center;
        flex: 1;
        font-size: 26rpx;
        font-family: "微软雅黑";
        color: #000000;
      }
      .write {
        margin: 0 10px;
        font-size: 14px;
        color: #888888;
      }
      .end {
        display: flex;
        justify-content: center;
        align-items: center;
        .copy {
          color: #888888;
          border-radius: 3px;
          border: 1px solid #888888;
          font-size: 24rpx;
          padding: 6rpx 20rpx;
          margin-right: 10rpx;
        }
      }
    }
  }

  /* 图片预览样式 */
  .image-preview-mask {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.8);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 9999;

    .imgBox {
      width: 100%;
      height: 100vh;

      .preview-image {
        width: 100%;
        height: 100% !important;
      }
    }
  }

  .process-guidelines {
    color: rgb(0, 0, 0);
    font-size: 32rpx;
    margin-top: 20rpx;
    margin-bottom: 20rpx;
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    border: 1rpx solid #f5f5f5;
    border-radius: 20rpx;
    box-shadow: 0 0px 10px 6px #efefef;
    padding-bottom: 70rpx;
    box-sizing: border-box;
  }

  .title-tip {
    position: relative;
    padding-left: 20rpx;
    height: 50rpx;
    display: flex;
    align-items: center;
    font-size: 32rpx;
    font-family: "黑体";
    width: 100%;
    box-sizing: border-box;

    &::before {
      position: absolute;
      top: 50%;
      transform: translatey(-40%);
      left: 0;
      content: "";
      width: 2px;
      height: 18px;
      background-color: #daa520;
    }
  }

  .balance-box {
    height: 300rpx;
    padding-left: 60rpx;
    color: #fff;
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    width: 100%;
    box-sizing: border-box;

    .balance-title {
      width: 100%;
      font-size: 36rpx;
      font-weight: 300;
      margin-bottom: 10rpx;
      font-family: "微软雅黑";
    }

    .balance-rmb {
      width: 100%;
      display: flex;
      width: 100%;
      font-size: 38rpx;
      font-weight: 300;

      .rmb {
        font-size: 60rpx;
        font-weight: 500;
        margin-left: 10rpx;
      }
    }
  }

  .btn-box {
    height: 100rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-bottom: 40rpx;
    margin-top: 80rpx;
    width: 100%;
    box-sizing: border-box;

    .btn {
      height: 75rpx;
      width: 400rpx;
      background-color: #cd9933;
      color: #fff;
      border-radius: 50rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 30rpx;
    }
  }

  .btn-tip {
    height: 30rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-bottom: 30rpx;
    color: #808080;
    width: 100%;
    box-sizing: border-box;
  }
}

.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>
