var http = require('http');
const sql_help = require('../use_mysql');
const PROT = 9101

var CMD = {
    'filter_task':require('../2filter_data/filter_server'),  //筛选任务
    'collect_create_task':require('../3collect_and_create_data/collect_and_create_data_server'), //收集并创建任务
    'send_data_task':require('../4send_data/send_data_server'), //发送数据给任务
    'tg_config':require('../config/get_config')
}
CMD.tg_config.init()
CMD.filter_task.init(CMD.collect_create_task)
CMD.collect_create_task.init(CMD.tg_config)

CMD.send_data_task.init()
var server = http.createServer(function(req,res){

    res.setHeader('Access-Control-Allow-Origin', '*'); // 允许所有域的请求，注意：在生产环境中应该限制为特定的域
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS'); // 允许的方法
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization'); // 允许的头部
    
    let body = '';

    // 监听数据块
    req.on('data', chunk => {
        body += chunk.toString(); // 将接收到的数据块转换为字符串并拼接
    });

    // 监听请求结束
    req.on('end', async () => {
        
        if (req.method === 'POST') {
            if (req.headers['content-type'] === 'application/x-www-form-urlencoded') {
                try {
                    // 解析 JSON 数据
                    const jsonData = JSON.parse(body);
                    console.log("recv msg:",jsonData)
                    const cmd = CMD[jsonData['cmd']] 
                    if(cmd==null||cmd==undefined){
                        res.writeHead(200, {'Content-Type': 'application/json'});
                        res.end(JSON.stringify({ message: 'cmd 错误',code:100}));
                    }else{
                        const fun = cmd[jsonData['fun']]
                        if(fun==null||fun==undefined){
                            res.writeHead(200, {'Content-Type': 'application/json'});
                            res.end(JSON.stringify({ message: 'fun 错误',code:100}));
                        }else{
                            fun(CMD.tg_config,jsonData['data'],(obj)=>{
                                res.writeHead(200, {'Content-Type': 'application/json'});
                                res.end(JSON.stringify(obj));
                            })
                        }
                    } 
                } catch (error) {
                    // 处理解析错误
                    console.error('Error parsing JSON:', error);
                    res.writeHead(200, {'Content-Type': 'application/json'});
                    res.end(JSON.stringify({ error: 'Invalid JSON' }));
                }
            } else {
                // 如果不是 JSON 内容类型，返回错误
                res.writeHead(200, {'Content-Type': 'text/plain'});
                res.end('Unsupported Media Type. Please send data as JSON.');
            }
        }else{
            res.writeHead(200, {'Content-Type': 'text/plain'});
            res.end(' Please Use Post.');
        }
        
    });

})
server.listen(PROT,()=>{

});  
sql_help.connect((results)=>{
    if(results){
      
    }
})

module.exports = CMD;