const CMD = {}
const time_count = 250;
const PROT = 9101
var http = require('http');
const axios = require('axios')
const redis_help = require('../src/use_redis');
const origin_data_controllers = require('../src/data_manager/Controllers/origin_data_controllers');
const helper = require('../src/helper');
const HttpClient = require('../src/HttpClient')
const config = require('../etc/config.json')
var recv_data_list = []

const 视频id = 0;
const 视频链接 = 1;
const 标题 = 2;
const 发布时间 = 3;
const 收藏数 = 4;
const 评论数 = 5;
const 点赞数 = 6;
const 分享数 = 7;
const 是否挂件 = 8;
const 挂件地址 = 9;
let task_status = false
function excelDateToJs(dateStr) {
    // const date = moment(dateStr, "DD/MM/YYYY HH:mm:ss").toDate();
    // return new Date(date);
    return new Date()
}

async function processTask(){
    try{
        if(recv_data_list.length>0){
            const xml = recv_data_list.pop();
            let guajian_link = ''
            guajian_link = xml[挂件地址]
            const result = await origin_data_controllers.getOriginData({video_id:xml[视频id]})
            if(result.success){
                await origin_data_controllers.updateOriginData({id:result.data.id},{kepp_num:xml[收藏数],comment_num:xml[评论数],like_num:xml[点赞数],shared_num:xml[分享数],guajian_link:guajian_link})
            }else{
                await origin_data_controllers.createOriginData(
                    {
                        video_id:xml[视频id],
                        video_link:xml[视频链接],
                        title:xml[标题],
                        // publish_time:xml[发布时间],
                        publish_time:excelDateToJs(xml[发布时间]),
                        kepp_num:xml[收藏数],
                        comment_num:xml[评论数],
                        like_num:xml[点赞数],
                        shared_num:xml[分享数],
                        is_guajian:xml[是否挂件],
                        guajian_link:guajian_link,
                        status:0,
                    }
                )
            }
        }else{
            task_status = false;
        }
    }catch(e){
        console.log("数据解析错误：",e)
    }finally{
        global.setTimeout(processTask,200)
    }
}
CMD.startTask = function(data){
    task_status = true;
    let temp_list = JSON.parse(data)
    for (let index = 1; index < temp_list.length; index++) {
        let isGuaJian = parseInt(temp_list[index][是否挂件])==1
        if(isGuaJian){
            recv_data_list.push(temp_list[index])
        }
    }
    console.log("temp_list.length:",temp_list.length)
    processTask()
}

CMD.init = function(){
    redis_help.connect(()=>{

    })
}

CMD.runTask = async function(){
   
    for (let index = 0; index < recv_data_list.length; index++) {
        const xml = recv_data_list[index];
       
    }
 
}

CMD.test_fq_book_sid_tt = async function(book_id,sid_tt){
    try{
        let client =new HttpClient()
        let response =  await client.proxyRequest( helper.getFqRequestOpt(book_id,sid_tt))
        let obj = response['data']
        return obj['novel_data']
    }catch(e){
        // return {"error_book_id":book_id,"error_sid_tt":sid_tt}
        return null
    }

}

CMD.get_group_mapping = function(res){
    let get_hy_group_mapping = require('../src/api/hy/get_hy_group_mapping');
    get_hy_group_mapping.get_group_mapping((data)=>{
        res.writeHead(200, {'Content-Type': 'application/json'});
        if(data.code==200){
            let list = data.data
            res.end(JSON.stringify({ message:"成功！",data:list,code:10000}));
        }else{
            res.end(JSON.stringify({ message:"fail!",data:data,code:data.code}));
        }
        console.log("get_hy_group_mapping:",data)
    })
}
CMD.get_hy_rechargeTemplate = function(res){
    let get_hy_recharge_template = require('../src/api/hy/get_hy_recharge_template');
    get_hy_recharge_template.get_recharge_template("1865735741365059585",(data)=>{
        res.writeHead(200, {'Content-Type': 'application/json'});
        if(data.code==200){
            let list = data.data
            res.end(JSON.stringify({ message:"成功！",data:list,code:10000}));
        }else{
            res.end(JSON.stringify({ message:"fail!",data:data,code:data.code}));
        }
        console.log("get_hy_rechargeTemplate:",data)
    })
}

CMD.get_hy_passBackTemplate = function(res){
    let get_hy_call_back_template = require('../src/api/hy/get_hy_call_back_template');
        get_hy_call_back_template.get_callback_template((data)=>{
        res.writeHead(200, {'Content-Type': 'application/json'});
        if(data.code==200){
            let list = data.data
            res.end(JSON.stringify({ message:"成功！",data:list,code:10000}));
        }else{
            res.end(JSON.stringify({ message:"fail!",data:data,code:data.code}));
        }
        console.log("get_hy_passBackTemplate:",data)
    })
}

CMD.get_fq_rechargeTemplate = function(res){
    var distributorId = config.fanqie_config.distributorId;
    var secretKey = config.fanqie_config.secretKey;
    const postData = {
        distributor_id: distributorId,
        ts: helper.getCurrentUnixTimestamp(),
        sign: helper.getSign(distributorId,secretKey),
        page_size: 100,
        page_index:0,
    };
    // console.log("get_recharge_template:")
    var url = config.fanqie_config.recharge_list_host
    var base_params = `/?distributor_id=${postData.distributor_id}&ts=${postData.ts}&sign=${postData.sign}`
    var other_params = `&page_size=${postData.page_size}&page_index=${postData.page_index}`

    axios.get(`${url}${base_params}${other_params}`)
    .then(response => {
        // console.log('Response data:', response.data );
        let data  = response.data
        res.writeHead(200, {'Content-Type': 'application/json'});
        if(data.code==200){
            let list = data.data
            res.end(JSON.stringify({ message:"成功！",data:list,code:10000}));
        }else{
            res.end(JSON.stringify({ message:"fail!",data:data,code:data.code}));
        }
        console.log("get_fq_rechargeTemplate:",data)
    })
    .catch(error => {
        console.error('Error:', error);
        res.end(JSON.stringify({ message:"fail!",data:data,code:data.code}));
    });
}



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)
                    if(jsonData['fun']=="start_filter"&&jsonData['cmd']=="filter_task"){
                        res.writeHead(200, {'Content-Type': 'application/json'});
                        if(task_status==false){
                            CMD.startTask(jsonData['data'])
                            res.end(JSON.stringify({ msg: 'success!',code:10000,data:{}}));
                        }else{
                            res.end(JSON.stringify({ msg: '服务器繁忙!',code:10000,data:{}}));
                        }
                        
                    }else if(jsonData['fun']=="test_fq_book_sid_tt"&&jsonData['cmd']=="fq_book"){
                        let book_id = jsonData['data']['book_id']
                        let sid_tt = jsonData['data']['sid_tt']
                        let info = await CMD.test_fq_book_sid_tt(book_id,sid_tt) 
                        res.writeHead(200, {'Content-Type': 'application/json'});
                        if(info==null){
                            res.end(JSON.stringify({ message:"失败",code:10001}));
                        }else{
                            res.end(JSON.stringify({ message:"成功！",data:info,code:10000}));
                        }
                      
                    }else if(jsonData['fun']=="groupMapping"&&jsonData['cmd']=="hy_link"){
                         CMD.get_group_mapping(res) 
                    }else if(jsonData['fun']=="rechargeTemplate"&&jsonData['cmd']=="hy_link"){
                        CMD.get_hy_rechargeTemplate(res) 
                    }else if(jsonData['fun']=="passBackTemplate"&&jsonData['cmd']=="hy_link"){
                        CMD.get_hy_passBackTemplate(res) 
                    }else if(jsonData['fun']=="rechargeTemplate"&&jsonData['cmd']=="fq_link"){
                        CMD.get_fq_rechargeTemplate(res) 
                    } else{
                        res.writeHead(200, {'Content-Type': 'application/json'});
                        res.end(JSON.stringify({ message: 'fun 错误',code:100}));
                    }

                } 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,()=>{
});  

CMD.init()
