'use strict';

/**
 *
 *
 * @author Zhong
 * @date 2018/5/29
 * @version
 */
import BaseController from '../../common/base/base_controller';
import moment from 'moment';
const billsGuidanceFacade = require('../facade/facades');
let logger = require('../../../logs/log_helper').logger;
const fs = require("fs");
// excel解析
const excel = require("node-xlsx");
let callback = function (req, res, err, msg, data) {
    res.json({error: err, message: msg, data: data});
};

const zhLibID = 'cf851660-3534-11ec-9641-2da8021b8e4e';

class BillsGuideLibController extends BaseController{

    //获取编办及编办清单库信息
    async getComBillsLibInfo(req, res){
        try{
            let comBillsLibInfo = await billsGuidanceFacade.getComBillsLibInfo();
            callback(req, res, 0, '', comBillsLibInfo);
        }
        catch(err) {
            callback(req, res, 1, err, null);
        }
    }

    async getBillsGuideLibs(req, res){
        try{
            let libs = await billsGuidanceFacade.getBillsGuideLibs({deleted: false}, req.session.managerData.isTemporary);
            callback(req, res, 0, '', libs);
        }
        catch(err){
            callback(req, res, 1, '获取清单指引库数据错误', null);
        }
    }

    async updateBillsGuideLib(req, res){
        try{
            let data = JSON.parse(req.body.data);
            if(data.updateType === 'create'){
                data.updateData.createDate = moment(Date.now()).format('YYYY-MM-DD HH:mm:ss');
                data.updateData.creator = req.session.managerData.username;
                await billsGuidanceFacade.initBillsGuideLib(data.updateData);
            }
            else{
                if (data.updateType === 'delete') {
                    logger.info(`delete billsGuidanceLib ${req.ip}`);
                }
                await billsGuidanceFacade.updateBillsGuideLib(data);
            }
            callback(req, res, 0, '', data.updateData);
        }
        catch(err){
            callback(req, res, 1, '更新失败', null);
        }
    }
    //获取清单指引库和该库引用的清单
    async getLibWithBills(req, res){
        try{
            let data = JSON.parse(req.body.data);
            let rst = await billsGuidanceFacade.getLibWithBills(data.libID);
            callback(req, res, 0, '', rst);
        }
        catch(err){
            callback(req, res, 1, err, null);
        }
    }

    async getItemsByBills(req, res){
        try{
            let data = JSON.parse(req.body.data);
            let items = await billsGuidanceFacade.getItemsBybills(data.guidanceLibID, data.billsID);
            callback(req, res, 0, '', items);
        }
        catch(err){
            callback(req, res, 1, err, null);
        }
    }

    async getItemsByBillIDs(req, res){
        try{
            let data = JSON.parse(req.body.data);
            let items = await billsGuidanceFacade.getItemsByBillIDs(data.guidanceLibID, data.billIDs);
            callback(req, res, 0, '', items);
        }
        catch(err){
            callback(req, res, 1, err, null);
        }
    }

    async updateItems(req, res){
        try{

            if (req.session.managerData.isTemporary) {
                const match = req.headers.referer.match(/libID=([\d,a-z,A-Z,-]{36})/);
                if (match && match[1] && match[1] !== zhLibID) {
                    throw '无此清单精灵库权限';
                }
            }

            let data = JSON.parse(req.body.data);
            let updateDatas = data.updateDatas;
            await billsGuidanceFacade.updateItems(updateDatas, req.session.managerData.isTemporary);
            callback(req, res, 0, '', null);
        }
        catch(err){
            callback(req, res, 1, err, null);
        }
    }

    async getBillMaterials(req, res){
        try{
            const data = JSON.parse(req.body.data);
            const materials = await billsGuidanceFacade.getBillMaterials(data.libID, data.billID);
            callback(req, res, 0, '', materials);
        }
        catch(err){
            callback(req, res, 1, err, null);
        }
    }

    async editBillMaterials(req, res){
        try{
            const data = JSON.parse(req.body.data);
            const materials = await billsGuidanceFacade.editBillMaterials(data.libID, data.billID, data.gljCodes, data.compilationID);
            callback(req, res, 0, '', materials);
        }
        catch(err){
            console.log(err);
            callback(req, res, 1, err.message, []);
        }
    }
    
    async generateClassData(req, res) {
        try{
            res.setTimeout(1000 * 60 * 10); // 不设置的话，处理时间过长，会触发默认的响应超时，报错(前端报错，后台还继续在处理)
            const data = JSON.parse(req.body.data);
            await billsGuidanceFacade.generateClassData(data.libID);
            callback(req, res, 0, '', []);
        }
        catch(err){
            console.log(err);
            callback(req, res, 1, err.message, []);
        }
    }

    async autoSetMaterial(req, res) {
        try{
            res.setTimeout(1000 * 60 * 10); // 不设置的话，处理时间过长，会触发默认的响应超时，报错(前端报错，后台还继续在处理)
            const data = JSON.parse(req.body.data);
            await billsGuidanceFacade.autoSetMaterial(data.libID);
            callback(req, res, 0, '', []);
        }
        catch(err){
            console.log(err);
            callback(req, res, 1, err.message, []);
        }
    }

    async exportClassExcel(req, res) {
        try{
            const excelData = await billsGuidanceFacade.getClassExcelData(req.query.libID);
            console.log('start-build');
            const buffer = excel.build([{name: "清单分类库", data: excelData}], {'!cols': [{wch:6}, {wch:12}, {wch:14}, {wch:24}, {wch:45}, {wch:20}, {wch:30}, {wch:30}]});
            console.log('end-build');
            const filePath = './public/export.xlsx';
            fs.writeFileSync(filePath, buffer, 'binary');
            const stats = fs.statSync(filePath);
            // 下载相关header
            res.set({
                'Content-Type': 'application/octet-stream',
                'Content-Disposition': 'attachment; filename=billClass.xlsx',
                'Content-Length': stats.size
            });
            fs.createReadStream(filePath).pipe(res);
            fs.unlink(filePath);
        }
        catch(err){
            console.log(err);
            response.end(error);
        }
    }

    async testItems(req, res){
        try{
            let data = JSON.parse(req.body.data);
            let rst = await billsGuidanceFacade.testItems(data.libID);
            res.json({error: 0, data: rst, message: ''});
        }
        catch (error){
            res.json({error: 1, data: null, message: error});

        }
    }
}

export default BillsGuideLibController;