const fs = require('fs');
const path = require('path');
const co = require('co');
const OSS = require('ali-oss');

const chalk = require('chalk');
const ProgressBar = require('progress');

const iconv = require('iconv-lite');

const config = require("../project.json");

class TuiaAutoUpload {
    constructor(props, type) {
        this.type = type;
        const defaultOptions = {
            dir: undefined,
            originDir: undefined
        }
        this.options = Object.assign({}, defaultOptions, props);
        if (!this.options.dir || !this.options.originDir) {
            console.log(chalk.red('缺少参数，初始化失败'))
            return;
        }
        this.init();
    }
    init() {
	    const _this = this;
	    this.client = new OSS({
            region: 'oss-cn-hangzhou',
			accessKeyId: 'LTAI5tAEU43ff2kFkrKRLnxG',
			accessKeySecret: '2qQIPVT3Lgp72s8RShDlE4uVNqZWgy',
            bucket: _this.type === 'prod' ? 'duiba' : 'daily-duiba'
        });
        this.bar = new ProgressBar(chalk.yellow(`  文件上传中 [:bar] :current/${this.files().length} :percent :elapseds`), {
            complete: '●',
            incomplete: '○',
            width: 20,
            total: this.files().length,
            callback: () => {
                console.log(chalk.green('\n  All complete.'));
                console.log(chalk.blue(`\n  本次队列文件共${this.files().length}个，已存在文件${this.existFiles}个，上传文件${this.uploadFiles}个，上传失败文件${this.errorFiles}个\n`));
            }
        })
        return this;
    }
    files() {
	    const _this = this;
	    if (this._files) return this._files;
        this._files = [];

        /**
         * 文件遍历方法
         * @param filePath 需要遍历的文件路径
         */
        function fileDisplay(filePath) {
            //根据文件路径读取文件，返回文件列表
	        const files = fs.readdirSync(filePath);
	        files.forEach(function (filename) {
                //获取当前文件的绝对路径
		        const filedir = path.join(filePath, filename);
		        //根据文件路径获取文件信息，返回一个fs.Stats对象
		        const stats = fs.statSync(filedir);
		        const isFile = stats.isFile();//是文件
		        const isDir = stats.isDirectory();//是文件夹
                if (isFile) {
	                let sep = '/';
	                if ('win32' === process.platform)
                        sep = '\\';
	                const newDirArr = filedir.split(sep);
	                newDirArr.shift();
                    _this._files.push(newDirArr.join('/'));
                }
                if (isDir) {
                    fileDisplay(filedir);//递归，如果是文件夹，就继续遍历该文件夹下面的文件
                }
            });

        }

        //调用文件遍历方法
        fileDisplay(this.options.dir);
        return this._files;
    }
    start() {
        this.files().map((file) => {
            let _this = this;
            const path1 = path.join(path.resolve(__dirname, '..'), 'released', file);
            let originFile;
            this.existFiles = 0;
            this.uploadFiles = 0;
            this.errorFiles = 0;
            co(function* () {
                const originPath = `${_this.options.originDir}${file}`;
                try {
                    originFile = yield _this.client.head(originPath);
                } catch (error) {
                    originFile = error;
                }
                if (_this.type === 'prod') {
                    if (originFile.status === 404) {
                        yield _this.client.put(originPath, path1);
                        _this.uploadFiles += 1;
                    } else {
                        _this.existFiles += 1;
                    }
                } else if (_this.type === 'dev') {
                    if (originFile.status === 404 || originFile.status === 200) {
                        _this.existFiles += 1;
                    }
                    yield _this.client.put(originPath, path1, {
                        headers: {
                            'Cache-Control': 'no-cache'
                        }
                    })
                    _this.uploadFiles += 1;
                }
                _this.bar.tick();
            }).catch(function (err) {
                _this.errorFiles += 1;
                console.log(err);
            });
        });
    }
}

if (!config.type) {
    throw new Error(`project.json 的type不存在.`);
}

if (!config.name) {
    throw new Error(`project.json 的name不存在.`);
}

const now = new Date();
const version = Math.round(now.getTime() / 1000);

console.log(chalk.bgMagenta(`资源版本号：\n${version}`));

const autoupload = new TuiaAutoUpload({
    dir: './released/',
    originDir: `/db_games/${config.type}/${config.name}/${version}/`
}, "prod");

autoupload.start();

const readPath = "./released/resource/";

// 读取json文件
let data = iconv.decode(fs.readFileSync(readPath + "res.json"), "utf-8");// GBK

// 反序列化
data = JSON.parse(data);
data.path = `https://yun.duiba.com.cn/db_games/${config.type}/${config.name}/${version}/resource/`;

// 写入目标文件夹，可配置，每个项目必须修改，或者直接和project的保持一致（淘宝项目文件固定后）
const endPath = './src/';
const endFile = `export const ResJson = ${JSON.stringify(data, "", "\t")}`;
fs.writeFileSync(endPath + "ResJson.ts", endFile);
