import { showToast } from "../../module/ctrls";
import { ajax, jsonp } from "../../module/ajax";
import { GDispatcher } from "../index";
import { getUrlParams } from "../../module/tools/WebTool";

//////////////星速台接口方法集成
/**
 * web接口枚举，mock 文件名类似aaa/homeInfo.do
 */
export enum WebNetName {
    /**
     * 首页
     * 参数a 参数b
     */
    index = "/projectx/{projectId}/game/index.do",
    /**
     * 参与
     */
    join = "/projectx/{projectId}/game/join.do",
    /**
     * 获取结果
     */
    queryResult = "/projectx/{projectId}/game/queryResult.do",
    /**
     * 获取规则
     */
    projectRule = "/projectx/{projectId}/projectRule.query"
}

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

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

/**
 * 发送接口
 * @param netName
 * @param parameter
 * @param callback
 * @param hideMsg
 * @param isGet
 * @param headers
 */
export function sendWebNet(
    netName: WebNetName,
    parameter?: any,
    callback?: (success: boolean, res?: dataOut) => void,
    hideMsg: boolean = false,
    isGet: boolean = true,//这两个参数基本不设置，放后面吧
    headers?: any,
): Promise<dataOut> {
    return new Promise((resolve, reject) => {

	    if (__ENV__ == "development") { // TODO 编译后提供的变量
            let path = netName.split('{projectId}/')[1];//后缀名字之前的是文件夹,mock里结构
            if (path.indexOf('/') <= -1) path = `projectX/${path}`;
            const url = "../../mock/webNet/" + path + ".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
                    );
                }, () => {
                })
            return
        }

        //网络请求
        ajax({
            url: netName.replace("{projectId}", getProjectId()), //请求地址
            type: isGet ? 'GET' : "POST",   //请求方式
            data: parameter || {}, //请求参数
            dataType: "json",     // 返回值类型的设定,暂时只有json
            async: true,   //是否异步
            headers: headers,
            success: function (response) {
                //发现有些接口成功了，但是response为空
                response = response || {}
                //记录数据
                dataRecord[netName] = response;
                //统一错误信息提示，
                if (!hideMsg && !response.success) {
                    showToast(response.message || "活动太火爆了，请稍后再试~");
                }
                callback && callback(response.success, response)
                resolve(response)
                console.log(
                    `\n%c[ request ]\n`
                    + `NAME  : ${netName} \n`
                    + `STATE : %o \n`
                    + `PARAM : %o \n`
                    + `%cDATA  : %o \n`
                    , `${response.success ? 'color:green' : 'color:red'}`
                    , response.success
                    , parameter
                    , `${response.success ? 'color:green' : 'color:red'}`
                    , response
                );
            },
            error: function (status) {
                if (!hideMsg) showToast("网络超时");
                callback && callback(false)
                resolve({ success: false });
                console.log("接口" + netName + "：网络超时");
            },
        })
    })
}

/**
 * 获取数据
 * @param netName
 */
export function getWebData(netName: WebNetName): dataOut {
    return dataRecord[netName] || null;
}

//销毁数据
export function destroyWebNetData() {
    dataRecord = {}
}


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;
}

const projectxString = "projectx/";
let projectId: string;

/**
 * 获取链接上的projectId
 */
export function getProjectId(): string {
    if (projectId) return projectId;

    let windowUrl = window.location.href;
    let splitArr = windowUrl.split(projectxString);
    if (splitArr.length != 2) {

        return projectId = "projectId"
    }

    let start = windowUrl.indexOf(projectxString) + projectxString.length;
    let end = splitArr[1].indexOf("/");
    return projectId = windowUrl.substr(start, end);
}

//这个临时，如星速台链接有变，注意
var isProd = location.href.indexOf(".com.cn/projectx") >= 0;

/**
 * 刷新星速台tokenkey,注意多活动跳转手动执行一边
 * @param callback
 */
export function refreshPxTokenKey(callback?: (success: boolean) => void) {
    if (isProd) {//线上
        var head = document.getElementsByTagName("head")[0];
        const scriptEl = document.createElement('script');
        scriptEl.src = "getTokenKey?_=" + Date.now();
        scriptEl.onload = function () {
            head.removeChild(scriptEl);
            callback && callback(true)
        };
        scriptEl.onerror = function () {
            head.removeChild(scriptEl);
            callback && callback(false)
        };
        head.appendChild(scriptEl);
    } else {//本地环境
        callback && callback(true)
    }
}

//执行一次
refreshPxTokenKey();

/**
 * 获取星速台token
 * @param callback
 */
export function getPxToken(callback: (msg: string, token?: string) => void) {
    if (!isProd) {//本地环境
        callback(null, "token")
        return
    }
    if (!window["ohjaiohdf"]) {
        callback("need reload")
        return
    }
    var xml = new XMLHttpRequest;
    xml.open("get", "getToken?_t=" + Date.now(), !0);
    xml.onreadystatechange = function () {
        if (xml.readyState === 4 && xml.status === 200) {
            var e = JSON.parse(xml.response);
            if (e.success) {
                window.eval(e.data);
                callback(null, window["ohjaiohdf"]());
            } else {
                var msg = (() => {
                    switch (e.code) {
                        case "100001":
                            return "need login"
                        case "100024":
                            return "state invalid"
                        default:
                            return e.code
                    }
                })();
                callback(msg);
            }
        }
    }
    xml.onerror = function () {
        callback("net error")
    };
    xml.onloadend = function () {
        xml.status === 404 && callback("net error")
    };
    xml.send()
}

export enum LOG_TYPE {
    EXPOSURE = 'exposure',
    CLICK = 'click',
}

/**
 * 埋点  sendLog(LOG_TYPE.EXPOSURE,"4")
 * 注意点击埋点前必有曝光埋点
 * @param type
 * @param data
 */
export function sendLog(type: LOG_TYPE | 'exposure' | 'click', area: number) {
    const projectID = getProjectId();
    const appID = getUrlParams("appID");
    //给个提示
    if (!appID) console.error("appID不存在，检查链接")
    var dpm = `${appID || 'appID'}.110.${area}.1`;// TODO appID注意默认写死一个，已防链接没有
    var dcm = `202.${projectID || 'projectID'}.0.0`;
    //看需求
    // var dom = `${isWxClient() ? '2' : '1'}.0.0.0`;
    let params: any = {
        dpm,
        dcm,
        appId: appID
    };
    //看需求
    // if (dom) params.dom = dom;
    let isExposure = (type == LOG_TYPE.EXPOSURE);
    if (isExposure) {
        //曝光
        jsonp('//embedlog.duiba.com.cn/exposure/standard', params);
    } else {
        //点击
        jsonp('/log/click', params);
    }
    // console.log('try log', {type, ...params});
}


/**
 * 根据规则id获取奖品列表
 * @param strategyId 规则id
 * @param optionId 不传表示返回所有奖品
 */
export function queryPrizeList(strategyId: string, optionId?: string): Promise<dataOut> {
    let url = `/projectx/${getProjectId()}/${strategyId}.query`;
    return new Promise((resolve) => {
        if (window.location.port == "8080") {//本地环境
            resolve({//自定义数据。暂时这样
                "success": true,
                "message": "consequat ea",
                "data": [
                    {
                        "prizeType": "dolore culpa in tempor",
                        "name": "ka3",
                        "refType": "Excepteur adipisicing sint",
                        "icon": "//yun.duiba.com.cn/spark/assets/58184d8d965c556b412026acf7a5d5d9e7a975f5.png",
                        "index": "Ut in pariatur",
                        "id": "et",
                        "refId": "minim culpa veniam aliqua ut",
                        "prizeId": "aa",
                        "icon2": "aliquip consectetur laborum Duis"
                    }
                ],
                "code": "fugiat velit in esse aute"
            })
        } else {
            ajax({
                url,
                type: 'GET',
                data: optionId ? { optionId } : {},
                dataType: "json",
                async: true,
                success: function (response) {
                    resolve(response)
                },
                error: function () {
                    resolve({ success: false })
                }
            })
        }
    })
}

////////////webview通信的范例，小程序端的是天猫精灵的例子
//天猫的webview数据请求方式  webview和小程序通讯方式，别忘了html上加sdk
//<script type="text/javascript" src="https://appx/web-view.min.js"></script>
export enum TmallNetName {
    getAppData = "mine.getAppData",
    /**
     * 监听声音类型
     */
    getVoiceType = "mine.getVoiceType",

}

//淘宝小程序全局
const my = window["my"];
if (FYGE.getEnv() == "web" && my) {//小程序webview时
    //接收数据
    my.onMessage = function (e) {
        console.log("返回数据", e.netName, e.data)
        //记录数据
        // data[e.netName] = e.data;
        //触发事件，会考虑单独发过来的事件
        GDispatcher.dispatchEvent(e.netName, e.data)
    }
}

export function sendTmallNet(
    netName: TmallNetName,
    parameter?: any,
    callback?: (success: boolean, res?: dataOut) => void,
): Promise<dataOut> {
    console.log("发送数据", netName, parameter)
    return new Promise((resolve, reject) => {
        if (window["development"]) {
            var url = "../../mock/miniTb/" + netName + ".json"
            fetchAsync(url)
                .then((data) => {
                    //回调
                    callback && callback(data.success, data);
                    resolve(data);
                }, () => {
                    callback(false);
                })
            return
        }
        if (FYGE.getEnv() == "web" && !my) {//临时处理
            if (netName == TmallNetName.getAppData) {
                var d = {
                    success: true,
                    data: {
                        avatar: "https://source.unsplash.com/user/erondu/76x76",
                        userNick: "驱蚊器委屈委"
                    }
                }
                callback && callback(true, d);
                resolve(d);
            }
            return
        }
        //向小程序发信息
        my.postMessage({
            netName: netName,
            parameter: parameter
        });
        //事件回调
        let fun = function (e: { type: string, data: dataOut }) {
            var d = e.data;
            GDispatcher.removeEventListener(netName, fun);
            callback && callback(d.success, d);
            resolve(d);
        }
        //加事件
        GDispatcher.addEventListener(netName, fun);
    })
}
