/**
 * Created by chen on 2017/8/16.
 */
/**
 * Created by zhang on 2017/8/14.
 */

const pdf = require('pdfkit');
const PDF_SCALE = 0.75;
const fs = require('fs');
const jpcCmnHelper = require('../rpt_component/helper/jpc_helper_common');
const DPI = jpcCmnHelper.getScreenDPI()[0] * PDF_SCALE;
const JV = require('../rpt_component/jpc_value_define');
const uuidV1 = require('uuid/v1');

let fontUtil = require('./rpt_font_util');

// 目前不支持下划线

module.exports = {
    export_pdf_file:export_pdf_file
}

function export_pdf_file (pageData, paperSize, fName, callback) {
    let offsetX= 10;
    let offsetY=10;
    let doc = new pdf({autoFirstPage: false});
    // let newName = '' + (new Date()).valueOf();
    let newName = uuidV1();
    let stream = doc.pipe(fs.createWriteStream(__dirname.slice(0, __dirname.length - 21) + '/tmp/'+newName+'.pdf'));
    let pageObj = pageData;
    // doc.rect(5,5,1190,890).lineWidth(1).strokeColor('black').stroke();//边框
    let paperSizeIdx = JV.PAGES_SIZE_STR.indexOf(paperSize);
    let size = JV.PAGES_SIZE[paperSizeIdx];

    function private_getIniPageMergeBorder(mergedBand) {
        let rst = {};
        rst[JV.PROP_LEFT] = mergedBand[JV.PROP_LEFT];
        rst[JV.PROP_RIGHT] = mergedBand[JV.PROP_RIGHT];
        rst[JV.PROP_TOP] = mergedBand[JV.PROP_TOP];
        rst[JV.PROP_BOTTOM] = mergedBand[JV.PROP_BOTTOM];
        rst[JV.PROP_STYLE] = mergedBand[JV.PROP_STYLE];
        return rst;
    }

    let newPageMergeBand = private_getIniPageMergeBorder(pageObj[JV.BAND_PROP_MERGE_BAND]);
    if (pageObj && pageObj.items.length > 0 ) {
        for(let i=0;i<pageObj.items.length;i++){
            if (pageData[JV.NODE_PAGE_INFO][JV.NODE_PAGE_SIZE][0] > pageData[JV.NODE_PAGE_INFO][JV.NODE_PAGE_SIZE][1]) {
                doc.addPage({size:[size[1]*DPI,size[0]*DPI]});
            } else {
                doc.addPage({size:[size[0]*DPI,size[1]*DPI]});
            }
            let page = pageObj.items[i],
                fonts = pageObj[JV.NODE_FONT_COLLECTION],
                styles = pageObj[JV.NODE_STYLE_COLLECTION],
                controls = pageObj[JV.NODE_CONTROL_COLLECTION];

            if (page[JV.PROP_PAGE_MERGE_BORDER]) {
                newPageMergeBand[JV.PROP_LEFT] = page[JV.PROP_PAGE_MERGE_BORDER][JV.PROP_LEFT];
                newPageMergeBand[JV.PROP_RIGHT] = page[JV.PROP_PAGE_MERGE_BORDER][JV.PROP_RIGHT];
                newPageMergeBand[JV.PROP_TOP] = page[JV.PROP_PAGE_MERGE_BORDER][JV.PROP_TOP];
                newPageMergeBand[JV.PROP_BOTTOM] = page[JV.PROP_PAGE_MERGE_BORDER][JV.PROP_BOTTOM];
            }
            for (let j = 0; j < page.cells.length; j++) {
                let cell = page.cells[j];
                private_drawCell(cell, fonts, styles, controls, newPageMergeBand);
            }
        }
    }
    doc.end();
    stream.on('finish',function () {
        console.log(newName + ".pdf was written.");
        callback(newName);
    });

    function private_chkIfInMergedBand(mergedBand, cell) {
        let rst = false;
        if (mergedBand && cell) {
            rst = mergedBand[JV.PROP_TOP] <= cell[JV.PROP_AREA][JV.PROP_TOP] && mergedBand[JV.PROP_BOTTOM] >= cell[JV.PROP_AREA][JV.PROP_BOTTOM] &&
                mergedBand[JV.PROP_LEFT] <= cell[JV.PROP_AREA][JV.PROP_LEFT] && mergedBand[JV.PROP_RIGHT] >= cell[JV.PROP_AREA][JV.PROP_RIGHT];
        }
        return rst;
    }

    function private_drawCell(cell, fonts, styles, controls, mergedBand) {
        doc.save();
        // doc.translate(0.5,0.5); //跟H5的canvas不同，不需要这样切换
        let style = styles[cell[JV.PROP_STYLE]];
        if (style) {
            let isNeedMergeBand = private_chkIfInMergedBand(mergedBand, cell);
            private_drawLine(cell, doc, style, JV.PROP_TOP, [JV.PROP_LEFT, JV.PROP_TOP],[JV.PROP_RIGHT, JV.PROP_TOP], mergedBand, styles, isNeedMergeBand);
            private_drawLine(cell, doc, style, JV.PROP_RIGHT, [JV.PROP_RIGHT, JV.PROP_TOP],[JV.PROP_RIGHT, JV.PROP_BOTTOM], mergedBand, styles, isNeedMergeBand);
            private_drawLine(cell, doc, style, JV.PROP_BOTTOM, [JV.PROP_RIGHT, JV.PROP_BOTTOM],[JV.PROP_LEFT, JV.PROP_BOTTOM], mergedBand, styles, isNeedMergeBand);
            private_drawLine(cell, doc, style, JV.PROP_LEFT, [JV.PROP_LEFT, JV.PROP_BOTTOM],[JV.PROP_LEFT, JV.PROP_TOP], mergedBand, styles, isNeedMergeBand);
        }
        private_drawCellText(cell, fonts, controls);
        doc.restore();

    }

    function private_drawLine(cell, doc, style, styleBorderDest, startP, destP, mergedBand, styles, isNeedMergeBand) {
        //doc.beginPath();
        let destStyle = style;
        if (mergedBand) {
            if (isNeedMergeBand && parseFloat(mergedBand[styleBorderDest]) === parseFloat(cell[JV.PROP_AREA][styleBorderDest])) {
                destStyle = styles[mergedBand[JV.PROP_STYLE][JV.PROP_ID]];
            }
        }
        // doc.moveTo(cell[JV.PROP_AREA][startP[0]] + offsetX, cell[JV.PROP_AREA][startP[1]] + offsetY);
        doc.moveTo( (cell[JV.PROP_AREA][startP[0]] + offsetX) * PDF_SCALE, (cell[JV.PROP_AREA][startP[1]] + offsetY) * PDF_SCALE);
        if (destStyle[styleBorderDest] && parseFloat(destStyle[styleBorderDest][JV.PROP_LINE_WEIGHT]) !== 0) {
            doc.lineWidth(1.0 * destStyle[styleBorderDest][JV.PROP_LINE_WEIGHT]);
            // doc.lineTo(cell[JV.PROP_AREA][destP[0]] + offsetX, cell[JV.PROP_AREA][destP[1]] + offsetY);
            doc.lineTo((cell[JV.PROP_AREA][destP[0]] + offsetX) * PDF_SCALE, (cell[JV.PROP_AREA][destP[1]] + offsetY) * PDF_SCALE);
            doc.strokeColor(destStyle[styleBorderDest][JV.PROP_COLOR]);
        }
        doc.stroke();
    }
    function private_drawCellText(cell, fonts, controls) {
        if (cell[JV.PROP_VALUE]) {
            let values = ("" + cell[JV.PROP_VALUE]).split('|');
            // let font = fonts[cell[JV.PROP_FONT]];
            let font = null;
            if (typeof cell[JV.PROP_FONT] === "string") {
                font = fonts[cell[JV.PROP_FONT]];
            } else {
                font = cell[JV.PROP_FONT];
            }
            // let control = controls[cell[JV.PROP_CONTROL]];
            let control = null;
            if (typeof cell[JV.PROP_CONTROL] === "string") {
                control = controls[cell[JV.PROP_CONTROL]];
            } else {
                control = cell[JV.PROP_CONTROL];
            }
            let height = cell[JV.PROP_AREA][JV.PROP_BOTTOM] - cell[JV.PROP_AREA][JV.PROP_TOP];
            let area = [cell[JV.PROP_AREA][JV.PROP_LEFT] + offsetX, cell[JV.PROP_AREA][JV.PROP_TOP] + offsetY, cell[JV.PROP_AREA][JV.PROP_RIGHT] + offsetX, cell[JV.PROP_AREA][JV.PROP_BOTTOM] + offsetY];
            let ah = height;
            let restTopH = 0, restBottomH = 0;
            if (control[JV.CONTROL_PROPS[JV.CONTROL_PROP_IDX_CLOSE_OUTPUT]] === 'T') {
                ah = (parseFloat(font[JV.FONT_PROPS[1]]) + JV.OUTPUT_OFFSET[JV.OFFSET_IDX_TOP] + JV.OUTPUT_OFFSET[JV.OFFSET_IDX_BOTTOM]) * values.length;
                let restH = height - ah;
                if (control[JV.CONTROL_PROPS[JV.CONTROL_PROP_IDX_VERTICAL]] === 'center') {
                    restTopH = restH / 2;
                    restBottomH = restH / 2;
                } else if (control[JV.CONTROL_PROPS[JV.CONTROL_PROP_IDX_VERTICAL]] === 'bottom') {
                    restBottomH = restH;
                } else {
                    restTopH = restH;
                }
            }
            let spaceIdxArr = [];
            for (let i = 0; i < values.length; i++) {
                // area[JV.IDX_TOP] = cell[JV.PROP_AREA][JV.PROP_TOP] + i * (height / values.length) + offsetY;
                // area[JV.IDX_BOTTOM] = cell[JV.PROP_AREA][JV.PROP_TOP] + (i + 1) * (height / values.length) + offsetY;
                area[JV.IDX_TOP] = cell[JV.PROP_AREA][JV.PROP_TOP] + i * (ah / values.length) + offsetY + restTopH;
                area[JV.IDX_BOTTOM] = cell[JV.PROP_AREA][JV.PROP_TOP] + (i + 1) * (ah / values.length) + offsetY + restBottomH;
                if (values[i] === null || values[i] === undefined || values[i] === 'null') {
                    values[i] = "";
                }
                // 因pdfkit输出空格只有一半宽度，需要额外加空格补上 -----------------------------
                if (typeof(values[i]) === "string") {
                    for (let j = 0; j < values[i].length; j++) {
                        if (values[i][j] === ' ') spaceIdxArr.push(j);
                    }
                }
                for (let j = spaceIdxArr.length - 1; j >= 0; j--) {
                    values[i] = values[i].slice(0, spaceIdxArr[j]) + ' ' + values[i].slice(spaceIdxArr[j]);
                }
                // -----------------------------
                private_drawText(values[i], area, font, control);
                spaceIdxArr = [];
            }
        }
    }

    function private_drawText(val, area, font, control) {
        let dftFontHeight = 12;
        let output = [];
        let fontFile = __dirname + '/pdf_base_files/simkai.ttf';
        if (font) {
            dftFontHeight = 1 * font[JV.FONT_PROPS[1]];
            fontFile = __dirname + '/pdf_base_files/' + fontUtil.getActualFont(font[JV.FONT_PROPS[0]], (font[JV.FONT_PROPS[3]] === 'T'), (font[JV.FONT_PROPS[4]] === 'T')) + '.ttf';
            doc.fontSize(dftFontHeight);
        }
        doc.font(fontFile);
        let options={};
        let inner_setupControl = function (inArea, inFontHeight, inOutput) {
            if (control) {
                private_setupAreaH(inArea, control.Horizon, font.FontAngle, inFontHeight, inOutput, options);
                private_setupAreaV(inArea, control.Vertical, font.FontAngle, inFontHeight, inOutput);
            } else {
                private_setupAreaH(inArea, "left", parseInt(font.FontAngle), inFontHeight, inOutput, options);
                private_setupAreaV(inArea, "bottom", parseInt(font.FontAngle), inFontHeight, inOutput);
            }
        };
        inner_setupControl(area, dftFontHeight, output);
        let validAreaTxtWidth = area[JV.IDX_RIGHT] - JV.OUTPUT_OFFSET[JV.OFFSET_IDX_RIGHT] - area[JV.IDX_LEFT] - JV.OUTPUT_OFFSET[JV.OFFSET_IDX_RIGHT];
        let validTxtLines = Math.floor((area[JV.IDX_BOTTOM] - area[JV.IDX_TOP]) / (dftFontHeight + JV.OUTPUT_OFFSET[JV.OFFSET_IDX_BOTTOM] + JV.OUTPUT_OFFSET[JV.OFFSET_IDX_TOP] + 4));
        if (parseInt(font.FontAngle) !== 0) {
            validAreaTxtWidth = area[JV.IDX_BOTTOM] - JV.OUTPUT_OFFSET[JV.OFFSET_IDX_BOTTOM] - area[JV.IDX_TOP] - JV.OUTPUT_OFFSET[JV.OFFSET_IDX_TOP];
            validTxtLines = Math.floor((area[JV.IDX_RIGHT] - area[JV.IDX_LEFT]) / (dftFontHeight + JV.OUTPUT_OFFSET[JV.OFFSET_IDX_RIGHT] + JV.OUTPUT_OFFSET[JV.OFFSET_IDX_LEFT] + 4));
        }

        function private_drawUnderline(underLineVal, underLineArea) {
            //A. 暂不支持角度; B. PDF输出时，坐标没有translate
            let ctx = doc;
            //1. 计算下划线的相关坐标
            let width = ctx.widthOfString(underLineVal);
            if (width > underLineArea[JV.IDX_RIGHT] - underLineArea[JV.IDX_LEFT]) {
                width = underLineArea[JV.IDX_RIGHT] - underLineArea[JV.IDX_LEFT];
            }
            let height = dftFontHeight;
            let startX = underLineArea[JV.IDX_LEFT], startY = underLineArea[JV.IDX_TOP], endX = underLineArea[JV.IDX_RIGHT], endY = underLineArea[JV.IDX_BOTTOM];
            // let startX = 0, startY = 0, endX = width, endY = startY;
            if (control.Horizon === "left") {
                startX = Math.round(underLineArea[JV.IDX_LEFT] + JV.OUTPUT_OFFSET[JV.IDX_LEFT]);
            } else if (control.Horizon === "right") {
                startX = Math.round(underLineArea[JV.IDX_RIGHT] - width - JV.OUTPUT_OFFSET[JV.IDX_RIGHT]);
            } else {
                startX = Math.round( underLineArea[JV.IDX_LEFT] + (underLineArea[JV.IDX_RIGHT] - underLineArea[JV.IDX_LEFT] - width) / 2);
            }
            endX = Math.round(startX + width);

            if (control.Vertical === "top") {
                startY = Math.round(underLineArea[JV.IDX_TOP] + JV.OUTPUT_OFFSET[JV.IDX_TOP] + JV.OUTPUT_OFFSET[JV.IDX_BOTTOM] + height);
            } else if (control.Vertical === "bottom") {
                startY = Math.round(underLineArea[JV.IDX_BOTTOM] + JV.OUTPUT_OFFSET[JV.IDX_BOTTOM]);
            } else {
                startY = Math.round( underLineArea[JV.IDX_TOP] + (underLineArea[JV.IDX_BOTTOM] - underLineArea[JV.IDX_TOP] + height) / 2) + JV.OUTPUT_OFFSET[JV.IDX_TOP] + JV.OUTPUT_OFFSET[JV.IDX_BOTTOM];
            }
            endY = Math.round(startY);
            //2. 画线
            // ctx.save();
            if ( output[1] !== Math.round(output[1])) {
                ctx.translate(0,0.5);
            }
            // ctx.beginPath();
            // ctx.moveTo(startX, startY);
            ctx.moveTo(startX * PDF_SCALE, startY * PDF_SCALE);
            ctx.lineWidth(1);
            ctx.strokeStyle = "BLACK";
            // ctx.lineTo(endX, endY);
            ctx.lineTo(endX * PDF_SCALE, endY * PDF_SCALE);
            ctx.stroke();
            // ctx.restore();
        }

        let rotateOptions;
        // if (font[JV.FONT_PROPS[5]] === 'T' && parseInt(font.FontAngle) === 0) {
        //     private_drawUnderline(val);
        // }
        if (parseInt(font.FontAngle) !== 0) {
            if (control){
                rotateOptions = private_setupAreaRotateOption(area,validAreaTxtWidth,control.Vertical,dftFontHeight, output);
            } else {
                rotateOptions = private_setupAreaRotateOption(area,validAreaTxtWidth,"bottom",dftFontHeight, output);
            }
            doc.rotate(font.FontAngle,rotateOptions);
        }
        if (validAreaTxtWidth >= doc.widthOfString(val) ||
            (control && control.Shrink !== 'T' && validTxtLines < private_splitString(val, validAreaTxtWidth, doc)) ) {
            options.width = validAreaTxtWidth * PDF_SCALE;
            options.height = dftFontHeight * PDF_SCALE;
            doc.fontSize(dftFontHeight);
            if (font[JV.FONT_PROPS[5]] === 'T' && parseInt(font.FontAngle) === 0) {
                private_drawUnderline(val, area);
            }
            doc.fontSize(dftFontHeight * PDF_SCALE);
            doc.text(val,output[0] * PDF_SCALE, output[1] * PDF_SCALE, options);
            doc.font(__dirname + '/pdf_base_files/simhei_bold_italic.ttf');
        } else {
            while (true) {
                //*/
                let lines = Math.floor((area[JV.IDX_BOTTOM] - area[JV.IDX_TOP]) / (dftFontHeight + JV.OUTPUT_OFFSET[JV.OFFSET_IDX_BOTTOM] + JV.OUTPUT_OFFSET[JV.OFFSET_IDX_TOP] + 4));
                lines = (lines === 0 || (control.Shrink === 'T' && control.ShrinkFirst === 'T'))?1:lines;
                let actLines = private_splitString(val, validAreaTxtWidth, doc);
                if (actLines.length > lines && dftFontHeight >= 6) {
                    dftFontHeight--;
                    doc.fontSize(dftFontHeight);
                    options.width = validAreaTxtWidth * PDF_SCALE;
                    options.height = dftFontHeight * PDF_SCALE;
                    // doc.text(val,output[0], output[1], options);
                } else {
                    let aH = dftFontHeight + JV.OUTPUT_OFFSET[JV.OFFSET_IDX_BOTTOM] + JV.OUTPUT_OFFSET[JV.OFFSET_IDX_TOP] + 4;
                    if ((aH * actLines.length) < (area[JV.IDX_BOTTOM] - area[JV.IDX_TOP]) && (control && control.Vertical !== 'top')) {
                        if (control.Vertical === 'bottom') {
                            area[JV.IDX_TOP] = area[JV.IDX_BOTTOM] - (aH * actLines.length);
                        } else {
                            area[JV.IDX_TOP] = (area[JV.IDX_TOP] + area[JV.IDX_BOTTOM]) / 2 - (aH * actLines.length) / 2
                            area[JV.IDX_BOTTOM] = area[JV.IDX_TOP] + (aH * actLines.length);
                        }
                    }
                    let newArea = [], baseTop = area[JV.IDX_TOP];
                    for (let ai = 0; ai < area.length; ai++) {
                        newArea[ai] = area[ai];
                    }
                    options.width = validAreaTxtWidth * PDF_SCALE;
                    options.height = dftFontHeight * PDF_SCALE;
                    for (let lIdx = 0; lIdx < actLines.length; lIdx++) {
                        newArea[JV.IDX_TOP] = Math.round(aH * lIdx + baseTop);
                        newArea[JV.IDX_BOTTOM] = Math.round(aH * (lIdx + 1) + baseTop);
                        inner_setupControl(newArea, dftFontHeight, output);
                        doc.fontSize(dftFontHeight);
                        if (font[JV.FONT_PROPS[5]] === 'T' && parseInt(font.FontAngle) === 0) {
                            private_drawUnderline(actLines[lIdx], newArea);
                        }
                        doc.fontSize(dftFontHeight * PDF_SCALE);
                        doc.text(actLines[lIdx], output[0] * PDF_SCALE, output[1] * PDF_SCALE, options);
                    }
                    break;
                }
                /*/
                dftFontHeight--;
                doc.fontSize(dftFontHeight);
                if (validAreaTxtWidth >= doc.widthOfString(val) || dftFontHeight < 6) {
                    options.width = validAreaTxtWidth;
                    options.height = dftFontHeight;
                    doc.text(val,output[0], output[1], options);
                    doc.font(__dirname + '/pdf_base_files/simhei_bold_italic.ttf');
                    break;
                }
                //*/
            }
        }
        // doc.text(val,output[0], output[1], options);
        doc.font(__dirname + '/pdf_base_files/simhei_bold_italic.ttf');
        // doc.restore();
    }

    function private_setupAreaH(area, type, fontAngle, dftFontHeight, outputPoint,options) {
        let lType = type;
        if (type !== "left" && type !== "right" && type !== "center") lType = "left";
        options.align=lType;
        outputPoint[0]=1 * area[JV.IDX_LEFT]+ JV.OUTPUT_OFFSET[JV.OFFSET_IDX_LEFT];
    }

    function private_setupAreaV(area, type, fontAngle, dftFontHeight, outputPoint) {
        let lType = type;
        if (type !== "top" && type !== "bottom" && type !== "center") lType = "top";
        switch (lType) {
            case "top":
                outputPoint[1] = 1 * area[JV.IDX_TOP] + JV.OUTPUT_OFFSET[JV.OFFSET_IDX_TOP];
                break;
            case "bottom":
                outputPoint[1] = 1 * area[JV.IDX_BOTTOM] - JV.OUTPUT_OFFSET[JV.OFFSET_IDX_BOTTOM]-dftFontHeight;
                break;
            case "center":
                outputPoint[1] = 1 * area[JV.IDX_TOP] + (1 * area[JV.IDX_BOTTOM]-1 * area[JV.IDX_TOP]- dftFontHeight) / 2;
                break;
        }
    }

    function private_splitString(strVal, areaWidth, doc) {
        let rst = [];
        if (strVal) {
            let preSIdx = 0, txtWidth = 0;
            let currentW = 0;
            let chnW = doc.widthOfString('一'), otherW = doc.widthOfString('_');
            for (let sIdx = 0; sIdx < strVal.length; sIdx++) {
                currentW = (strVal.charCodeAt(sIdx) > 127)?chnW:otherW;
                txtWidth += currentW;
                if (txtWidth > areaWidth) {
                    if (preSIdx < sIdx) {
                        rst.push(strVal.substr(preSIdx, sIdx - preSIdx));
                        preSIdx = sIdx;
                    } else {
                        rst.push(strVal.substr(preSIdx, 1));
                        preSIdx = sIdx + 1;
                    }
                    txtWidth = currentW;
                }
                if (sIdx === strVal.length - 1) {
                    rst.push(strVal.substr(preSIdx, strVal.length - preSIdx));
                }
            }
        }
        if (rst.length === 0) rst.push(''); //什么都没有，也得整个空串
        return rst;
    }

    function private_setupAreaRotateOption(area,w, type="top",dftFontHeight,outputPoint){
        let x = (area[JV.IDX_RIGHT] - area[JV.IDX_LEFT])/2+area[JV.IDX_LEFT];
        let y =(area[JV.IDX_BOTTOM] - area[JV.IDX_TOP])/2+ area[JV.IDX_TOP];
        let rotateOptions = {origin:[x,y]};
        let h = area[JV.IDX_RIGHT] - area[JV.IDX_LEFT];
        outputPoint[0]=x-w/2+JV.OUTPUT_OFFSET[JV.OFFSET_IDX_LEFT];
        switch (type) {
            case "top":
                outputPoint[1] = y- h/2+ JV.OUTPUT_OFFSET[JV.OFFSET_IDX_TOP];
                break;
            case "bottom":
                outputPoint[1] = y+ h/2-JV.OUTPUT_OFFSET[JV.OFFSET_IDX_BOTTOM]-dftFontHeight;
                break;
            case "center":
                outputPoint[1] = y+dftFontHeight/2;
                break;
        }
        return rotateOptions;
    }

}