<template>
  <view class="asset-page asset-theme wallet-page">
    <asset-page-shell title="钱包地址" />

    <view class="asset-scroll wallet-scroll">
      <view class="wallet-panel">
        <view class="wallet-panel__head">
          <view class="wallet-panel__title">
            <view class="wallet-panel__title-icon">
              <view class="wallet-panel__title-tab"></view>
              <view class="wallet-panel__title-body"></view>
            </view>
            <text class="wallet-panel__title-text">当前钱包地址</text>
          </view>
          <text class="wallet-panel__subtitle">我在交易所的钱包地址</text>
        </view>

        <view v-if="currentWallet" class="wallet-panel__content">
         <view class="wallet-panel__address-box">{{
            currentWallet.address
          }}</view>
          <view class="wallet-panel__footer">
            <text class="wallet-panel__name">{{ currentWallet.name }}</text>
            <text
              class="wallet-panel__copy"
              @click="copy(currentWallet.address)"
              >复制地址</text
            >
          </view>
        </view>

        <view v-else class="wallet-panel__new">
          <view class="wallet-input">
            <input
              v-model="draftAddress"
              class="wallet-input__field asset-number-font"
              type="text"
              placeholder="粘贴新钱包地址"
              placeholder-style="color:rgba(154, 163, 197, 0.82);font-size:28rpx;"
            />
            <!-- <text class="wallet-input__paste" @click="paste">粘贴</text> -->
          </view>
          <text class="wallet-panel__helper">
            钱包地址请在【海南农综】APP中获取
          </text>
        </view>
      </view>

      <view
        class="wallet-actions"
        :class="{ 'wallet-actions--compact': !currentWallet }"
      >
        <view
          class="wallet-button wallet-button--primary"
          @click="currentWallet ? openEditDialog() : saveCurrentAddress()"
        >
          {{ currentWallet ? "修改钱包地址" : savingAddress ? "保存中..." : "保存" }}
        </view>
        <view
          class="wallet-button wallet-button--secondary"
          @click="handleBack"
        >
          返回
        </view>
      </view>
      <view v-if="!currentWallet" class="get-walleck">
        <view class="title">获取操作流程</view>
        <view
          v-for="(imageUrl, index) in walletFlowImages"
          :key="imageUrl"
          class="img"
          @click="previewWalletFlow(index)"
        >
          <image :src="imageUrl" mode="widthFix"></image>
        </view>
      </view>

      <text
        v-if="currentWallet"
        class="wallet-delete"
        @click="openDeleteDialog"
      >
        删除地址
      </text>
    </view>

    <wallet-action-popup
      :visible="deleteDialogVisible"
      title="删除钱包"
      message="确认删除钱包地址"
      :address="currentWallet ? currentWallet.address : ''"
      confirm-text="确认"
      cancel-text="取消"
      @cancel="deleteDialogVisible = false"
      @confirm="remove"
    />

    <asset-confirm-popup
      class="wallet-edit-popup"
      :visible="editDialogVisible"
      title="修改钱包"
      :confirm-text="editingAddress ? '确认中...' : '确认'"
      cancel-text="取消"
      :close-on-mask="false"
      @cancel="closeEditDialog"
      @confirm="confirmEditAddress"
    >
      <view class="wallet-edit-dialog">
        <text class="wallet-edit-dialog__message">确认修改钱包新地址</text>
        <view class="wallet-edit-dialog__box">
          <input
            v-model="editAddress"
            class="wallet-edit-dialog__input asset-number-font"
            type="text"
            placeholder="粘贴新钱包地址"
            placeholder-style="color:rgba(165,175,208,0.82);font-size:28rpx;"
          />
         <!-- <text class="wallet-edit-dialog__paste" @click.stop="pasteEditAddress">
            粘贴
          </text> -->
        </view>
        <text class="wallet-edit-dialog__desc asset-number-font">
          *请仔细核对钱包地址，以免造成财产损失
        </text>
      </view>
    </asset-confirm-popup>

    <view v-if="successTipVisible" class="wallet-success-tip">
      <image
        class="wallet-success-tip__icon"
        src="https://imgs.agrimedia.cn/bm-bmt/success.png"
        mode="aspectFit"
      ></image>
      <text class="wallet-success-tip__text">{{ successTipText }}</text>
    </view>
  </view>
</template>

<script>
import AssetPageShell from "../../components/asset-page-shell.vue";
import AssetConfirmPopup from "../../components/asset-confirm-popup.vue";
import WalletActionPopup from "../../components/wallet-action-popup.vue";
import {
  fetchWalletDetail,
  deleteAssetWallet,
  saveAssetWallet,
} from "../../api/assets";

export default {
  components: {
    AssetPageShell,
    AssetConfirmPopup,
    WalletActionPopup,
  },
  data() {
    return {
      wallets: [],
      draftAddress: "",
      savingAddress: false,
      editDialogVisible: false,
      editAddress: "",
      editingAddress: false,
      deleteDialogVisible: false,
      successTipVisible: false,
      successTipText: "",
      successTipTimer: null,
      walletFlowImages: [
        "https://imgs.agrimedia.cn/bm-bmt/wallect-1.png",
        "https://imgs.agrimedia.cn/bm-bmt/wallect-2.png",
        "https://imgs.agrimedia.cn/bm-bmt/wallect-3.png",
        "https://imgs.agrimedia.cn/bm-bmt/wallect-4-s.png",
        "https://imgs.agrimedia.cn/bm-bmt/wallect-5.png",
      ],
    };
  },
  onLoad() {
    this.loadPage();
  },
  onShow() {
    this.loadPage();
  },
  onUnload() {
    this.clearSuccessTipTimer();
  },
  computed: {
    currentWallet() {
      for (let i = 0; i < this.wallets.length; i += 1) {
        if (this.wallets[i].isDefault) {
          return this.wallets[i];
        }
      }

      return this.wallets[0] || null;
    },
    trimmedDraftAddress() {
      return String(this.draftAddress || "").trim();
    },
    trimmedEditAddress() {
      return String(this.editAddress || "").trim();
    },
  },
  methods: {
    async loadPage() {
      try {
        const result = await fetchWalletDetail();
        this.wallets = result.wallets || [];
        if (this.currentWallet) {
          this.draftAddress = this.currentWallet.address || "";
        }
      } catch (error) {
        uni.showToast({
          title: error.message || "钱包加载失败",
          icon: "none",
        });
      }
    },
    handleBack() {
      if (getCurrentPages().length > 1) {
        uni.navigateBack();
        return;
      }

      uni.reLaunch({
        url: "/pages/index/index",
      });
    },
    copy(address) {
      uni.setClipboardData({
        data: address,
        success() {
          uni.showToast({
            title: "已复制",
            icon: "none",
          });
        },
      });
    },
    paste() {
      const that = this;
      uni.getClipboardData({
        success(result) {
          that.draftAddress = result.data || "";
        },
      });
    },
    previewWalletFlow(index) {
      const urls = Array.isArray(this.walletFlowImages)
        ? this.walletFlowImages
        : [];
      if (!urls.length) {
        return;
      }

      const currentIndex = Number(index) || 0;
      const currentUrl = urls[currentIndex] || urls[0];

      uni.previewImage({
        urls: urls,
        current: currentUrl,
      });
    },
    openEditDialog() {
      if (!this.currentWallet) {
        return;
      }

      this.editAddress = "";
      this.editDialogVisible = true;
    },
    closeEditDialog() {
      this.editDialogVisible = false;
      this.editAddress = "";
      this.editingAddress = false;
    },
    pasteEditAddress() {
      uni.getClipboardData({
        success: (result) => {
          const clipboardValue =
            result && result.data !== undefined && result.data !== null
              ? String(result.data)
              : "";
          this.editAddress = clipboardValue;
        },
        fail: () => {
          uni.showToast({
            title: "粘贴失败，请重试",
            icon: "none",
          });
        },
      });
    },
    clearSuccessTipTimer() {
      if (this.successTipTimer) {
        clearTimeout(this.successTipTimer);
        this.successTipTimer = null;
      }
    },
    showSuccessTip(text) {
      const message = String(text || "").trim();
      if (!message) {
        return;
      }

      this.clearSuccessTipTimer();
      this.successTipText = message;
      this.successTipVisible = true;

      this.successTipTimer = setTimeout(() => {
        this.successTipVisible = false;
        this.successTipTimer = null;
      }, 1400);
    },
    async confirmEditAddress() {
      if (!this.currentWallet || this.editingAddress) {
        return;
      }

      if (!this.trimmedEditAddress) {
        uni.showToast({
          title: "请先粘贴钱包地址",
          icon: "none",
        });
        return;
      }

      this.editingAddress = true;

      try {
        await saveAssetWallet(
          {
            id: this.currentWallet.id,
            name: this.currentWallet.name,
            address: this.trimmedEditAddress,
          },
          {
            showLoading: true,
            loadingText: "保存中",
          },
        );

        this.closeEditDialog();
        this.showSuccessTip("修改成功!");

        this.loadPage();
      } catch (error) {
        uni.showToast({
          title: error.message || "保存失败",
          icon: "none",
        });
      } finally {
        this.editingAddress = false;
      }
    },
    async saveCurrentAddress() {
      if (this.currentWallet || this.savingAddress) {
        return;
      }

      if (!this.trimmedDraftAddress) {
        uni.showToast({
          title: "请先粘贴钱包地址",
          icon: "none",
        });
        return;
      }

      this.savingAddress = true;

      try {
        await saveAssetWallet(
          {
            address: this.trimmedDraftAddress,
          },
          {
            showLoading: true,
            loadingText: "保存中",
          },
        );

        this.showSuccessTip("保存成功!");

        this.loadPage();
      } catch (error) {
        uni.showToast({
          title: error.message || "保存失败",
          icon: "none",
        });
      } finally {
        this.savingAddress = false;
      }
    },
    openDeleteDialog() {
      if (!this.currentWallet) {
        return;
      }

      this.deleteDialogVisible = true;
    },
    async remove() {
      if (!this.currentWallet) {
        return;
      }

      try {
        await deleteAssetWallet(this.currentWallet.id);
        this.deleteDialogVisible = false;
		this.draftAddress = '';
        this.showSuccessTip("删除成功!");
        this.loadPage();
      } catch (error) {
        uni.showToast({
          title: error.message || "删除失败",
          icon: "none",
        });
      }
    },
  },
};
</script>

<style lang="scss" scoped>
@import "../../styles/tokens.scss";
@import "../../styles/common.scss";

.wallet-page {
  min-height: 100vh;
  background: #191e32;
}

.wallet-scroll {
  min-height: calc(100vh - env(safe-area-inset-top) - 104rpx);
  display: flex;
  flex-direction: column;
  padding: 10rpx 22rpx calc(env(safe-area-inset-bottom) + 36rpx);
}

.wallet-panel {
  padding: 22rpx 20rpx 24rpx;
  border-radius: 12rpx;
  background: #242944;
  box-shadow: 0 12rpx 24rpx rgba(8, 13, 30, 0.12);
}

.wallet-panel__head {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12rpx;
}

.wallet-panel__title {
  display: flex;
  align-items: center;
  min-width: 0;
}

.wallet-panel__title-icon {
  position: relative;
  width: 34rpx;
  height: 28rpx;
  margin-right: 10rpx;
  flex-shrink: 0;
}

.wallet-panel__title-tab {
  position: absolute;
  left: 5rpx;
  top: -4rpx;
  width: 16rpx;
  height: 10rpx;
  border-radius: 6rpx 6rpx 0 0;
  background: #b48eff;
}

.wallet-panel__title-body {
  position: absolute;
  left: 0;
  bottom: 0;
  width: 34rpx;
  height: 22rpx;
  border-radius: 6rpx;
  background: linear-gradient(135deg, #b48eff 0%, #8c6ef0 100%);
}

.wallet-panel__title-text {
  font-size: 28rpx;
  font-weight: 700;
  color: #ffffff;
}

.wallet-panel__subtitle {
  margin-left: 16rpx;
  max-width: 280rpx;
  font-size: 26rpx;
  line-height: 1.4;
  text-align: right;
  flex-shrink: 0;
  color: rgba(174, 183, 211, 0.88);
}

.wallet-panel__content,
.wallet-panel__new {
  margin-top: 18rpx;
}

.wallet-panel__address-box {
  padding: 30rpx 24rpx;
  border-radius: 8rpx;
  background: rgba(53, 62, 94, 1);
  font-size: 26rpx;
  line-height: 1.6;
  word-break: break-all;
  color: #ffffff;
}

.wallet-panel__footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 20rpx;
}

.wallet-panel__name {
  font-size: 26rpx;
  color: rgba(196, 205, 231, 0.88);
}

.wallet-panel__copy {
  font-size: 26rpx;
  font-weight: 700;
  color: #1fb7f9;
}

.wallet-input {
  display: flex;
  align-items: center;
  padding: 0 20rpx;
  height: 94rpx;
  border-radius: 10rpx;
  background: #191e32;
}

.wallet-input__field {
  flex: 1;
  min-width: 0;
  height: 94rpx;
  font-size: 28rpx;
  color: #ffffff;
}

.wallet-input__paste {
  margin-left: 18rpx;
  font-size: 28rpx;
  font-weight: 500;
  color: #1fb7f9;
}

.wallet-panel__helper {
  display: block;
  margin-top: 18rpx;
  font-size: 26rpx;
  line-height: 1.6;
  color: rgba(174, 183, 211, 0.82);
}

.wallet-actions {
  display: flex;
  gap: 20rpx;
  margin-top: 180rpx;
  padding: 0 10rpx;
}

.wallet-actions--compact {
  margin-top: 48rpx;
}

.get-walleck {
  background: #20263e;
  margin-top: 48rpx;
  padding: 30rpx 28rpx;
  border-radius: 8rpx;
}

.get-walleck .title {
  font-weight: 500;
  font-size: 28rpx;
  color: #ffffff;
  text-align: center;
  margin-bottom: 28rpx;
}

.get-walleck .img {
  margin: 12rpx auto 0;
  text-align: center;
  border-radius: 12rpx;
  overflow: hidden;
}

.get-walleck .img:first-of-type {
  margin-top: 0;
}

.get-walleck .img image {
  width: 100%;
  display: block;
}

.wallet-edit-dialog__message {
  display: block;
  margin-top: 4rpx;
  font-size: 30rpx;
  line-height: 1.8;
  color: #edf2ff;
}

.wallet-edit-dialog__box {
  display: flex;
  align-items: center;
  margin-top: 26rpx;
  padding: 0 20rpx;
  min-height: 112rpx;
  border-radius: 12rpx;
  background: rgba(70, 80, 122, 0.78);
}

.wallet-edit-dialog__input {
  flex: 1;
  min-width: 0;
  min-height: 112rpx;
  font-size: 28rpx;
  line-height: 1.6;
  color: #ffffff;
}

.wallet-edit-dialog__paste {
  margin-left: 18rpx;
  font-size: 28rpx;
  font-weight: 500;
  color: #1fb7f9;
}

.wallet-edit-dialog__desc {
  display: block;
  margin-top: 26rpx;
  font-size: 22rpx;
  line-height: 1.8;
  color: #F77E57;
}

.wallet-edit-popup ::v-deep .popup-panel {
  max-width: 640rpx;
  padding: 30rpx 30rpx 32rpx;
  border-radius: 12rpx;
  background: #20263e;
}

.wallet-edit-popup ::v-deep .popup-panel__close-image {
  width: 38rpx;
  height: 38rpx;
}

.wallet-edit-popup ::v-deep .popup-panel__footer {
  margin-top: 34rpx;
  gap: 16rpx;
}

.wallet-edit-popup ::v-deep .popup-panel__btn {
  height: 82rpx;
  border-radius: 12rpx;
  font-size: 32rpx;
}

.wallet-edit-popup ::v-deep .popup-panel__btn--ghost {
  border: 1px solid rgba(157, 173, 221, 0.64);
  background: rgba(67, 77, 118, 0.92);
}

.wallet-button {
  display: flex;
  align-items: center;
  justify-content: center;
  flex: 1;
  height: 90rpx;
  border-radius: 999rpx;
  font-size: 32rpx;
  font-weight: 700;
}

.wallet-button--primary {
  background: linear-gradient(135deg, #22c2ff 0%, #159de6 100%);
  box-shadow: 0 16rpx 30rpx rgba(31, 169, 243, 0.2);
  color: #ffffff;
}

.wallet-button--secondary {
  border: 1px solid rgba(154, 164, 200, 0.64);
  background: rgba(67, 77, 118, 0.92);
  color: #ffffff;
}

.wallet-delete {
  margin-top: auto;
  padding: 140rpx 0 10rpx;
  text-align: center;
  font-size: 28rpx;
  font-weight: 700;
  color: #1fb7f9;
}

.wallet-success-tip {
  position: fixed;
  top: calc(env(safe-area-inset-top) + 132rpx);
  left: 50%;
  transform: translateX(-50%);
  z-index: 99;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12rpx;
  min-height: 76rpx;
  padding: 14rpx 28rpx;
  border-radius: 999rpx;
  background: rgba(17, 23, 43, 0.96);
  box-shadow: 0 10rpx 30rpx rgba(8, 13, 30, 0.38);
}

.wallet-success-tip__icon {
  width: 34rpx;
  height: 34rpx;
  flex-shrink: 0;
}

.wallet-success-tip__text {
  font-size: 28rpx;
  font-weight: 700;
  color: #ffffff;
  white-space: nowrap;
}
</style>
