import { GDispatcher } from "..";
import { DreamToast } from "../components/DreamToast/DreamToast";
import { ModalCtroller } from "../modules/ModalControl";

//接口枚举，包括需要调用淘宝的api，用是否含有兑吧区分，或者单独区分
export enum TbNetName {
    submitGame = 'mine.submitGame',
    reduceTools = "mine.reduceTools",
    goBackHome = "mine.goBackHome",
    goMyPrize = "mine.goMyPrize",
    onDrawLottery = "mine.onDrawLottery",
    openCardTask = "mine.openCardTask"
}

async function fetchAsync(url: string) {
    // await response of fetch call
    let response = await fetch(url);
    // only proceed once promise is resolved
    let data = await response.json();
    // only proceed once second promise is resolved
    return data;
}

function showToast(msg: string) {

    ModalCtroller.showModal(DreamToast, {
        msg: msg
    }, {
        maskAlpha: 0
    })
    setTimeout(() => {
        ModalCtroller.closeModal(DreamToast)
    }, 1500)
}

//返回数据类型
interface dataOut {
    success: boolean,
    data?: any
    code?: string,
    message?: string
}

//记录数据
let dataRecord: {
  [name: string]: any
} = {};

/**
* 发送接口
* @param netName
* @param parameter
* @param callback
* @param hideMsg
*/
export function sendTbNet(
  netName: TbNetName,
  parameter?: any,
  callback?: (success: boolean, res?: dataOut) => void,
  hideMsg: boolean = false
): Promise<dataOut> {
  return new Promise((resolve, reject) => {
      //网络超时
      // let waitObj;
      //@ts-ignore 本地开发，直接取数据
      console.log('send tbNet ===========')
      if (location && location.port == '8081') {
          const netInfo = netName.split(".");
        const url = `../../mock/miniTb/${netInfo[0]}/${netInfo[1]}.json`;
        fetchAsync(url)
              .then((data) => {
                  //清除超时
                  // clearWait(waitObj)
                  //记录数据
                  dataRecord[netName] = data;
                  //统一错误信息提示
                  if (!hideMsg && !data.success) showToast(data.message || "网络异常")
                  //回调
                  callback && callback(data.success, data);
                  resolve(data)
                  console.log(
                      `\n%c[ mock ]\n`
                      + `NAME  : ${netName} \n`
                      + `STATE : %o \n`
                      + `PARAM : %o \n`
                      + `%cDATA  : %o \n`
                      , `${data.success ? 'color:green' : 'color:red'}`
                      , data.success
                      , parameter
                      , `${data.success ? 'color:green' : 'color:red'}`
                      , data
                  );
              }, () => {
                  resolve({ success: false, data: null });
              })
          return
      }


      let fun = function (e: { type: string, data: dataOut }) {
          //清除超时记录
          // clearWait(waitObj)
          //移除事件
          GDispatcher.removeEventListener(netName, fun);

          var d = e.data;
          //记录数据
          dataRecord[netName] = d;
          //统一错误信息提示，d.data为了区分网络超时
          if (!hideMsg && !d.success) showToast(d.message || "网络超时")
          //执行回调
          callback && callback(d.success, d);
          resolve(d)
          console.log(
              `\n%c[ request ]\n`
              + `NAME  : ${netName} \n`
              + `STATE : %o \n`
              + `PARAM : %o \n`
              + `%cDATA  : %o \n`
              , `${d.success ? 'color:green' : 'color:red'}`
              , d.success
              , parameter
              , `${d.success ? 'color:green' : 'color:red'}`
              , d
          );
      }
      //添加事件接收接口返回信息
      GDispatcher.addEventListener(netName, fun);
      //用事件方式吧，派发事件发接口,,,,注意很多独有的事件名别重了，onHide,onShow,onMessage等  放到最后，因为有同步的情况
      GDispatcher.dispatchEvent({ type: "onMessage" }, { netName, parameter })
  })
}