import { NetManager } from "../libs/tw/manager/NetManager";
import { DataManager } from "../libs/tw/manager/DataManager";
import { NetName } from "../libs/tw/enum/NetName";
import PanelCtrl from "./ctrls/panelCtrl";
import { ModuleTypes } from "./types/sceneTypes";
import GameConst from "./GameConst";

export class NetPromise {
  private static instance: NetPromise;

  public static get ins(): NetPromise {
    if (!this.instance) {
      this.instance = new NetPromise();
    }
    return this.instance;
  }

  constructor() { }

  shareCode;
  inviteCode;

  Date=new Date();

  /**
   * 达令家养成任务列表
   */
  getDalingjiaTaskList(type,alert?) {
    let alert1;
    if(alert){
       alert1=alert
    }else{
       alert1=0;
    }
    return new Promise((resolve, reject) => {
      NetManager.ins.getDalingjiaTaskList((success) => {
        if (!success) {
          reject(success)
        }
        resolve(success)
      }, type,window["CFG"].activityId,alert1)
    })
  }

  /**
   * 查询签到情况
   */
  getSignInfo() {
    return new Promise((resolve, reject) => {
      NetManager.ins.getSignInfo((success) => {
        if (!success) {
          reject(success)
        }
        resolve(success)
      }, window["signActivityId"])
    })
  }

  /**
   * 达令家养成查询连续签到信息
   */
  getCntSignInfo() {
    return new Promise((resolve, reject) => {
      NetManager.ins.getCntSignInfo((success) => {
        if (!success) {
          reject(success)
        }
        resolve(success)
      }, window["signActivityId"])
    })
  }

  /**
  * 查询补签卡
  */
  getReSignCard() {
    return new Promise((resolve, reject) => {
      NetManager.ins.getReSignCard((success) => {
        if (!success) {
          reject(success)
        }
        resolve(success)
      })
    })
  }

  /**
   * 达令家养成任务领奖接口
   */
  getDalingjiaTaskPrize(rewardType,vipType) {
    return new Promise((resolve, reject) => {
      NetManager.ins.getDalingjiaTaskPrize((success) => {
        if (!success) {
          reject(success)
        }
        resolve(success)
      }, rewardType,vipType)
    })
  }

  /**
   * 签到
   */
  doSign() {
    return new Promise((resolve, reject) => {
      NetManager.ins.doSign2((success) => {
        if (!success) {
          reject(success)
        }
        resolve(success)
      }, window["signActivityId"])
    })
  }

 /**
   * 达令家养成任务补签接口
   */
  reSign(signDate) {
    return new Promise((resolve, reject) => {
      NetManager.ins.reSign((success) => {
        if (!success) {
          reject(success)
        }
        resolve(success)
      }, window["signActivityId"],signDate)
    })
  }
  
  /**
   * 获取分享码
   */
  getUserShareCode() {
    return new Promise((resolve, reject) => {
      NetManager.ins.getUserShareCode((success) => {
        if (!success) {
          reject(success)
        }
        resolve(success)
      })
    })
  }


  /**
  * 达令家养成-签到关注开关
  */
  setSignpetPushSwitch(type) {
    return new Promise((resolve, reject) => {
      NetManager.ins.setSignpetPushSwitch((success) => {
        if (!success) {
          reject(success)
        }
        resolve(success)
      }, type, window["signType"],window["signActivityId"])
    })
  }


  async Main(){
    console.log()
    setTimeout(()=>{
     // this.openSignWin();
    },2000)
    console.log("milk")
    console.log(DataManager.ins.getData("milk"))
     await this.ReSignCardTips();
     await this.msgTipsState();
     this.taskJoinPrize()
  }

  openSignWin(){
    NetPromise.ins.getSignInfo()
    .then(()=>{
        return NetPromise.ins.getCntSignInfo()
    })
    .then(()=>{
        console.log("打开签到弹窗")
        PanelCtrl.instance.show(ModuleTypes.SIGN_PANEL)
    })
    .then(()=>{
        //PanelCtrl.instance.show(ModuleTypes.SIGN_PANEL)
    })
    .catch(()=>{

    })
}

  taskJoinPrize(){
      let dcustom = GameConst.getCookie("dcustom");
      this.getDalingjiaTaskList(NetPromise.ins.getQueryVariable(dcustom, "vip"),1)
      .then(() => {
            for(let i=0;i<DataManager.ins.getData(NetName.GET_DALINGJIA_TASK_LIST).data.length;i++){
               if(DataManager.ins.getData(NetName.GET_DALINGJIA_TASK_LIST).data[i].type=="assistance"
               &&DataManager.ins.getData(NetName.GET_DALINGJIA_TASK_LIST).data[i].alert
               &&DataManager.ins.getData(NetName.GET_DALINGJIA_TASK_LIST).data[i].durationRewardCount>0){
                   NetPromise.ins.showToast(`好友助力成功，奖励${DataManager.ins.getData(NetName.GET_DALINGJIA_TASK_LIST).data[i].durationRewardCount}g牛草`)
               }
            }
      })
      .catch(() => {
      })
  }

  /**
   * 设置弹窗
   */
 msgTipsState(){
    return new Promise((resolve, reject) => {
      this.getSignInfo()
    .then(()=>{
        return this.getSignpetPushQuery()
    })
    .then(()=>{
        let continueDay=DataManager.ins.signInfoData.signInfoVO.continueDay;
        if(continueDay==3&&DataManager.ins.getData(NetName.getSignpetPushQuery).data==0){
          console.log("弹出开启通知开关")
          PanelCtrl.instance.show(ModuleTypes.PUB_PANEL,{winType:"signtips_group",callback:()=>{
           resolve()
            }})
        }else{
          resolve()
        }
         
    })
    .catch(()=>{
      resolve()
    })
    })
  }

   /**
   * 设置每月补签卡弹窗
   */
  ReSignCardTips(){
     return new Promise((resolve, reject)=>{
        if(DataManager.ins.getData("milk").data.reSignCardRewardTimes>=1){
            this.TakePrize()
            .then(()=>{
             // console.log("恭喜您，获得补签卡"+DataManager.ins.getData(NetName.TakePrize).data.count)
              if(DataManager.ins.getData(NetName.TakePrize).data.count){
                  PanelCtrl.instance.show(ModuleTypes.PUB_PANEL,
                    {
                      winType:"resingcard_group",
                      text:`每月补签卡到账啦!\n补签卡+${DataManager.ins.getData(NetName.TakePrize).data.count}`,
                      callback:()=>{
                        resolve()
                      }
                    }
                  )
                }else{
                  resolve()
                }
            })
            .catch(()=>{
              resolve()
            })
        }else{
           resolve()
        }
     })
  }
  
  /**
   * 达令家养成每月赠送补签卡
   */
  TakePrize() {
    return new Promise((resolve, reject) => {
      NetManager.ins.TakePrize((success) => {
        if (!success) {
          reject(success)
        }
        resolve(success)
      })
    })
  }

  /**
   * 达令家养成-签到关注开关查询
   */
  getSignpetPushQuery() {
    return new Promise((resolve, reject) => {
      NetManager.ins.getSignpetPushQuery((success) => {
        if (!success) {
          reject(success)
        }
        resolve(success)
      }, window["signType"], window["signActivityId"])
    })
  }

  /**
   * 达令家养成-记录分享任务完成状态
   */
  setSignpetTaskBrowse() {
    return new Promise((resolve, reject) => {
      let dcustom = GameConst.getCookie("dcustom");
      NetManager.ins.setSignpetTaskBrowse((success) => {
        if (!success) {
          reject(success)
        }
        resolve(success)
      },NetPromise.ins.getQueryVariable(dcustom, "vip"))
    })
  }

  /**
   * 达令家养成-签到-助力接口
   */
  doHelp4Sign(shareCode) {
    return new Promise((resolve, reject) => {
      NetManager.ins.doHelp4Sign((success) => {
        if (!success) {
          reject(success)
        }
        resolve(success)
      }, window["CFG"].activityId, window["joinSignType"], shareCode)
    })
  }

  /**
   * 达令家养成-查询邀请的用户列表
   */
  getInvitedConsumers(count,shareCode) {
    return new Promise((resolve, reject) => {
      NetManager.ins.getInvitedConsumers((success) => {
        if (!success) {
          reject(success)
        }
        resolve(success)
      }, count, window["CFG"].activityId,"signpet",shareCode)
    })
  }

  /**
   * 获取url cookie参数
   * @param url 
   * @param variable 
   */
  getQueryVariable(url, variable) {
    var query = url;
    var vars = query.split("&");
    for (var i = 0; i < vars.length; i++) {
      var pair = vars[i].split("=");
      if (pair[0] == variable) { return pair[1]; }
    }
    return (false);
  }


  /**
   * 获取url参数
   * @param name 
   */
  getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]);
    return null;
  };

  /**
   * 分享功能
   */
  handleShare() {
    return new Promise((resolve, reject) => {
      window["kuwoApi"].share({
        imgurl: 'https://yun.duiba.com.cn/db_games/activity/kwyyyc_20190809/share.jpg',
        imageurl: 'https://yun.duiba.com.cn/db_games/activity/kwyyyc_20190809/share.jpg',
        url: `https://activity.m.duiba.com.cn/customShare/share?id=3490&appId=${window["CFG"].appId}&activityId=${window["CFG"].activityId}`,
        weibo: '上酷我，一起来玩酷小我出道记！',
        qqspace: '上酷我，一起来玩酷小我出道记！',
        qqspaceTitle: '上酷我，一起来玩酷小我出道记！',
        qqfriend: '升级酷小我，红包领不停～',
        qqfriendTitle: '上酷我，一起来玩酷小我出道记！',
        wxmsg: '上酷我，一起来玩酷小我出道记！',
        wxdes: '升级酷小我，红包领不停～',
        needconfirm: '0',
        callback: function (res) {
          //r(res);
          console.log('kwShare', res);
          resolve()
        }
      });
    })
  };

  /**
   * 播放音乐
   * @param data 
   */
  handlePlay(data) {
    window["kuwoApi"].play({
      index: 0,
      isplayall: false,
      libpath: "worldcup",
      listpic: "",
      listtitle: "",
      musiclist: [data],
      callback: (res) => {
        console.log('play', res);
      }
    });
  }

  /**
   * 提示toast
   * @param string 
   * @param time
   */
  showToast(string: string = "活动太火爆了，请稍后再试~", time = 1500) {
    let msgData = { msg: string, time: time, isHideMask: true }
    PanelCtrl.instance.show(ModuleTypes.TOAST_PANEL, msgData);
  }

  /**
   * 是否微信环境
   */

  isWeiXin() {
    var ua = navigator.userAgent.toLowerCase();
    if (ua.match(/MicroMessenger/i)) {
      return true
    } else {
      return false
    }
  }

}