/**标准清单操作相关
 * Created by Zhong on 2017/8/2.
 */
let billsController = require("./bills_lib_controllers");
let billsLibDao = require("./../models/bills_lib_interfaces");
import baseController from "../../common/base/base_controller";
import fs from 'fs';
import path from 'path';
import multiparty from 'multiparty';
const excel = require("node-xlsx");
const uuidV1 = require('uuid/v1');

const shareDir = 'public/share/images';
const imgTriggers = ['billsRecharge', 'rationExplanation', 'rationRuleText'];


class billsPermContr extends baseController{
    getCurrentUniqId(req, res){
        billsController.getCurrentUniqId(req, res);
    }
    getBills(req, res){
        billsController.getBills(req, res);
    }
    createBills(req, res){
        billsController.createBills(req, res);
    }
    updatePNId(req, res){
        billsController.updatePNId(req, res);
    }
    upMove(req, res){
        billsController.upMove(req, res);
    }
    downMove(req, res){
        billsController.downMove(req, res);
    }
    upLevel(req, res){
        billsController.upLevel(req, res);
    }
    downLevel(req, res){
        billsController.downLevel(req, res);
    }
    updateBills(req, res){
        billsController.updateBills(req, res);
    }
    updateSectionInfo(req, res){
        billsController.updateSectionInfo(req, res);
    }
    updateBillsArr(req, res){
        billsController.updateBillsArr(req, res);
    }
    removeTotal(req, res){
        billsController.removeTotal(req, res);
    }
    updateSerialNo(req, res){
        billsController.updateSerialNo(req, res);
    }
    pasteBills(req, res){
        billsController.pasteBills(req, res);
    }
    updateRecharge(req, res){
        billsController.updateRecharge(req, res);
    }
    pasteRel(req, res){
        billsController.pasteRel(req, res);
    }
    deleteBills(req, res){
        billsController.deleteBills(req, res);
    }
    isUsed(req, res){
        billsController.isUsed(req, res);
    }
    /*
     * 导入标准清单(确定节点结构：深度数组)
     * */
    importBills(req, res){
        let form = new multiparty.Form({uploadDir: './public'});
        const allowHeader = ['application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'];
        let uploadFullName;
        form.parse(req, async function (err, fields, files) {
            try {
                const file = typeof files.file !== 'undefined' ? files.file[0] : null;
                if (err || !file) {
                    throw '上传失败。';
                }
                if (file.headers['content-type'] === undefined || allowHeader.indexOf(file.headers['content-type']) < 0) {
                    throw '不支持该类型';
                }
                const billsLibId = typeof fields.billsLibId !== 'undefined' && fields.billsLibId.length > 0 ? fields.billsLibId[0] : null;
                if (!billsLibId) {
                    throw '请选择一个清单库。';
                }
                let hasData = await billsLibDao.hasData(billsLibId);
                if (hasData) {
                    throw '请新建一个新的清单库，或删除库中的清单后再导入。';
                }
                // 重命名文件名
                uploadFullName = './public/' + file.originalFilename;
                fs.renameSync(file.path, uploadFullName);
                const sheet = excel.parse(uploadFullName);
                if (sheet[0] === undefined || sheet[0].data === undefined || sheet[0].data.length <= 0) {
                    throw 'excel没有对应数据';
                }
                //插入清单
                await billsLibDao.importBills(billsLibId, sheet[0].data);
                // 删除文件
                if(uploadFullName && fs.existsSync(uploadFullName)){
                    fs.unlinkSync(uploadFullName);
                }
                res.json({error: 0, data: null, msg: ''});

            } catch (err) {
                console.log(err);
                // 删除文件
                if(uploadFullName && fs.existsSync(uploadFullName)){
                    fs.unlinkSync(uploadFullName);
                }
                res.json({error: 1, data: null, msg: err});
            }
        });
    }

    /*
    *上传图片
    * */
    uploadImg(req, res){
        let uploadDir = path.join(req.app.locals.rootDir, shareDir);
        let form = new multiparty.Form({uploadDir: uploadDir});
        form.parse(req, async function(err, fields, files){
            try {
                const file = typeof files.file !== 'undefined' ? files.file[0] : null;
                if(err || !file) {
                    throw '上传失败';
                }
                //触发上传图片的地方
                const trigger = typeof fields.trigger !== 'undefined' && fields.trigger.length > 0 ? fields.trigger[0] : null;
                if (!trigger || !imgTriggers.includes(trigger)) {
                    throw '该操作没有上传权限'
                }
                if (!fs.existsSync(uploadDir)) {
                    fs.mkdirSync(uploadDir);
                }
                //根据触发源放置文件到相关文件夹
                let triggerPath = path.join(uploadDir, trigger);
                if (!fs.existsSync(triggerPath)) {
                    fs.mkdirSync(triggerPath);
                }
                //文件后缀
                let px = file.originalFilename.split('.').pop();
                //时间戳重命名图片并移动文件
                let newFileName = Date.now() + '.' + px;
                if (fs.existsSync(newPath)) {
                    newFileName += uuidV1();
                }
                let newPath = path.join(triggerPath, newFileName);
                fs.renameSync(file.path, newPath);
                //返回图片域名后的url
                res.json({error: 0, data: `${shareDir}/${trigger}/${newFileName}`, message: 'success'});
            } catch (err) {
                console.log(err);
                res.json({error: 1, data: null, message: err});
            }
        });
    }
    /*
    * 删除图片
    * */
    delImg(req, res){
        try {
            let data = JSON.parse(req.body.data),
                trigger = data.trigger,
                url = data.url;
            if (!imgTriggers.includes(trigger)) {
                throw '该操作没有权限';
            }
            //拼接完整的删除路径
            let delUrl = path.join(req.app.locals.rootDir, url);
            fs.unlinkSync(delUrl);
            res.json({error: 0, data: null, message: 'success'});
        } catch(err) {
            res.json({error: 1, data: null, message: err});
        }
    }
    /*
     *  根据页码加载图片
     *  返回总页码和当前页码的图片信息
     * */
    loadImgs(req, res){
        try {
            let data = JSON.parse(req.body.data),
                trigger = data.trigger,
                page = data.page;
            if (!imgTriggers.includes(trigger)) {
                throw '该操作没有权限';
            }
            //每页显示的图片数
            const perImgs = 3;
            //总的图片信息
            let triggerPath = path.join(req.app.locals.rootDir, shareDir, trigger);
            if (!fs.existsSync(triggerPath)) {
                fs.mkdirSync(triggerPath);
            }
            let allImgs = fs.readdirSync(triggerPath);
            //将图片按照时间排序,降序
            allImgs.sort(function (a, b) {
                let aV = a.split('.')[0],
                    bV = b.split('.')[0];
                    if(aV > bV) {
                        return -1;
                    } else if(aV < bV) {
                        return 1;
                    }
                    return 0;
            });
            let pageCount = Math.ceil(allImgs.length / perImgs) || 1;
            //当前页图片信息
            let startIdx = (page - 1) * perImgs,
                endIdx = startIdx + 3,
                currentPageArr = allImgs.slice(startIdx, endIdx),
                currentImgsUrl = [];
            for (let img of currentPageArr){
                currentImgsUrl.push(`${shareDir}/${trigger}/${img}`);
            }
            res.json({error: 0, data: {pageCount: pageCount, currentImgsUrl: currentImgsUrl}, message: 'success'});

        } catch (err) {
            console.log(err);
            res.json({error: 1, data: {pageCount: 1, currentImgsUrl: []}, message: err});
        }
    }
}

export default billsPermContr;