import { ACTIVITY_TYPE, HTTP_METHOD } from '../../consts';
import { httpRequest } from '../../pubUtils/httpUtil';
import { ServerTempModel } from '../../db/ServerTemp';
import { GetuiMessagesModel } from '../../db/GetuiMessages';

const crypto = require('crypto');
const APP_ID = "T5QiUVuzjw5nNT2kwjZpD2"
const APP_KEY = "IoP3lJYAgO63UWKSx6JyV2"
const APP_SECRET = "K9tGNJBnOt7iUBjXZ13hd4"
const PACKAGE_NAME = "com.getui.demo"
const MASTER_SECRET = "VVVRlJDaog7RWbLffpHzAA"
const BASE_URL = `https://restapi.getui.com/v2/${APP_ID}`


/**
   *  获取token
   *
   *
   */
export async function GTAuth() {
    let url = `${BASE_URL}/auth`;
    let headers = {
        'content-type': 'application/json;charset=utf-8',
    };
    const timestamp = new Date().getTime();
    let body = {
        sign: getSign(timestamp),
        timestamp,
        appkey: APP_KEY,
    };
    let result = await httpRequest(url, HTTP_METHOD.POST, body, headers)
    if (result.code == 0) {
        console.log('GETUI_TOKEN', result.data.token)
        return await ServerTempModel.updateGetuiData(result.data.token, result.data.expire_time);
    }
    return null;
}

/**
   * 执行cid单推
   *
   * @param {number} ttl 离线时间1-3天，单位毫秒
   * @param {string} cid 玩家cid
   * @param {string} title 信息标题
   * @param {string} bodyStr 信息内容
   *
   */
export async function GTPushSingleCidMessage(cid: string, ttl: number, title: string, bodyStr: string,) {
    let url = `${BASE_URL}/push/single/cid`;
    let body = {
        "request_id": uuid(),//唯一标识
        "settings": {
            "ttl": ttl,//259200000//1-3天，单位毫秒
        },
        "audience": {
            "cid": [
                cid
            ]
        },
        "push_message": {//个推通道消息内容
            "notification": {//仅支持安卓系统，iOS系统不展示个推通道下发的通知消息
                "title": title,
                "body": bodyStr,
                "click_type": "none",
                "url": ""
            }
        }
    }
    let result = await request(url, HTTP_METHOD.POST, {}, body)
    //{"msg":"success","code":0,"data":{"RASS_0630_a35e791ba3f04c84b741b9e5f17963ae":{"ba64ee9a9d516bbd341267d685baceb4":"successed_online"}}}
    //successed_online在线  successed_offline离线
    if (result.code == 0) {
        await GetuiMessagesModel.insertSingleMessage(body.request_id, JSON.stringify(body), 'GTPushSingleCidMessage', true)
        return true;
    }
    return false;
}

/**
   * 执行cid批量推
   *
   * @param {string} taskid 任务id
   * @param {string[]} cid cid数组
   * @param {boolean} isAsync 是否异步
   *
   */
export async function GTPushListCidMessage(taskid: string, cid: string[], isAsync: boolean = true) {
    let url = `${BASE_URL}/push/list/cid`;
    let body = {
        "taskid": taskid,
        "audience": {
            "cid": cid,
        },
        "is_async": isAsync,//是否异步
    }
    let result = await request(url, HTTP_METHOD.POST, {}, body)
    if (result.code == 0) {
        await GetuiMessagesModel.pushMessageSuccess(taskid, true);
        return true;
    }
    return false;
}

/**
   * 创建消息,此接口用来创建消息体，并返回taskid，为批量推的前置步骤
   *
   * @param {number} ttl 离线时间1-3天，单位毫秒
   * @param {string} group_name 任务组名
   * @param {string} title 信息标题
   * @param {string} bodyStr 信息内容
   *
   */
export async function GTCreateListMessage(group_name: string, ttl: number, title: string, bodyStr: string,) {
    let url = `${BASE_URL}/push/list/message`;
    let body = {
        "request_id": uuid(),//唯一标识
        "group_name": group_name,//"请填写任务组名",
        "settings": {
            "ttl": ttl,//259200000//1-3天，单位毫秒
        },
        "push_message": {//个推通道消息内容
            "notification": {//仅支持安卓系统，iOS系统不展示个推通道下发的通知消息
                "title": title,
                "body": bodyStr,
                "click_type": "none",
                "url": ""
            }
        }
    }
    let result = await request(url, HTTP_METHOD.POST, {}, body)
    //{"msg":"success","code":0,"data":{"taskid":"RASL_0630_da707a0c484d4ee39f2d462d5f52984c"}}
    //taskid 任务编号，用于执行cid批量推和执行别名批量推，此taskid可以多次使用，有效期为用户设置的离线时间
    if (result.code == 0) {
        await GetuiMessagesModel.insertListMessage(body.request_id, result.data.taskid, JSON.stringify(body), 'GTCreateListMessage', false)
        return result.data.taskid;
    }
    return false;
}

export async function request(url: string, method: string, headers: any, body: any) {
    const timestamp = new Date().getTime();
    let tokenData = await ServerTempModel.findGetuiData();

    if (!tokenData || (!tokenData.getuiTokenExpireTime) || timestamp > tokenData.getuiTokenExpireTime) {
        tokenData = await GTAuth()
        if (tokenData) {
            console.log('token success')
        } else {
            console.log('token fail......')
        }
    }

    headers = { ...headers, 'content-type': 'application/json;charset=utf-8', 'token': tokenData.getuiToken };
    let result = await httpRequest(url, method, body, headers)
    if (result.code == 10001) {
        if (await GTAuth()) {
            console.log('token success11')
        } else {
            console.log('token fail......')
        }
    }
    return result;
}


/**
 * 获取签名
 * @param timestamp 时间戳
 */
function getSign(timestamp: number) {
    let stringToSign = `${APP_KEY}${timestamp}${MASTER_SECRET}`;
    return crypto.createHash('sha256').update(stringToSign).digest('hex');
}

function uuid() {
    var d = new Date().getTime();
    var uuid = d + '-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = (d + Math.random() * 16) % 16 | 0;
        d = Math.floor(d / 16);
        return (c == 'x' ? r : (r & 0x7 | 0x8)).toString(16);
    });
    return uuid;
};