const fs = require('fs');
const path = require('path')
const XLSX = require('xlsx');
// const app = require('express')();
// const server = require('http').Server(app);
const {RedisConf, CommonConf} = require('./config')
const Redis = require('ioredis');

let dataPath = "../assets/scripts/data";
let dataPrefix =  "allstar_";

/**
 * excel表转换为json对象
 * @param {String} filename 文件名
 */
function getSheet(filename) {
    let filePath = path.join(__dirname, "/excel", filename);
    // let buf = fs.readFile(filePath);
    let workbook = XLSX.readFileSync(filePath)
    let sheets = workbook.SheetNames;
    if(sheets.length == 1) {
        let firstSheet = sheets[0]
        let ws = workbook.Sheets[firstSheet]
        return XLSX.utils.sheet_to_json(ws, {range: 1})
    } else if(sheets.length > 1) {
        let sheetsObj = {}
        sheets.forEach(n => {
            let ws = workbook.Sheets[n]
            sheetsObj[n] = XLSX.utils.sheet_to_json(ws, {range: 1})
        })
        return sheetsObj;
    }
    
    // console.log(XLSX.utils.sheet_to_json(ws));
    // console.log(workbook.SheetNames);
}

/**
 * 写入json内容到客户端assets目录
 * @param {String} filename 文件名
 * @param {Object} content json内容
 */
function writeToAssets (filename, content) {
    let writeFileName = filename.replace(/\.xlsx|\.xls/, '.js').replace(dataPrefix, "");
    let writePath = path.join(__dirname, dataPath, writeFileName);
    fs.writeFile(writePath, 'module.exports=' + JSON.stringify(content))
    console.log(JSON.stringify(content, null, 2));
}

function init () {
    let redis = new Redis(RedisConf.R1);
    
    fs.readdir("./excel", (err, file) => {
        file.forEach(n => {
            if(n.match(/\~\$/)) {
                return
            }
            let ws = getSheet(n);

            if(ws.length > 0) {
                //单个表
                let sheetName = 'client:' + n.replace("_", ":").replace(/\.xlsx|\.xls/, "");
                ws.forEach((value, index) => {
                    let hkey = Object.keys(value)[0]
                    redis.multi().hset(sheetName,  value[hkey], JSON.stringify(value)).exec()
                })
                console.log(`Add ${sheetName} to redis`);
            } else {
                //多个表，redis的key要加上表名
                for(let i in ws) {
                    let sheetName = 'client:' + n.replace("_", ":").replace(/\.xlsx|\.xls/, "") + ':' + i;
                    ws[i].forEach((value, index) => {
                        let hkey = Object.keys(value)[0]
                        redis.multi().hset(sheetName,  value[hkey], JSON.stringify(value)).exec()
                    })
                    console.log(`Add ${sheetName} to redis`);
                }
            }
    
            //把生成的js写入客户端assets目录
            writeToAssets(n, ws);
        })

        // process.exit()
    })
}

init();

// let ws = getSheet("allstar_buildingtest_level.xlsx")
// ws.forEach((value, index) => {
//     let key = `allstar:test`;
//     redis.multi().hset(key,  index, JSON.stringify(value)).exec()
// })

// redis.get("allstar:building", (err, res) => {
    // console.log(res);
// })

// for(var i in BuildingInfo) {
//     for(var j in BuildingInfo[i]) {
//         let key2 = `allstar:test:${i}:${BuildingInfo[i][j].level}`;
//         redis.set(key2, JSON.stringify(BuildingInfo[i][j]))    
//     }
// }

// app.get('/', function (req, res) {
    // res.body = getSheet("achievementAttribute.xlsx")
    // res.sendFile(__dirname + '/index.html');
// });

// server.listen(408, () => {
//     console.log('listening on *:408');
// });