
// const api = require('./src/api/api');
// api.test()
// const csv_data = require('./src/csv_data')
// csv_data.loadData()



    var http = require('http');

    const url = require('url');

    const querystring = require('querystring');

    const sql_help = require('./src/use_mysql');
    const tools = require('./tools.js');
    tools.init()


    // const redis_help = require('./src/use_redis');

    var init_mysql = false

    var init_redis = false

    require('./src/config')

    global.config.initFinishAccount = function(){

    }

    global.config.initFinishFindApp = async function(task_id){
        const api = require('./src/api/api');
        api.createLink(JSON.parse(await redis_help.getKeyValue(task_id)))
    }

    // var jl_get_asset_list =  require('./src/api/jl_get_asset_list')
    // jl_get_asset_list.send()


    function start_run_heiyan_and_create(param,call_back){
        let create_heiyan_book_link = require('./src/api/hy/create_heiyan_book_link')
        create_heiyan_book_link.send(param.book_id,param.book_name,(start_page,start_param, info)=>{
            call_back(start_page,start_param, info,param.id)
        })
    }

    function start_run_fanqie_and_create(param,call_back){
        let remark =   param.app_page[0].new_remark
        let create_fanqie_book_link = require('./src/api/fq/create_fanqie_book_link')
        create_fanqie_book_link.send(param.book_id,1,remark,1,(start_page,start_param, info)=>{
            call_back(start_page,start_param, info,param.id)
        })
    }


    async function start_run_and_create(param,call_back){
        param.app_page =  [
            {
                "id": 0,
                "link": "",
                "remark": "",
                "operate_type": "NEW",
                "start_page": "",
                "start_param": ""
            }
        ]
        if(param.channel_type=="fanqie"){
            let name = param.book_name +""
            param.app_page[0].remark  =   name.replace(/[^\u4e00-\u9fa5a-zA-Z0-9]/g, '')
            param.app_page[0].new_remark =  name.replace(/[^\u4e00-\u9fa5a-zA-Z0-9]/g, '')
            start_run_fanqie_and_create(param,(start_page,start_param,info,id)=>{
                call_back(start_page,start_param, info,id)
            })
        }else if(param.channel_type=="heiyan"){
            param.app_page[0].remark = param.book_name
            param.app_page[0].new_remark = param.book_name + ""
            start_run_heiyan_and_create(param,(start_page,start_param,info,id)=>{
                call_back(start_page,start_param, info,id)
            })
        }
    }

    // sql_help.connect((results)=>{
    //     if(results){
    //         init_mysql = true
    //     }
    // })

    // create table auto_book_link (
    //     id int not null auto_increment COMMENT '唯一id',
    //     book_name  varchar(1024) DEFAULT "" COMMENT '小说名字',
    //     book_id   varchar(1024) DEFAULT "" COMMENT '书id',
    //     type   varchar(1024) DEFAULT "" COMMENT '类型',	
    //     info JSON  COMMENT  '详情',
    // primary key (id));


    async function recv(data){
        let cmd = data['cmd']
        if(cmd==null||cmd==undefined){
            return null
        }
        let post_param = data['param']
        if(post_param==null||post_param==undefined||init_mysql==false||init_redis==false){
            return null
        }
        if(cmd == "create_book_link"){
            let param =  {}
            param.book_id = post_param['book_id']
            param.book_name =  post_param['book_name']
            param.channel_type =  post_param['channel_type']
            if(param.book_id==""||param.book_name==""||param.channel_type==""){
                return null
            }
 
            if(param.book_id!=undefined&&param.book_name!=undefined&&param.channel_type!=undefined){
                param.id = await redis_help.getNewId()
                // tsak_list[param.id] = param
                sql_help.isHaveBook(param.book_id,(isHave)=>{
                    if(!isHave){
                        start_run_and_create(param,(start_page,start_param, info,id)=>{
                            let data  = {start_page:start_page,start_param:start_param,info:info}
                            sql_help.query('INSERT INTO auto_book_link SET ?', {book_name:param.book_name,book_id:param.book_id,type:param.channel_type,info:JSON.stringify(data,null,4)}, async ()=>{
                                console.log("成功创建！")
                                // let task_data = JSON.parse(await redis_help.getKeyValue(id))
                                param.app_page[0].start_page = start_page
                                param.app_page[0].start_param = start_param
                                await redis_help.setKeyValue(param.id,JSON.stringify(param))
                                var jl_get_app_list =  require('./src/api/jl_get_app_list')
                                jl_get_app_list.send(id)
                            })
                        })
                    }else{
                        console.log("已经存在这本书！")
                    }
                })
          
                return {status:"OK"}
            }
            return null
        }   
        return null
    }
    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', () => {
            
            if (req.method === 'POST') {
                if (req.headers['content-type'] === 'application/json') {
                    try {
                        // 解析 JSON 数据
                        const jsonData = JSON.parse(body);
                        // console.log('Received JSON data:', jsonData);
                        let d = recv(jsonData)
                        if(d==null){
                            res.writeHead(200, {'Content-Type': 'application/json'});
                            res.end(JSON.stringify({ message: '参数错误' ,data:null,code:100}));
                        }else{
                            // 发送响应
                            res.writeHead(200, {'Content-Type': 'application/json'});
                            res.end(JSON.stringify({ message: "",data:d,code:10000}));
                        }
                       
                    } 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(9877,()=>{

    // });

    // redis_help.connect((results)=>{
    //     if(results){
    //         test()
    //         init_redis = true
    //     }
    // })


    async function test(){
        // let hy_search_book = require('./src/api/hy/hy_search_book')
        // hy_search_book.search_id("1856613738085793794")


        // let fq_search_book = require('./src/api/fq/fq_search_book')
        // fq_search_book.search_name("阴毒世子")
        // fq_search_book.search_id("7156137614049807396")
    }

    require('./src/1recv_data/recv_server.js')
