var zxy = require('zxy-comm');
var path = require('path');
var _ = require('underscore');
var Promise = require('bluebird');
var multiparty = require('multiparty');
var fs = require('fs');

//上传文件
var upload = function (req, res) {
    res.setHeader("Access-Control-Allow-Origin", "*");
    //创建上传文件夹
    var uploadfilepath = path.join(__dirname, '../../../uploads/');
    if (!fs.existsSync(uploadfilepath)) {
        fs.mkdirSync(uploadfilepath);
    }
    // 解析一个文件上传
    var form = new multiparty.Form();
    //设置编辑
    form.encoding = 'utf-8';
    //设置文件存储路径
    form.uploadDir = "uploads/";
    //设置单文件大小限制 
    // form.maxFilesSize = 2 * 1024 * 1024;
    //设置所以文件的大小总和
    // form.maxFields = 1000;  
    form.parse(req, function (err, fields, files) {
        var destination = path.join(__dirname, '../../../uploads/');
        var encoding = form.encoding;
        var batch = zxy.app.m_cryptogram.md5(new Date().valueOf().toString() + zxy.app.m_obtain.getRandomStr() + zxy.app.m_obtain.guid());
        var ids = new Array();
        var promise_arr = new Array();
        _.each(files, function (obj) {
            obj = obj[0];
            var id = zxy.app.m_obtain.guid();
            var originalname = obj.originalFilename;
            var fieldname = obj.fieldName;
            var filename = obj.path.replace('uploads\\', '').replace('uploads/', '');
            var mimetype = obj.headers['content-type'];
            var path = require('path').join(__dirname, '../../../' + obj.path);
            var size = obj.size;
            ids.push({ uuid: id, originalname: originalname, mimetype: mimetype, size: size });
            var sql = "INSERT INTO zxy_upload_log("
                + "id,destination,encoding,fieldname,filename,mimetype,originalname,path,size,upload_time,batch)VALUES("
                + "@id,@destination,@encoding,@fieldname,@filename,@mimetype,@originalname,@path,@size,NOW(),@batch);";
            promise_arr.push(
                zxy.app.m_mysql.run(sql, {
                    id: id,
                    destination: destination,
                    encoding: encoding,
                    fieldname: fieldname,
                    filename: filename,
                    mimetype: mimetype,
                    originalname: originalname,
                    path: path,
                    size: size,
                    batch: batch
                })
            );
        });
        Promise.all(promise_arr).then(function () {
            res.jsonp(ids);
        });
    });
}
exports.upload = upload;

//下载文件
var download = function (req, res) {
    res.setHeader("Access-Control-Allow-Origin", "*");
    var id = req.params.id;
    try {
        var sql = "select * from zxy_upload_log where id = @id";
        zxy.app.m_mysql.run(sql, {
            id: id
        }).then(function (r) {
            if (r && r.length && r[0]) {
                if (fs.exists(r[0].path, function (exists) {
                    if (exists) {
                        var attachmentName = r[0].originalname;
                        attachmentName = encodeURIComponent(attachmentName);
                        res.setHeader('Content-disposition', 'attachment; filename=' + attachmentName);
                        res.setHeader('Content-type', r[0].mimetype + ";charset=utf8");
                        var filestream = fs.createReadStream(r[0].path);
                        filestream.on('data', function (chunk) {
                            res.write(chunk);
                        });
                        filestream.on('end', function () {
                            res.end();
                        });
                    }
                    else {
                        res.send({ code: -1, msg: '文件不存在' });
                    }
                }));
            }
            else {
                res.send({ code: -2, msg: '文件信息不存在' });
            }
        }).catch(function () {
            res.send({ code: -3, msg: '查找文件信息异常' });
        });
    }
    catch (ex) {
        res.send({ code: -4, msg: '系统错误' });
    }
}
exports.download = download;

//预览文件
var preview = function (req, res) {
    res.setHeader("Access-Control-Allow-Origin", "*");
    var id = req.params.id;
    try {
        var sql = "select * from zxy_upload_log where id = @id";
        zxy.app.m_mysql.run(sql, {
            id: id
        }).then(function (r) {
            if (r && r.length && r[0]) {
                if (fs.exists(r[0].path, function (exists) {
                    if (exists) {
                        if (r[0].mimetype.StartWith('video/') ||
                            r[0].mimetype.StartWith('image/') ||
                            r[0].mimetype.StartWith('text/')) {
                            var rs = fs.createReadStream(r[0].path);
                            rs.on('data', function (data) {
                                res.write(data);
                            });
                            rs.on('end', function () {
                                res.end();
                            });
                        }
                        else {
                            res.send({ code: -5, msg: '暂不支持该类型文件预览' });
                        }
                    }
                    else {
                        res.send({ code: -1, msg: '文件不存在' });
                    }
                }));
            }
            else {
                res.send({ code: -2, msg: '文件信息不存在' });
            }
        }).catch(function () {
            res.send({ code: -3, msg: '查找文件信息异常' });
        });
    }
    catch (ex) {
        res.send({ code: -4, msg: '系统错误' });
    }
}
exports.preview = preview;

//获取文件属性
var attribute = function (req, res) {
    res.setHeader("Access-Control-Allow-Origin", "*");
    var id = req.params.id;
    try {
        var sql = "select * from zxy_upload_log where id = @id";
        zxy.app.m_mysql.run(sql, {
            id: id
        }).then(function (r) {
            if (r && r.length && r[0]) {
                var attr = {
                    uuid: r[0].id,
                    mimetype: r[0].mimetype,
                    originalname: r[0].originalname,
                    size: r[0].size,
                    upload_time: r[0].upload_time,
                    batch: r[0].batch
                };
                res.jsonp(attr);
            }
            else {
                res.send({ code: -2, msg: '文件信息不存在' });
            }
        }).catch(function () {
            res.send({ code: -3, msg: '查找文件信息异常' });
        });
    }
    catch (ex) {
        res.send({ code: -4, msg: '系统错误' });
    }
}
exports.attribute = attribute;