import JiaZai from "../../Script/JiaZai";
import MapConroler from "../../Script/Map";
import Utils from "../../Script/module/Pay/Utils";
import List from "../../Script/module/RankList/List";
import NumberToImage from "../../Script/NumberToImage";
import SceneManager from "../../Script/SceneManager";
import { MiniGameSdk } from "../../Script/Sdk/MiniGameSdk";

const { ccclass, property } = cc._decorator;

@ccclass
export default class NewClass extends cc.Component {
   //商店界面
   @property(cc.Node)
   shop: cc.Node = null;
   //商品列表
   @property(cc.Node)
   itemList: cc.Node = null;

   //金币数量
   @property(cc.Node)
   coin: cc.Node = null;
   //体力信息
   @property(cc.Node)
   Stamina: cc.Node = null;
   //月卡信息
   @property(cc.Node)
   monthCardTime: cc.Node = null;

   @property(cc.SpriteAtlas)
   ui: cc.SpriteAtlas = null;

   btn_Touch: boolean = true;
   private onShowListener: () => void;
   private scheduleCallback: Function = null;
   private currentCoin: number = 0;
   private coinAnimTime: number = 0;
   private coinAnimDuration: number = 1.5; // 1.5秒
   private coinStart: number = 0;
   private coinEnd: number = 0;
   private coinAnimating: boolean = false;
   //飞金币动画
   @property(cc.Node)
   coinAnim: cc.Node = null;
   private buy: boolean = false;

   private iosPrice: number = 0;
   private iosProductId: string = "";
   private iosCount: number = 1;
   scheduleCallback3: any;
   scheduleCallback2: Function;
   sceneValue: string = "";
   reward: boolean = false;
   private monthCard: boolean = false;
   doubleInfo: null;


   onLoad() {
      this.btn_Touch = true;
      this.monthCard = false;
      // 检测微信小游戏切到后台

   }
   start() {
      this.btn_Touch = true;

   }

   init(data) {
      this.doubleInfo = data;
      cc.fx.GameConfig.GM_INFO.shopDouble = data;
      this.openShop();
      let top = this.node.getChildByName("Top");
      top.getChildByName("tx").opacity = 0;
      top.getChildByName("icon").opacity = 0;
      if (cc.fx.GameConfig.GM_INFO.useravatarIcon.length > 10) {
         console.log("获取头像链接:", cc.fx.GameConfig.GM_INFO.useravatarIcon);
         cc.assetManager.loadRemote(cc.fx.GameConfig.GM_INFO.useravatarIcon, { ext: '.png' }, (err, texture: cc.Texture2D) => {
            if (texture) {
               top.getChildByName("icon").getChildByName("icon").getComponent(cc.Sprite).spriteFrame = new cc.SpriteFrame(texture);
            }
            top.getChildByName("icon").opacity = 255;
         })
      } else {
         top.getChildByName("icon").getChildByName("icon").getComponent(cc.Sprite).spriteFrame =
            this.ui.getSpriteFrame(cc.fx.GameConfig.GM_INFO.useravatarIcon);
         top.getChildByName("icon").opacity = 255;
      }

      top.getChildByName("tx").getComponent(cc.Sprite).spriteFrame =
         this.ui.getSpriteFrame(cc.fx.GameConfig.GM_INFO.useravaterkuang);
      top.getChildByName("tx").opacity = 255;

      let flag = cc.fx.GameTool.getSetScreenResolutionFlag();
      if (flag) {
         console.log("shop设置分辨率");
         if (this.node.getChildByName("itemcontent"))
            this.node.getChildByName("itemcontent").getChildByName("view").height = 1500;
      }
      this.onShowListener = null;
      if (cc.sys.platform === cc.sys.WECHAT_GAME || cc.sys.platform === cc.sys.BYTEDANCE_GAME) {
         // 定义监听函数
         console.log("shop添加监听");
         this.onShowListener = () => {
            console.log("回到前台,shop");
            this.onShow();
         };
         //@ts-ignore
         wx.onShow(this.onShowListener);
      }
      this.btn_Touch = true;
      var timeTemp = cc.fx.GameTool.getTimeMargin(cc.fx.GameConfig.GM_INFO.min_Time);
      // 同步显示
      // if (this.Stamina && this.Stamina.getChildByName("time")) {
      //     this.Stamina.getChildByName("time").getComponent(cc.Label).string = timeTemp;
      // }
      this.stopTimeCutDown();
      this.stopPowerTime();
      this.updatePower();
      this.setHealthInfo(true);
      this.updateIcon();
      NumberToImage.numberToImageNodes(cc.fx.GameConfig.GM_INFO.coin, 30, 15, "coin_", this.coin, true);
   }
   //打开商店界面
   openShop() {
      this.sceneValue = cc.fx.GameConfig.GM_INFO.sceneValue;
      Utils.outTradeNo = null;
      cc.fx.GameConfig.GM_INFO.sceneValue = "Shop";
      this.initCoin();
      // 商品数据数组

      NumberToImage.numberToImageNodes(cc.fx.GameConfig.GM_INFO.coin, 30, 15, "coin_", this.coin, true);
      this.updateIcon();
   }

   initCoin() {
      const products = [
         { product_id: "gold_1", price: 600, coin: 1200, title: "3x2六档金币" },
         { product_id: "gold_1", price: 600, coin: 1200, title: "3x2六档金币" },
         { product_id: "gold_2", price: 3600, coin: 8000, title: "" },
         { product_id: "gold_3", price: 6800, coin: 16000, title: "" },
         { product_id: "gold_4", price: 12800, coin: 32000, title: "" },
         { product_id: "gold_5", price: 32800, coin: 100000, title: "" },
         { product_id: "gold_6", price: 64800, coin: 240000, title: "" },
      ];
      if (this.itemList) {
         for (let i = 2; i <= 7 && i < this.itemList.children.length; i++) {
            const spriteComp = this.itemList.children[i].children[0].getComponent(cc.Sprite);
            const price = this.itemList.children[i].children[1];
            const title = this.itemList.children[i].children[2];
            const discount = this.itemList.children[i].children[4];
            const add = this.itemList.children[i].children[5];
            this.itemList.children[i].children[4].active = false;
            this.itemList.children[i].children[5].active = false;
            this.itemList.children[i].children[6].active = false;
            const product = products[i - 1];
            let name = "gold_" + (i - 1)
            if (this.doubleInfo) {
               console.log(name);
               console.log(this.doubleInfo[name]);
               if (this.doubleInfo[name] == false) {
                  this.itemList.children[i].children[4].active = true;
                  this.itemList.children[i].children[5].active = true;
                  this.itemList.children[i].children[6].active = true;
               }
            }

            if (spriteComp && product) {
               // TODO: 根据 product_id 或 name 设置 spriteComp.spriteFrame
            }


            if (price && product) {
               NumberToImage.numberToImageNodesShop(product.price / 100, 37, 20, "resultBlack_", price, false)
            }
            if (title && product) {
               NumberToImage.numberToImageNodes(product.coin, 40, 25, "scoin_", title, true)
            }
            if (discount && product) {
               NumberToImage.numberToImageNodesShop(product.coin, 40, 25, "new_coin_", discount, true)
               let pos = cc.v2(discount.children[0].position.x, discount.children[0].position.y);
               let number = i % 2 == 0 ? 34 : 42
               add.x = pos.x + discount.x - number; add.y = pos.y + discount.y;

            }
         }
      }

   }



   startCoinAnim(target: number) {
      if (this.coinAnimating && this.coinEnd === target) return;
      this.coinStart = this.currentCoin;
      this.coinEnd = target;
      this.coinAnimTime = 0;
      this.coinAnimating = true;
   }
   //优化
   protected update(dt: number): void {
      if (this.coin && this.coinAnimating) {
         this.coinAnimTime += dt;
         let t = this.coinAnimTime / this.coinAnimDuration;
         if (t >= 1) {
            this.currentCoin = this.coinEnd;
            this.coinAnimating = false;
            NumberToImage.numberToImageNodes(this.currentCoin, 30, 15, "coin_", this.coin, true);
         } else {
            this.currentCoin = Math.floor(this.coinStart + (this.coinEnd - this.coinStart) * t);
            NumberToImage.numberToImageNodes(this.currentCoin, 30, 15, "coin_", this.coin, true);
         }
      }
   }

   playCoinAnim(target?: number) {
      this.coinAnim.active = true;
      this.coinAnim.getComponent(sp.Skeleton).setAnimation(0, "feijinbi", false);
      // 监听动画完成事件
      this.coinAnim.getComponent(sp.Skeleton).setCompleteListener(() => {
         // 动画播放完成后销毁节点
         this.coinAnim.active = false;
      });
      this.startCoinAnim(5000);
   }
   //关闭商店界面
   closeShop(data, currentCoin) {
      if (this.sceneValue)
         cc.fx.GameConfig.GM_INFO.sceneValue = this.sceneValue;
      // 移除 wx.onShow 监听器
      if ((cc.sys.platform === cc.sys.WECHAT_GAME || cc.sys.platform === cc.sys.BYTEDANCE_GAME) && this.onShowListener) {
         console.log("shop移除onshow");
         console.log(currentCoin);
         //@ts-ignore
         wx.offShow(this.onShowListener);
      }
      Utils.outTradeNo = null;
      if (this.node && this.node.parent) {
         //销毁预制体
         if (this.node.parent.getComponent("JiaZai")) {
            this.node.parent.getComponent("JiaZai").closeShop();
         }
         else if (this.node.parent.getComponent("SceneManager")) {
            this.node.parent.getComponent("SceneManager").closeShop();
         }
      }

      // this.shop.destroy();
      if (this.reward) {
         this.reward = false;
         const winCOIN = cc.find("Canvas"); // 假设 Canvas 节点
         if (winCOIN) {
            const wincoin1 = winCOIN.getComponent(JiaZai);
            if (wincoin1) {
               if (wincoin1) {
                  wincoin1.onGames();
                  wincoin1.rewarded();
               }
            }
         }
      }
   }

   onShow() {
      console.log("从后台进入前台 onShow");
      let systemInfo = null;
      if (cc.sys.platform === cc.sys.WECHAT_GAME)
         //@ts-ignore
         systemInfo = wx.getSystemInfoSync();

      else if (cc.sys.platform === cc.sys.BYTEDANCE_GAME)
         //@ts-ignore
         systemInfo = tt.getSystemInfoSync();

      if (systemInfo.platform === 'ios') {
         if ((cc.sys.platform === cc.sys.WECHAT_GAME || cc.sys.platform === cc.sys.BYTEDANCE_GAME)) {
            console.log("从后台进入前台订单号:", cc.fx.GameConfig.GM_INFO.iosShopOrder);
            if (cc.fx.GameConfig.GM_INFO.iosShopOrder != null && cc.fx.GameConfig.GM_INFO.iosShopOrder != "") {
               console.log("有苹果订单号，开始轮训");
               const iosShopOrder = cc.fx.GameConfig.GM_INFO.iosShopOrder;
               // this.closeLoad();
               // this.openLoad();
               this.btn_Touch = true;

               Utils.getIosPayInfo(iosShopOrder,
                  (data) => {
                     console.log("商城获得轮训结果:", data);
                     const iosID = data.data?.payment_name || this.iosProductId;
                     let iosAmount = data.data?.goodsPrice || this.iosPrice;
                     iosAmount = parseInt(iosAmount);
                     if (iosID == "reborn_Gift" || iosID == "month_Card" || iosID == "starter_pack") {
                        console.log("商城检测到是月卡返回");
                        return;
                     }
                     if (data.code == 1) {
                        console.log("购买成功");
                        console.log("商品id:", iosID);
                        // const dataSuccess = {
                        //    outTradeNo: iosShopOrder,
                        //    pay_amount: iosAmount,
                        //    payment_name: iosID,
                        //    payment_num: this.iosCount,
                        //    type: "ios",
                        // }
                        // cc.fx.GameTool.shushu_Track("payment", dataSuccess);
                        let name = "购买金币道具:" + iosID;
                        MiniGameSdk.API.yinli_Pay(iosAmount, iosShopOrder, name)

                        console.log("_________正式发货", iosID);
                        MiniGameSdk.API.showToast("充值成功");
                        cc.fx.GameTool.shopBuy(iosID, false);
                        if (iosID == "unlimited_health_bundle_10" ||
                           iosID == "unlimited_health_bundle_20" ||
                           iosID == "unlimited_health_bundle_30"
                        ) {
                           this.updatePower();
                        }
                        cc.fx.GameConfig.GM_INFO.iosShopOrder = null;
                        NumberToImage.numberToImageNodes(cc.fx.GameConfig.GM_INFO.coin, 30, 15, "coin_", this.coin, true);
                        if (this.node && this.node.parent) {
                           if (this.node.parent.getComponent("JiaZai"))
                              this.node.parent.getComponent("JiaZai").updateCoin();
                           else if (this.node.parent.getComponent("SceneManager")) {
                              this.node.parent.getComponent("SceneManager").updateCoin();
                           }
                        }
                        this.closeLoad();
                        this.btn_Touch = true;
                        //console.log("充值成功获得金币");
                     }
                     else if (data.code == 0) {
                        console.log("用户自己取消充值");
                        MiniGameSdk.API.showToast("充值失败");
                        this.closeLoad();
                        this.btn_Touch = true;
                        const dataFail = {
                           outTradeNo: iosShopOrder,
                           pay_amount: iosAmount,
                           payment_name: iosID,
                           payment_num: this.iosCount,
                           type: "ios",
                           fail_reason: "用户取消充值",
                        }
                        cc.fx.GameTool.shushu_Track("payment_fail", dataFail);
                        cc.fx.GameConfig.GM_INFO.iosShopOrder = null;
                     }
                     else if (data.code == 2) {
                        this.closeLoad();
                        this.btn_Touch = true;
                        console.log("轮训超时");
                        MiniGameSdk.API.showToast("请检查网络,如充值成功，请重新登录领取", 4);
                        const dataFail = {
                           outTradeNo: iosShopOrder,
                           pay_amount: iosAmount,
                           payment_name: iosID,
                           payment_num: this.iosCount,
                           type: "ios",
                           fail_reason: "用户充值后，轮训结果超时",
                        }
                        cc.fx.GameTool.shushu_Track("payment_fail", dataFail);
                        this.openConfirmBox();
                     }
                  })
            }
            else {
               this.closeLoad();
            }
         }
      }


   }

   openLoad() {
      if (this.node) {
         this.node.getChildByName("Loading").active = true;
         this.node.getChildByName("Loading").getChildByName("load").stopAllActions();
         this.node.getChildByName("Loading").getChildByName("load").runAction(cc.rotateTo(2, 1080).repeatForever());
      }

   }

   closeLoad() {
      if (this.node)
         this.node.getChildByName("Loading").active = false;
   }

   setHealthInfo(type) {
      if (cc.fx.GameConfig.GM_INFO.hp >= cc.fx.GameConfig.GM_INFO.hp_Max && this.Stamina) {
         this.Stamina.getChildByName("man").active = true;
         this.Stamina.getChildByName("health").active = true;
         this.Stamina.getChildByName("time").active = false;
         NumberToImage.numberToImageNodes(cc.fx.GameConfig.GM_INFO.hp, 25, 15, "hp_", this.Stamina.getChildByName("health"), false);
      }
      else {
         const winCOIN = cc.find("Canvas"); // 假设 Canvas 节点
         if (winCOIN) {
            const wincoin = winCOIN.getComponent(SceneManager);
            if (wincoin) {
               if (MapConroler && MapConroler._instance) {
                  MapConroler._instance.setPropNum();
               }
               console.log("局内");
               cc.fx.GameTool.getHealth((data) => {
                  if (this.Stamina) this.Stamina.getChildByName("time").active = true;
                  if (cc.fx.GameConfig.GM_INFO.min_Time != 0) {
                     let time = cc.fx.GameTool.getTimeMargin(cc.fx.GameConfig.GM_INFO.min_Time);
                     if (this.Stamina) {
                        this.Stamina.getChildByName("time").getComponent(cc.Label).string = time;
                        let power = cc.fx.GameTool.getUserPowerTime();
                        if (!power) this.Stamina.getChildByName("time").opacity = 255;
                        else this.Stamina.getChildByName("time").opacity = 0;
                     }
                     this.stopTimeCutDown();
                     this.startTimeCutDown();
                  }
               });
            } else {
               if (this.Stamina) this.Stamina.getChildByName("time").active = true;
               if (cc.fx.GameConfig.GM_INFO.min_Time != 0) {
                  let time = cc.fx.GameTool.getTimeMargin(cc.fx.GameConfig.GM_INFO.min_Time);
                  if (this.Stamina) {
                     this.Stamina.getChildByName("time").getComponent(cc.Label).string = time;
                     let power = cc.fx.GameTool.getUserPowerTime();
                     if (!power) this.Stamina.getChildByName("time").opacity = 255;
                     else this.Stamina.getChildByName("time").opacity = 0;
                  }
                  this.stopTimeCutDown();
                  this.startTimeCutDown();
               }
            }
         }
         if (this.Stamina) {
            this.Stamina.getChildByName("man").active = false;
            this.Stamina.getChildByName("health").active = true;
            NumberToImage.numberToImageNodes(cc.fx.GameConfig.GM_INFO.hp, 25, 15, "hp_", this.Stamina.getChildByName("health"), false);
         }

      }
   }

   startTimeCutDown() {
      this.stopTimeCutDown();
      if (this.scheduleCallback3) {
         this.unschedule(this.scheduleCallback3);
      }

      this.scheduleCallback3 = function () {
         if (this.pause) return;
         if (cc.fx.GameConfig.GM_INFO.min_Time <= 0) {
            this.stopTimeCutDown();
            var timeTemp = cc.fx.GameTool.getTimeMargin(cc.fx.GameConfig.GM_INFO.min_Time);
            // 同步显示
            if (this.Stamina && this.Stamina.getChildByName("time")) {
               this.Stamina.getChildByName("time").getComponent(cc.Label).string = timeTemp;
            }
            MiniGameSdk.API.showToast("恢复一点体力");
            cc.fx.GameTool.setUserHealth(1, (data) => {
               cc.fx.GameTool.getHealth(null);
               this.setHealthInfo(true);
            }, true)
         }
         else {
            if (this.node && this.node.parent) {
               if (this.node.parent.getComponent("JiaZai")) {
               }
               else cc.fx.GameConfig.GM_INFO.min_Time -= 1;
            }
            else {
               cc.fx.GameConfig.GM_INFO.min_Time -= 1;
            }
            var timeTemp = cc.fx.GameTool.getTimeMargin(cc.fx.GameConfig.GM_INFO.min_Time);
            // 同步显示
            if (this.Stamina && this.Stamina.getChildByName("time")) {
               let power = cc.fx.GameTool.getUserPowerTime();
               if (!power) this.Stamina.getChildByName("time").opacity = 255;
               else this.Stamina.getChildByName("time").opacity = 0;
               this.Stamina.getChildByName("time").getComponent(cc.Label).string = timeTemp;
            }
         }
      }.bind(this);
      this.schedule(this.scheduleCallback3, 1);

   }

   // 停止倒计时
   stopTimeCutDown() {
      if (this.scheduleCallback3) {
         this.unschedule(this.scheduleCallback3);
         this.scheduleCallback3 = null;
      }
   }

   //点击充值购买

   buyProduct(event, customData) {
      if (!this.btn_Touch) {
         return;
      }
      this.btn_Touch = false;
      const productId = customData;
      let id = "10011";
      let price = 100;
      let count = 1;
      id = productId;
      console.log("购买商品id:", productId);
      switch (productId) {
         case "gold_1":
            price = 600;
            break;
         case "gold_2":
            price = 3600;
            break;
         case "gold_3":
            price = 6800;
            break;
         case "gold_4":
            price = 12800;
            break;
         case "gold_5":
            price = 32800;
            break;
         case "gold_6":
            price = 64800;
            break;
         case "unlimited_health_bundle_10":
            price = 1000;
            break;
         case "unlimited_health_bundle_20":
            price = 2000;
            break;
         case "unlimited_health_bundle_30":
            price = 3000;
            break;
         case "month_Card":
            price = 3000;
            break;
      }
      //console.log("获得商品id:", id, count, price);
      // 判断设备系统
      let systemType = "Android";
      try {
         //@ts-ignore
         const systemInfo = wx.getSystemInfoSync();
         if (systemInfo.platform === 'ios') {
            systemType = "ios";
         }
      } catch (e) {
         console.error('获取系统信息失败', e);
      }

      if (systemType == "ios") {
         // MiniGameSdk.API.showToast("IOS系统暂不支持支付");
         // this.btn_Touch = true;
         this.openLoad();
         this.btn_Touch = true;
         let iosPayInfo = {
            price: price,
            payment_name: productId,
            payment_count: 1,
         }
         this.iosPrice = price;
         this.iosProductId = productId;
         this.iosCount = 1;
         console.log("准备跳客服回话:");
         console.log(this.iosProductId);
         Utils.GoKEFu(iosPayInfo, (res) => {
            if (res == "success") {
               console.log("客服回话成功");
            }
            else {
               console.log("客服回话失败");
               this.closeLoad();
            }
         });
      }
      else {
         // MiniGameSdk.API.showToast("充值成功");
         // cc.fx.GameTool.shopBuy(productId, false);
         // setTimeout(() => {
         //    if (productId == "unlimited_health_bundle_10" ||
         //       productId == "unlimited_health_bundle_20" ||
         //       productId == "unlimited_health_bundle_30"
         //    ) {
         //       console.log("触发————————updatePower");
         //       this.updatePower();
         //    }
         // }, 500);

         this.openLoad();
         this.btn_Touch = true;
         //console.log("7.14_____________________", "调用充值接口");
         Utils.buyProp(id, count, price, systemType, productId, (res) => {
            //console.log("获得充值结果", res);
            if (res == null) {
               MiniGameSdk.API.showToast("充值失败");
               this.btn_Touch = true;
               const dataFail = {
                  outTradeNo: Utils.outTradeNo,
                  pay_amount: price,
                  payment_name: productId,
                  payment_num: 1,
                  type: systemType,
                  fail_reason: "网络异常,没有拉起支付",
               }
               cc.fx.GameTool.shushu_Track("payment_fail", dataFail);
               this.closeLoad();
               return;
            }
            else if (res.err) {
               MiniGameSdk.API.showToast("充值失败");
               //console.log(res);
               this.btn_Touch = true;
               let name = "支付拉起失败";
               if (res.errCode == -2) {
                  name = "用户取消充值";
               }
               const dataFail = {
                  outTradeNo: Utils.outTradeNo,
                  pay_amount: price,
                  payment_name: productId,
                  payment_num: 1,
                  type: systemType,
                  fail_reason: name,
               }
               cc.fx.GameTool.shushu_Track("payment_fail", dataFail);
               this.closeLoad();
               return;
            }
            else {
               Utils.getPayInfo((data) => {
                  // MiniGameSdk.API.showToast("充值成功");
                  console.log("7.28_______________充值成功，准备轮训", data);
                  //console.log("获得轮训结果:", data);
                  this.closeLoad();
                  if (data.data.pay_state == 1) {
                     this.btn_Touch = true;
                     MiniGameSdk.API.showToast("取消充值");
                     const dataFail2 = {
                        outTradeNo: Utils.outTradeNo,
                        pay_amount: price,
                        payment_name: productId,
                        payment_num: 1,
                        type: systemType,
                        fail_reason: "用户取消支付",
                     }
                     cc.fx.GameTool.shushu_Track("payment_fail", dataFail2);
                  }
                  else if (data.data.pay_state == 2) {
                     this.btn_Touch = true;
                     // const dataSuccess = {
                     //    outTradeNo: Utils.outTradeNo,
                     //    pay_amount: price,
                     //    payment_name: productId,
                     //    payment_num: 1,
                     //    type: systemType,
                     // }
                     // cc.fx.GameTool.shushu_Track("payment", dataSuccess);
                     let name = "购买金币道具:" + productId;
                     MiniGameSdk.API.yinli_Pay(price, Utils.outTradeNo, name);


                     console.log("7.14_______________充值成功，轮训成功，准备发货");
                     Utils.setPayInfo(
                        (res) => {
                           console.log("设置轮训结果:", res);
                           if (res.code === 1) {
                              console.log("7.14_________正式发货", Utils.outTradeNo);
                              MiniGameSdk.API.showToast("充值成功");
                              cc.fx.GameTool.shopBuy(productId, false);
                              if (productId == "unlimited_health_bundle_10" ||
                                 productId == "unlimited_health_bundle_20" ||
                                 productId == "unlimited_health_bundle_30"
                              ) {
                                 this.updatePower();
                              }
                              //console.log("充值成功获得金币");
                           }
                           else {
                              MiniGameSdk.API.showToast("网络异常，充值奖励将在登录后再次发放");
                              const dataFail4 = {
                                 outTradeNo: Utils.outTradeNo,
                                 pay_amount: price,
                                 payment_name: productId,
                                 payment_num: 1,
                                 type: systemType,
                                 fail_reason: "成功付款，但是发货时请求服务器失败，充值成功未发货",
                              }
                              cc.fx.GameTool.shushu_Track("payment_fail", dataFail4);
                           }
                           NumberToImage.numberToImageNodes(cc.fx.GameConfig.GM_INFO.coin, 30, 15, "coin_", this.coin, true);
                           if (this.node && this.node.parent) {
                              if (this.node.parent.getComponent("JiaZai"))
                                 this.node.parent.getComponent("JiaZai").updateCoin();
                              else if (this.node.parent.getComponent("SceneManager")) {
                                 this.node.parent.getComponent("SceneManager").updateCoin();
                              }
                           }
                        }, Utils.outTradeNo)
                  }
                  else {
                     NumberToImage.numberToImageNodes(cc.fx.GameConfig.GM_INFO.coin, 30, 15, "coin_", this.coin, true);
                     const dataFail3 = {
                        outTradeNo: Utils.outTradeNo,
                        pay_amount: price,
                        payment_name: productId,
                        payment_num: 1,
                        type: systemType,
                        fail_reason: "拉起支付后，付款时网络异常付款失败",
                     }
                     cc.fx.GameTool.shushu_Track("payment_fail", dataFail3);
                     this.btn_Touch = true;
                     if (this.node && this.node.parent) {
                        if (this.node.parent.getComponent("JiaZai"))
                           this.node.parent.getComponent("JiaZai").updateCoin();
                        else if (this.node.parent.getComponent("SceneManager")) {
                           this.node.parent.getComponent("SceneManager").updateCoin();
                        }
                     }
                  }
               })
            }
         });
      }

   }


   //无限体力刷新功能
   updatePower() {
      console.log("无限体力时间戳:", cc.fx.GameConfig.GM_INFO.userPowerTime);
      const winCOIN = cc.find("Canvas"); // 假设 Canvas 节点
      if (winCOIN) {
         const wincoin = winCOIN.getComponent(SceneManager);
         if (wincoin) {
            if (MapConroler && MapConroler._instance) {
               MapConroler._instance.setPropNum();
            }
            console.log("局内");
         };
      }
      if (cc.fx.GameConfig.GM_INFO.userPowerTime != 0) {
         let nowTime = Math.floor(Date.now() / 1000);
         if (cc.fx.GameConfig.GM_INFO.userPowerTime > nowTime) {
            this.stopPowerTime();
            this.startPowerTime();
            console.log("还有无限体力时间_____________", (cc.fx.GameConfig.GM_INFO.userPowerTime - nowTime));
            if (this.Stamina) {
               this.Stamina.getChildByName("skyLine").active = true;
               this.Stamina.getChildByName("time").opacity = 0;
               this.Stamina.getChildByName("man").active = false;
            }
         }
         else {
            if (this.Stamina) this.Stamina.getChildByName("skyLine").active = false;
            console.log("无限体力时间已过期");
            this.setHealthInfo(true);
         }
      }
      else {
         if (this.Stamina) this.Stamina.getChildByName("skyLine").active = false;
         this.setHealthInfo(true);
         console.log("没有无限体力时间");
      }
   }

   startPowerTime() {
      this.stopPowerTime();
      this.scheduleCallback2 = function () {
         let nowTime = Math.floor(Date.now() / 1000);
         if (cc.fx.GameConfig.GM_INFO.userPowerTime < nowTime) {
            if (this.Stamina) this.Stamina.getChildByName("skyLine").active = false;
            this.stopPowerTime();
            this.setHealthInfo(true);
            return;
         }
         else {
            if (this.Stamina) {
               this.Stamina.getChildByName("skyLine").active = true;
               this.Stamina.getChildByName("time").opacity = 0;
               this.Stamina.getChildByName("man").active = false;
            }
         }
         let time = cc.fx.GameConfig.GM_INFO.userPowerTime - nowTime;
         if (time <= 0) {
            time = 0;
            if (this.Stamina) this.Stamina.getChildByName("skyLine").active = false;
            this.stopPowerTime();
            this.setHealthInfo(true);
            var timeTemp = cc.fx.GameTool.getTimeMargin2(time);
            // 同步显示
            if (this.Stamina && this.Stamina.getChildByName("skyLine").getChildByName("skyTime")) {
               this.Stamina.getChildByName("skyLine").getChildByName("skyTime").getComponent(cc.Label).string = timeTemp;
            }
         }
         else {
            var timeTemp = cc.fx.GameTool.getTimeMargin2(time);
            // 同步显示
            if (this.Stamina && this.Stamina.getChildByName("skyLine").getChildByName("skyTime")) {
               this.Stamina.getChildByName("skyLine").getChildByName("skyTime").getComponent(cc.Label).string = timeTemp;
            }
         }
      }.bind(this);
      this.schedule(this.scheduleCallback2, 1);
   }

   stopPowerTime() {
      cc.fx.GameTool.getUserPowerTime();
      if (this.scheduleCallback2) {
         this.unschedule(this.scheduleCallback2);
         this.scheduleCallback2 = null;
      }
   }
   openmonthCard() {
      const winCOIN = cc.find("Canvas"); // 假设 Canvas 节点
      if (winCOIN) {
         const wincoin = winCOIN.getComponent(SceneManager);
         if (wincoin) {
            wincoin.openMonthlyCard("yiconBtn_level");
            console.log("局内")
         };
         const wincoin1 = winCOIN.getComponent(JiaZai);
         if (wincoin1) {
            if (wincoin1) {
               wincoin1.openMonthlyCard(null, "yiconBtn");
               this.reward = true;
               console.log("局外")
            }
         }
      }
      this.monthCard = true;
      this.updateIcon()
   }
   //更新图标
   updateIcon() {
      let isExpired = cc.fx.GameTool.checkExpiration();
      if (isExpired) {
         this.monthCardTime.active = true;

      } else {
         this.monthCardTime.active = false;

      }
      if (this.monthCardTime)
         NumberToImage.numberToImageNodes(cc.fx.GameConfig.GM_INFO.monthTime, 35, 15, "button_", this.monthCardTime.children[1], true);
   }

   openConfirmBox() {
      if (this.node)
         this.node.getChildByName("ConfirmBox").active = true;
      this.closeLoad();
   }

   //关闭商城确认按钮
   closeConfirmBox() {
      if (this.node)
         this.node.getChildByName("ConfirmBox").active = false;
   }

   // update (dt) {}
}
