const fs = require('fs');
const path = require('path');
const csv = require('csv-parser');
const XLSX = require('xlsx');
const csv_data  = {
    
}
csv_data.loadData = function(){
    var results = [];
    const filePath = path.join(__dirname, '2024-10-28-novel.csv'); // 替换为你的 CSV 文件路径
    fs.createReadStream(filePath)
      .pipe(csv())
      .on('data', (data) => {
        if(data['是否挂件']=='1'){
            let obj = this.parsePromotion(data['挂件地址'])
            if(obj!=null){
                results.push(
                    {'点赞':data['点赞数'],
                    '视频链接':data['视频链接'],
                    '视频id':data['视频id'],
                    '标题':data['标题'],
                    '发布时间':data['发布时间'],
                    '收藏数':data['收藏数'],
                    '评论数':data['评论数'],
                    '分享数':data['分享数'],
                    '渠道':obj.channel,
                    '书id':obj.book_id||0,
                    '挂件详情':JSON.stringify(obj)})
            }
        }
      })
      .on('end', () => {
        this.GoWriteFile(results,false)
        // console.log(results); // 这里会打印出解析后的 CSV 数据
      });
}

//解析挂件
csv_data.parsePromotion = function(promotion){
    let list = promotion.split('&')
    if(list.length!=undefined){
        if(list.length>2){
            let params = {}
            for (let index = 0; index < list.length; index++) {
                const element = list[index];
                let obj = this.parsePromotionItem(element)
                if(obj!=null){
                    if(obj.key=="start_page"&&obj.bookId!=null&&obj.bookId!=undefined){
                        params['bookId'] = obj.bookId
                    }
                    params[obj.key] = obj.value
                }
            }
            let channel = this.getChannel(params['start_page'])
            if(channel!=null){
                let item_info = {}
                if(params['bookId']!=undefined&&channel=="黑岩"){
                    item_info['book_id'] = params['bookId'];
                }
                item_info['channel'] = channel;
                return item_info
            }
            return null
        }else{
            return null
        }
    }else{
        return null
    }
}

csv_data.parsePromotionItem = function(item){
    let list = item.split('=')
    if(list.length>1){
        let key = list[0]
        let value = list[1]
        if(key==="start_page"&&list.length>2){
            return {key:key,value:value,bookId:list[2]}
        }
        return {key:key,value:value}
    }
    return null
}

csv_data.getChannel = function(start_page){
    if(start_page==="pages/readPage/chapter?bookId"){
        return "黑岩"
    }else if(start_page==="pages/bookstore/index?aid"){
        return "番茄"
    }
    return null
}

csv_data.GoWriteFile = function(data,isJson=false){
    if(isJson){
        // 要写入的文件路径
        const filePath = path.join(__dirname, 'data.json');
        // 将数据写入 JSON 文件
        fs.writeFile(filePath, JSON.stringify(data, null, 2), (err) => {
            if (err) {
                console.error('Error writing to JSON file:', err);
                return;
            }
            console.log('JSON file has been written successfully');
        });
    }else{
        const excelFilePath = path.join(__dirname, 'data.xlsx');
        const worksheet = XLSX.utils.json_to_sheet(data);
        const workbook = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
        XLSX.writeFile(workbook, excelFilePath);
        console.log('Excel file has been generated successfully');
    }

}
module.exports = csv_data;