<template>
  <view class="page">
    <view class="topBody">
      <PageHeader title="M币充值" class="PageHeader">
        <template v-slot:right>
          <DropdownMenu 
            :options="dropdownOptions" 
            @select="handleDropdownSelect"
          />
        </template>
      </PageHeader>
      <view class="reserveASeat"></view>

      <view class="myGoldCoin-box">
        <view>我的M币</view>
        <view class="myGoldCoin-box-content">
          <image src="../../static/icon/coin_m.png" mode="widthFix" />
          <text>{{ myGoldCoin }}</text>
        </view> 
      </view>
      <view class="myinfo">
        <view class="purchaseList" style="margin-top: 32rpx">
          <view
            class="item"
            :class="index == sel ? 'itemSel' : ''"
            v-for="(item, index) in list"
            @click="selTA(item, index)"
            :key="index"
          >
            <view class="num1">
              <image src="../../static/icon/coin_m.png" mode="widthFix" />
              <view class="name">{{ item.num_gmm| formatNumberToK }} </view>
            </view>
            <view class="num2">
              <view class="name">{{ $t("txt.￥") }}{{ item.money }}</view>
            </view>
          </view>
        </view>

        <view class="jinchu">
          <text>{{ $t("txt.支付方式") }}</text>
        </view>

        <view v-if="isWeChatPay" class="mingxiList" @click="selPay('wechat')">
          <view class="left">
            <image
              class="icon"
              src="../../static/me/icon_wechat.png"
              mode="widthFix"
            />
            <text style="font-size: 28rpx; margin-left: 20rpx">{{
              $t("txt.微信支付")
            }}</text>
          </view>
          <view class="right">
            <image
              class="icon"
              :src="
                payType != 'wechat'
                  ? '../../static/icon/wd_icon_gouxuan04.png'
                  : '../../static/icon/wd_icon_gouxuan05.png'
              "
             
            />
          </view>
        </view>
        <!-- <view class="line"></view> -->
        <view class="mingxiList" @click="selPay('alipay')">
          <view class="left">
            <image
              class="icon"
              src="../../static/me/icon_alipay.png"
              mode="widthFix"
            />
            <text style="font-size: 28rpx; margin-left: 20rpx">{{
              $t("txt.支付宝支付")
            }}</text>
          </view>
          <view class="right">
            <image
              class="icon"
              :src="
                payType != 'alipay'
                  ? '../../static/icon/wd_icon_gouxuan04.png'
                  : '../../static/icon/wd_icon_gouxuan05.png'
              "
               
            />
          </view>
        </view>
        <!-- <view class="line"></view> -->

      </view>

      <view class="agree">
          <view class="agree2" @click="agreeChk()">
            <image
               
              src="../../static/icon/wd_icon_gouxuan04.png"
              v-if="is_agree == 0"
            ></image>
            <image
              
              src="../../static/icon/wd_icon_gouxuan05.png"
              v-if="is_agree == 1"
            ></image>
          </view>
          <view>
            同意
            <text class="xy" @click="goPage('/pages/AboutUs/pay_xy')">
              《充值服务协议》 </text
            >，充值M币仅【萌创星球】使用，点击查看
            <text class="xy" @click="goPage('/pages/vip/record?type=coin')"> 充值记录 </text>
          </view>
        </view>
        <view class="btn_submit" :class="{'btn-loading': isSubmitting}" @click="submitData">
          <text v-if="!isSubmitting">¥{{ money }}</text>
          <text v-if="!isSubmitting">确认充值</text>
          <view v-if="isSubmitting" class="loading-spinner"></view>
        </view>
      <view class="blankHeight"></view>
    </view>

    <!-- 提示框 -->
    <DialogBox ref="DialogBox"></DialogBox>
  </view>
</template>

<script>
import DropdownMenu from '@/components/DropdownMenu.vue'
import { mapState } from 'vuex'
export default {
  components: {
    DropdownMenu
  },
  computed: {
    ...mapState('hideModule', ['isWeChatPay'])
  },
  data() {
    return {
      title: "",
      sel: 1,
      payType: "wechat",
      list: [],
      money: 0,
      tid: 0,
      linkid: "",
      is_agree: 0,
      myGoldCoin: 0,
      dropdownOptions: [
        { label: '购买记录', type: 'vipRecord' }
      ],
      isSubmitting: false,
      lastClickTime: 0
    };
  },
  onLoad() {
    // setTimeout(function() {
    // 	uni.setNavigationBarColor({
    // 		frontColor: '#ffffff',
    // 		backgroundColor: '#00000000',
    // 		animation: {
    // 			duration: 400,
    // 			timingFunc: 'easeIn'
    // 		}
    // 	})
    // }, 200);
  },
  onShow() {
    this.loadData();
    let that = this;
  },
  methods: {
    onBack() {},
    goPage(page) {
      uni.navigateTo({
        url: page,
      });
    },
    selTA(item, se) {
      this.tid = item.id;
      this.sel = se;
      if (this.list != null && this.list != undefined) {
        this.money = this.list[se]["money"];
      }
    },
    selPay(se) {
      this.payType = se; 
    },
    chkSel() {
      if (this.sel == 1) {
        this.sel = 0;
      } else {
        this.sel = 1;
      }
    },
    submitData() {
      const now = Date.now();
      if (now - this.lastClickTime < 3000) {
        uni.showToast({
          title: "请勿频繁点击",
          icon: "none"
        });
        return;
      }
      this.lastClickTime = now;
      
      if (this.isSubmitting) return;
      if (this.is_agree == 0) {
        uni.showToast({
          title: "请确认并选择协议",
          icon: "none",
        });
        return;
      }
      this.isSubmitting = true;
      let that = this;
      uni.request({
        url: this.$apiHost + "/Order/submit",
        data: {
          uuid: getApp().globalData.uuid,
          product_id: this.tid,
          type: "buyM",
          payType: this.payType,
        },
        header: {
          "content-type": "application/json",
        },
        success: (res) => {
          console.log("res-pay", res.data);
          if (res.data.success == "yes") {
            this.linkid = res.data.linkid;

            // 微信支付逻辑
            if (this.payType === "wechat") {
              uni.requestPayment({
                provider: "wxpay",
                orderInfo: {
                  appid: res.data.wepay.appid,
                  partnerid: res.data.wepay.partnerid,
                  prepayid: res.data.wepay.prepayid,
                  package: "Sign=WXPay",
                  noncestr: res.data.wepay.noncestr,
                  timestamp: res.data.wepay.timestamp,
                  sign: res.data.wepay.sign
                },
                success(res) {
                  console.log("微信支付成功:", res);
                  setTimeout(function () {
                    that.showPayCall();
                  }, 1000);
                },
                fail(e) {
                  console.log("微信支付失败:", e);
                  uni.showToast({
                    title: "支付失败，请重试",
                    icon: "none"
                  });
                }
              });
            } 
            // 支付宝支付逻辑
            else if (this.payType === "alipay") {
              uni.requestPayment({
                provider: "alipay",
                orderInfo: res.data.ali_pay, // 直接使用后端返回的支付宝支付参数
                success(res) {
                  console.log("支付宝支付成功:", res);
                  setTimeout(function () {
                    that.showPayCall();
                  }, 1000);
                },
                fail(e) {
                  console.log("支付宝支付失败:", e);
                  uni.showToast({
                    title: "支付失败，请重试",
                    icon: "none"
                  });
                }
              });
            }
          } else {
            uni.showToast({
              title: "创建订单失败，请联系客服",
              icon: "none",
            });
          }
        },
        fail: (err) => {
          console.log("请求失败:", err);
          uni.showToast({
            title: "网络错误，请重试",
            icon: "none"
          });
        },
        complete: () => {
          that.isSubmitting = false;
        }
      });
    },
    showPayCall() {
      let that = this;
      this.$refs["DialogBox"]
        .confirm({
          title: "提示",
          content: "我已经支付完成",
          DialogType: "inquiry",
          btn1: "否",
          btn2: "是",
          animation: 0,
        })
        .then((res) => {
          uni.request({
            url: this.$apiHost + "/Order/getstatus",
            data: {
              uuid: getApp().globalData.uuid,
              linkid: that.linkid,
            },
            header: {
              "content-type": "application/json",
            },
            success: (res) => {
              if (res.data.success == "yes") {
                uni.showToast({
                  title: "充值成功",
                  icon: "none",
                });
              } else {
                uni.showToast({
                  title: "还未检测到充值状态，请稍后再试",
                  icon: "none",
                });
                setTimeout(function () {
                  that.showPayCall();
                }, 1000);
              }
            },
            complete: (com) => {},
          });
        });
    },
    loadData() {
      // 获取M币数量
      uni.request({
        url: this.$apiHost + '/My/getnum',
        method: 'GET',
        header: {
          'content-type': 'application/json',
          'sign': getApp().globalData.headerSign
        },
        data: {
          uuid: getApp().globalData.uuid
        },
        success: (res) => {
          console.log("获取用户M币数量：", res.data);
          if (res.data && res.data.num_gmm) {
            this.myGoldCoin = res.data.num_gmm;
          }
        }
      });

      // 获取充值列表
      uni.request({
        url: this.$apiHost + "/User/getCzList",
        data: {
          uuid: getApp().globalData.uuid,
        },
        header: {
          "content-type": "application/json",
        },
        success: (res) => {
          console.log("res", res.data);
          this.num = res.data.num;
          if (res.data.list != null && res.data.list != undefined) {
            this.list = res.data.list;
            this.tid = this.list[1]["id"];
            this.sel = 1;
            this.money = this.list[1]["money"];
          }
        },
      });
    },
    handleDropdownSelect(item) {
      switch (item.type) {
        case "vipRecord":
          uni.navigateTo({
            url: "/pages/vip/record?type=coin",
          });
          break;
      }
    },
    agreeChk() {
      if (this.is_agree == 0) {
        this.is_agree = 1;
      } else {
        this.is_agree = 0;
      }
    },
  },
};
</script>

<style scoped lang="scss">
@import "M_purchase.scss";
.agree {
  width: 90%;
  margin: 0 auto;
  color: #666666;
  font-size: 24rpx; 
  display: flex;
  align-items: center;
  text-align: left;
  line-height: 32rpx;
 position: absolute;
    bottom: 215rpx;
    left: 50%;
    transform: translateX(-50%);
  .agree2 {
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
    align-items: center;
    padding-right: 8rpx;
    flex-shrink: 0; 
    padding-bottom: 34rpx;
  }

  .xy {
    color: #0084ff;
    display: inline;
  }

  image {
    width: 32rpx;
    height: 32rpx;
  }
}

.btn_submit {
  width: 626rpx;
  height: 88rpx;
  background: linear-gradient(to left, #1f1f1f  , #444444  );
  border-radius: 76rpx;
  margin: 0 auto;
  margin-top: 70rpx;
  color: #acf934;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32rpx;
  line-height: 0;
  position: relative;
  overflow: hidden;
  transition: all 0.3s ease;
  position: absolute;
    bottom: 100rpx;
    left: 50%;
    transform: translateX(-50%);
  &.btn-loading {
    opacity: 0.7;
    pointer-events: none;
  }
  
  .loading-spinner {
    width: 40rpx;
    height: 40rpx;
    border: 4rpx solid rgba(255, 255, 255, 0.3);
    border-radius: 50%;
    border-top-color: #fff;
    animation: spin 1s linear infinite;
  }

  text { 
    display: inline-block;
    margin-right: 10rpx;
  }
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}
</style>
