const CMD = {}
const time_count = 60000*5 //60秒更新一次配置
const WebSocket = require('ws');
const ConfigTaskManager = require('../worker_task/ConfigTaskManager')
const redis_help = require('../use_redis');
class WebSocketClient {
    constructor(url, options = {},wsListener) {
        this.url = url;
        this.options = options;
        this.wsListener = wsListener
        this.reconnectDelay = options.reconnectDelay || 5000;
        this.heartbeatInterval = options.heartbeatInterval || 30000;
        this.heartbeatTimeout = options.heartbeatTimeout || 5000;
        
        this.ws = null;
        this.heartbeatTimer = null;
        this.reconnectTimer = null;
        this.heartbeatTimeoutTimer = null;
        
        this.connect();
    }

    connect() {
        try {
            this.ws = new WebSocket(this.url);
            
            this.ws.on('open', () => {
                console.log('WebSocket connected');
                this.startHeartbeat();
                this.wsListener.onOpen(this.ws)
            });

            this.ws.on('message', (data) => {
                this.handleMessage(data);
            });

            this.ws.on('close', () => {
                console.log('WebSocket closed');
                this.cleanup();
                this.scheduleReconnect();
                this.wsListener.onClosing()
            });

            this.ws.on('error', (error) => {
                console.error('WebSocket error:', error);
                this.cleanup();
                this.scheduleReconnect();
                this.wsListener.onFailure()
            });

        } catch (error) {
            console.error('Connection error:', error);
            this.scheduleReconnect();
            this.wsListener.onFailure()
        }
    }

    handleMessage(data) {
        // Handle incoming messages
        const message = data.toString();
        console.log('Received:', message);
        // If received pong message
        if (message === 'pong') {
            clearTimeout(this.heartbeatTimeoutTimer);
            return
        }
        this.wsListener.onMessage(this.ws,message)
        // Handle other messages
    }

    startHeartbeat() {
        this.heartbeatTimer = setInterval(() => {
            if (this.ws.readyState === WebSocket.OPEN) {
                // Send ping message
                this.ws.send('ping');
                
                // Set timeout for pong response
                this.heartbeatTimeoutTimer = setTimeout(() => {
                    console.log('Heartbeat timeout');
                    this.ws.terminate();
                }, this.heartbeatTimeout);
            }
        }, this.heartbeatInterval);
    }

    cleanup() {
        if (this.heartbeatTimer) {
            clearInterval(this.heartbeatTimer);
            this.heartbeatTimer = null;
        }
        if (this.heartbeatTimeoutTimer) {
            clearTimeout(this.heartbeatTimeoutTimer);
            this.heartbeatTimeoutTimer = null;
        }
        if (this.reconnectTimer) {
            clearTimeout(this.reconnectTimer);
            this.reconnectTimer = null;
        }
    }

    scheduleReconnect() {
        if (!this.reconnectTimer) {
            this.reconnectTimer = setTimeout(() => {
                console.log('Attempting to reconnect...');
                this.connect();
            }, this.reconnectDelay);
        }
    }

    close() {
        this.cleanup();
        if (this.ws) {
            this.ws.close();
        }
    }

    sendMsg(msg){
        if (this.ws) {
            this.ws.send(msg);
        }
    }
}
var FilterConfig = null
// {
//     kepp_num: 10,
//     status: 1,
//     is_guajian: 1,
//     platform_select: 2,
//     material_time: 2,
//     comment_num: 289,
//     shared_num: 10,
//     like_num: 10,
//     genre: 1,
//     source_filter: ["来源1","来源2"]
//   }
var MainConfig = null
// [
//     {
//       budget: 9000000,
//       tg_platform_id: 2,
//       tg_link_config: '{"id": 3, "is_open": "1", "kadian_id": "", "chongzhi_id": 1, "huichuan_id": ""}',
//       app_id: 'tt46893034d9b8232301',
//       ad_quantity: 40,
//       main_name: '陆丰全量',
//       running_status: 1,
//       bid_type: 2,
//       valid_time: 12,
//       daily_new_limit: 0,
//       id: 3,
//       update_time: '2024-11-22 11:38:37',
//       cpa_bid: 1750,
//       bid_ratio: '2:1',
//       create_time: '2024-11-20 12:18:12'
//     },
// ]
  
var AppConfig = null
// [
//     {
//         budget: 9000000,
//         app_id: 'tt2fff5942b0cca07701',
//         ad_quantity: 40,
//         main_name: '吉林爱麦厅',
//         create_time: '2024-11-20 14:59:45',
//         bid_type: 1,
//         tg_platform_id: 1,
//         daily_new_limit: 0,
//         id: 5,
//         update_time: '2024-11-20 16:51:28',
//         cpa_bid: 1750,
//         running_status: 1,
//         bid_ratio: '1'
//       }
// ]

var PlatformConfig = null
// [
//     {
//       tg_platform_id: 1,
//       chongzhi: '[{"id": 1, "name": "短篇9.9元"}, {"id": 2, "name": "热门19.9元"}]',
//       id: 1,
//       huichuan: '[{"id": 1, "name": "全部回传"}, {"id": 2, "name": "关闭回传"}, {"id": 3, "name": "传10漏1"}]',
//       tg_platform_name: '黑岩',
//       kadian: '[{"id": 1, "name": "默认卡点"}, {"id": 2, "name": "第1章"}, {"id": 3, "name": "第2章"}]'
//     },
//     {
//       tg_platform_id: 2,
//       chongzhi: '[{"id": 1, "name": "热门19.9元"}]',
//       tg_platform_name: '番茄',
//       id: 2
//     },
//     {
//       tg_platform_id: 3,
//       chongzhi: '[{"id": 1, "name": "短篇9.9元"}, {"id": 2, "name": "热门19.9元"}, {"id": 3, "name": "热门29.9元"}, {"id": 4, "name": "热门39.9元"}, {"id": 5, "name": "热门59.9元"}]',
//       id: 5,
//       huichuan: '[{"id": 1, "name": "全部回传"}]',
//       tg_platform_name: '测试平台1',
//       kadian: '[{"id": 1, "name": "默认卡点"}, {"id": 2, "name": "第一章"}]'
//     },
//     { tg_platform_id: 4, tg_platform_name: '测试平台2', id: 6 },
//     { tg_platform_id: 5, tg_platform_name: '测试平台3', id: 7 },
//     { tg_platform_id: 6, tg_platform_name: '测试平台4', id: 8 },
//     { tg_platform_id: 7, tg_platform_name: '测试平台5', id: 9 },
//     {
//       tg_platform_id: 8,
//       chongzhi: '[{"id": 1, "name": "长篇19.9元"}, {"id": 2, "name": "短篇9.9"}]',
//       id: 10,
//       huichuan: '[{"id": 1, "name": "关闭回传"}]',
//       tg_platform_name: '起点',
//       kadian: '[{"id": 1, "name": "默认卡点"}]'
//     }
//   ]
  
var axios = require('axios');
const tools = require('../../tools');

//根据Appid获取主体
CMD.getMainInfoByAppid = function(app_id){
    let list = []
    for (let index = 0; index < MainConfig.length; index++) {
        const element = MainConfig[index];
        if(element.app_id==app_id){
            list.push(element)
        }
    }
    return list
}

//根据平台id获取小程序
CMD.getAppInfoByPlatformId = function(tg_platform_id){
    for (let index = 0; index < AppConfig.length; index++) {
        const element = AppConfig[index];
        if(element.tg_platform_id==tg_platform_id){
            return element
        }
    }
    return null
}
CMD.getPlatformInfoByName = async function(name){
    if(PlatformConfig==null){
        PlatformConfig = await CMD.getPlatformConfig()
    }
    for (let index = 0; index < PlatformConfig.length; index++) {
        const element = PlatformConfig[index];
        if(element.tg_platform_name==name){
            return element
        }
    }
    return null
}

CMD.getStaticPlatformInfoByName = function(name){
    for (let index = 0; index < PlatformConfig.length; index++) {
        const element = PlatformConfig[index];
        if(element.tg_platform_name==name){
            return element
        }
    }
    return null
}

CMD.getStaticFilterConfig = function(){
    return FilterConfig
}
//获取数据筛选配置
CMD.getFilterConfig = async function(){
    if(FilterConfig!=null){
        return FilterConfig
    }
    await CMD.updateFilterConfig()
    return FilterConfig
}
CMD.updateFilterConfig = async function(){
    const postData = {
        cmd:"db_filter_config",
        fun:"getConfig",
        data:{}
    };
    return axios.post('http://127.0.0.1:9100/tg/back/api', postData)
    .then(response => {
        FilterConfig  = response.data.data
        redis_help.setKeyValue("FilterConfig",JSON.stringify(FilterConfig))
        // console.log("updateFilterConfig",FilterConfig)
    })
    .catch(error => {
      console.error('updateFilterConfig error!', error);
  });
}
//获取主体配置
CMD.getMainConfig = async function(){
    if(MainConfig!=null){
        return MainConfig
    }
    await CMD.updateMainConfig()
    return MainConfig
}
CMD.updateMainConfig = async function(){
    const postData = {
        cmd:"tg_main",
        fun:"getOpenMainList",
        data:{}
    };
    axios.post('http://127.0.0.1:9100/tg/back/api', postData)
    .then(response => {
        MainConfig  = response.data.data
        redis_help.setKeyValue("MainConfig",JSON.stringify(MainConfig))
        // console.log("MainConfig",MainConfig)
    })
    .catch(error => {
      console.error('updateFilterConfig error!', error);
    });
}
//获取小程序配置
CMD.getAppConfig = async function(){
    if(AppConfig!=null){
        return AppConfig
    }
    await CMD.updateAppConfig()
    return MainConfig
}
CMD.updateAppConfig = async function(){
    const postData = {
        cmd:"tg_app",
        fun:"getAppList",
        data:{}
    };
    axios.post('http://127.0.0.1:9100/tg/back/api', postData)
    .then(response => {
        AppConfig  = response.data.data
        redis_help.setKeyValue("AppConfig",JSON.stringify(AppConfig))
        // console.log("AppConfig",AppConfig)
    })
    .catch(error => {
      console.error('updateFilterConfig error!', error);
    });
}

//获取平台配置
CMD.getPlatformConfig = async function(){
    if(PlatformConfig!=null){
        return PlatformConfig
    }
    await CMD.updatePlatformConfig()
    return PlatformConfig
}
CMD.updatePlatformConfig = async function(){
    const postData = {
        cmd:"tg_platform",
        fun:"getPlatformList",
        data:{}
    };
    axios.post('http://127.0.0.1:9100/tg/back/api', postData)
    .then(response => {
        PlatformConfig  = response.data.data
        redis_help.setKeyValue("PlatformConfig",JSON.stringify(PlatformConfig))
        // console.log("PlatformConfig:",PlatformConfig)
    })
    .catch(error => {
      console.error('updateFilterConfig error!', error);
    });
}
var ws_isOpen = false
CMD.myListener = {
    onOpen: function (webSocket, response) {
        ws_isOpen = true
        //打开链接后，想服务器端发送一条消息
        sendMessage("status_task",{work:1})
    },
    onMessage: function (webSocket, msg) { //msg可能是字符串，也可能是byte数组，取决于服务器送的内容
        recvMessage(msg)
    },
    onClosing: function (webSocket, code, response) {
        ws_isOpen = false
    },
    onClosed: function (webSocket, code, response) {
        ws_isOpen = false
    },
    onFailure: function (webSocket, t, response) {
    }
}

function sendMessage(cmd,data){
    if(ws_isOpen==true){
        var json = {};
        json.cmd=cmd; //方法
        json.data= data; //参数
        var msg=JSON.stringify(json);
        if(CMD.wsClient!=undefined&&CMD.wsClient!=null){
            CMD.wsClient.sendMsg(msg);
        }
    }
}

async function recvMessage(data){
    try {
        // 单个任务
        let json_msg = JSON.parse(data)
        console.log("recvMessage:",data)
        // // 批量任务
        // const batchItems = Array(1000).fill().map((_, i) => ({
        //     type: 'batch',
        //     data: `item-${i}`
        // }));
        // const results = await taskManager.processBatch(batchItems);
        // console.log('Batch processing completed:', results.length);
        switch (json_msg.cmd) {
            case "updateFilterConfig":
                CMD.updateFilterConfig()
            break;
            case "updateMainConfig":
                CMD.updateMainConfig()
            break;
            case "updateAppConfig":
                CMD.updateAppConfig()
            break;
            case "updatePlatformConfig":
                CMD.updatePlatformConfig()
            break;     
            default:
                const result = await taskManager.processTask({ type: 'single', data: json_msg });
                console.log('Single task result:', result);
            break;
        }
        }catch(e){
            await taskManager.shutdown();
            console.error("recvMessage error:",e)
        }
}

const taskManager = new ConfigTaskManager();
CMD.init = function(){
    redis_help.connect((results)=>{
        if(results){
            CMD.wsClient = new WebSocketClient('ws://127.0.0.1:9211', {
                reconnectDelay: 5000,      // 5 seconds
                heartbeatInterval: 30000,  // 30 seconds
                heartbeatTimeout: 5000     // 5 seconds
            },CMD.myListener);
        }
    })
    // CMD.updateFilterConfig()
    // CMD.updateMainConfig()
    // CMD.updateAppConfig()
    // CMD.updatePlatformConfig()
    CMD.updateConfig()
    // Usage example:

    CMD.updateTimeConfig()
}

CMD.updateTimeConfig = function(){
    let create_heiyan_book_link = require('../api/hy/create_heiyan_book_link')
    create_heiyan_book_link.login((data)=>{
         tools.setHyToken(data['token'])
         // console.log("data:",data['token'])
    })
}
//定时更新配置
CMD.updateConfig = function(){
    setInterval(()=>{
        // CMD.updateFilterConfig()
        // CMD.updateMainConfig()
        // CMD.updateAppConfig()
        // CMD.updatePlatformConfig()
        CMD.updateTimeConfig()
    },time_count)
}
// To close connection
// wsClient.close();
module.exports = CMD