/**
 * Created by Tony on 2018/6/27.
 * 报表直接打印需要
 */

let JV = require('../rpt_component/jpc_value_define');
let pdf = require('pdfkit');
let jpcCmnHelper = require('../rpt_component/helper/jpc_helper_common');
let SCREEN_DPI = jpcCmnHelper.getScreenDPI();
let fontUtil = require('./rpt_font_util');

module.exports = {
    exportSvgStr: function (pagesData, offsetX, offsetY) {
        let rst = [];
        let styles = pagesData[JV.NODE_STYLE_COLLECTION],
            fonts = pagesData[JV.NODE_FONT_COLLECTION],
            controls = pagesData[JV.NODE_CONTROL_COLLECTION]
        ;
        let pdf_doc = new pdf({autoFirstPage: false});
        for (let idx = 0; idx < pagesData.items.length; idx++) {
            let page = pagesData.items[idx];
            let svgPageArr = [], pixelSize = getPixelSize(pagesData);
            svgPageArr.push("<svg width='" + pixelSize[0] + "' height='" + pixelSize[1] + "'>");
            let adjustY = 0.5 * ((idx + 1) % 2);
            // let cnt = 0;
            for (let cell of page.cells) {
                svgPageArr.push(buildCellSvg(cell, fonts, styles, controls, page[JV.PROP_PAGE_MERGE_BORDER], pagesData[JV.BAND_PROP_MERGE_BAND], offsetX, offsetY, adjustY, pdf_doc));
                // cnt++;
                // console.log(cnt);
            }
            svgPageArr.push("</svg>");
            rst.push(svgPageArr);
        }
        return rst;
    }
}

function getActualBorderStyle(cell, styles, mergeBorderStyle, pageBorderArea, borderStr) {
    let rst = styles[cell[JV.PROP_STYLE]][borderStr];
    if (mergeBorderStyle) {
        if (parseFloat(cell[JV.PROP_AREA][borderStr]) === parseFloat(pageBorderArea[borderStr])) {
            if (borderStr === JV.PROP_LEFT || borderStr === JV.PROP_RIGHT) {
                if (parseFloat(cell[JV.PROP_AREA][JV.PROP_TOP]) >= parseFloat(pageBorderArea[JV.PROP_TOP]) &&
                    parseFloat(cell[JV.PROP_AREA][JV.PROP_BOTTOM]) <= parseFloat(pageBorderArea[JV.PROP_BOTTOM])) {
                    rst = mergeBorderStyle[borderStr];
                }
            } else if (borderStr === JV.PROP_TOP || borderStr === JV.PROP_BOTTOM) {
                if (parseFloat(cell[JV.PROP_AREA][JV.PROP_LEFT]) >= parseFloat(pageBorderArea[JV.PROP_LEFT]) &&
                    parseFloat(cell[JV.PROP_AREA][JV.PROP_RIGHT]) <= parseFloat(pageBorderArea[JV.PROP_RIGHT])) {
                    rst = mergeBorderStyle[borderStr];
                }
            }
        }
    }
    return rst;
}

function buildCellSvg(cell, fonts, styles, controls, pageMergeBorder, rptMergeBorder, offsetX, offsetY, adjustY, pdf_doc) {
    let rst = [];
    let style = styles[cell[JV.PROP_STYLE]];
    let mergeBandStyle = null;
    if (rptMergeBorder) {
        mergeBandStyle = styles[rptMergeBorder[JV.PROP_STYLE][JV.PROP_ID]];
    }
    let font = cell[JV.PROP_FONT];
    if (typeof font === 'string') {
        font = fonts[cell[JV.PROP_FONT]];
    }
    let left = parseInt(cell[JV.PROP_AREA][JV.PROP_LEFT]) + offsetX + 0.5,
        right = parseInt(cell[JV.PROP_AREA][JV.PROP_RIGHT]) + offsetX + 0.5,
        top = parseInt(cell[JV.PROP_AREA][JV.PROP_TOP]) + offsetY + adjustY,
        bottom = parseInt(cell[JV.PROP_AREA][JV.PROP_BOTTOM]) + offsetY + adjustY
    ;
    if (style) {
        let leftBS = getActualBorderStyle(cell, styles, mergeBandStyle, (pageMergeBorder)?pageMergeBorder:rptMergeBorder[JV.PROP_AREA], JV.PROP_LEFT);
        // if (style[JV.PROP_LEFT] && parseFloat(style[JV.PROP_LEFT][JV.PROP_LINE_WEIGHT]) > 0) {
        if (leftBS && parseFloat(leftBS[JV.PROP_LINE_WEIGHT]) > 0) {
            rst.push("<line x1='" + left + "' y1='" + top +
                "' x2='" + left + "' y2='" + bottom +
                "' style='stroke:rgb(0,0,0);stroke-width:" + leftBS[JV.PROP_LINE_WEIGHT] +"'/>")
        }
        let rightBS = getActualBorderStyle(cell, styles, mergeBandStyle, (pageMergeBorder)?pageMergeBorder:rptMergeBorder[JV.PROP_AREA], JV.PROP_RIGHT);
        // if (style[JV.PROP_RIGHT] && parseFloat(style[JV.PROP_RIGHT][JV.PROP_LINE_WEIGHT]) > 0) {
        if (rightBS && parseFloat(rightBS[JV.PROP_LINE_WEIGHT]) > 0) {
            rst.push("<line x1='" + right + "' y1='" + top +
                "' x2='" + right + "' y2='" + bottom +
                "' style='stroke:rgb(0,0,0);stroke-width:" + rightBS[JV.PROP_LINE_WEIGHT] +"'/>")
        }
        let topBS = getActualBorderStyle(cell, styles, mergeBandStyle, (pageMergeBorder)?pageMergeBorder:rptMergeBorder[JV.PROP_AREA], JV.PROP_TOP);
        // if (style[JV.PROP_TOP] && parseFloat(style[JV.PROP_TOP][JV.PROP_LINE_WEIGHT]) > 0) {
        if (topBS && parseFloat(topBS[JV.PROP_LINE_WEIGHT]) > 0) {
            rst.push("<line x1='" + left + "' y1='" + top +
                "' x2='" + right + "' y2='" + top +
                "' style='stroke:rgb(0,0,0);stroke-width:" + topBS[JV.PROP_LINE_WEIGHT] +"'/>")
        }
        let bottomBS = getActualBorderStyle(cell, styles, mergeBandStyle, (pageMergeBorder)?pageMergeBorder:rptMergeBorder[JV.PROP_AREA], JV.PROP_BOTTOM);
        // if (style[JV.PROP_BOTTOM] && parseFloat(style[JV.PROP_BOTTOM][JV.PROP_LINE_WEIGHT]) > 0) {
        if (bottomBS && parseFloat(bottomBS[JV.PROP_LINE_WEIGHT]) > 0) {
            rst.push("<line x1='" + left + "' y1='" + bottom +
                "' x2='" + right + "' y2='" + bottom +
                "' style='stroke:rgb(0,0,0);stroke-width:" + bottomBS[JV.PROP_LINE_WEIGHT] +"'/>")
        }
    }
    buildText(rst, cell, font, controls[cell[JV.PROP_CONTROL]], offsetX, offsetY, adjustY, pdf_doc);

    return rst.join("");
}

function buildText(destRst, cell, font, control, offsetX, offsetY, adjustY, pdf_doc) {
    let orgFontHeight = parseInt(font[JV.FONT_PROPS[JV.FONT_PROP_IDX_HEIGHT]]);
    let fontWeight = (font[JV.FONT_PROPS[JV.FONT_PROP_IDX_BOLD]] === 'T')?"bold":"normal";
    let fontStyle = (font[JV.FONT_PROPS[JV.FONT_PROP_IDX_ITALIC]] === 'T')?"italic":"normal";
    let dftFontBold = font[JV.FONT_PROPS[3]];
    let dftFontItalic = font[JV.FONT_PROPS[4]];
    let fontFile = __dirname + '/pdf_base_files/' + fontUtil.getActualFont(font[JV.FONT_PROPS[0]], (dftFontBold === 'T'), (dftFontItalic === 'T')) + '.ttf';
    let left = parseInt(cell[JV.PROP_AREA][JV.PROP_LEFT]) + offsetX + 0.5,
        right = parseInt(cell[JV.PROP_AREA][JV.PROP_RIGHT]) + offsetX + 0.5,
        top = parseInt(cell[JV.PROP_AREA][JV.PROP_TOP]) + offsetY + adjustY,
        bottom = parseInt(cell[JV.PROP_AREA][JV.PROP_BOTTOM]) + offsetY + adjustY,
        x = left, y = top,
        text_anchor = "start"
    ;
    let value = cell[JV.PROP_VALUE];
    if (!(value)) {
        value = "";
    }
    let values = null;
    if (typeof value === "string") {
        values = value.split("|");
    } else {
        values = [value];
    }
    let stepHeight = (parseInt(cell[JV.PROP_AREA][JV.PROP_BOTTOM]) - parseInt(cell[JV.PROP_AREA][JV.PROP_TOP])) / values.length;
    if (control) {
        if (control[JV.CONTROL_PROPS[JV.CONTROL_PROP_IDX_HORIZON]] === "left") {
            text_anchor = "start";
            x = left + JV.OUTPUT_OFFSET[JV.OFFSET_IDX_LEFT];
        } else if (control[JV.CONTROL_PROPS[JV.CONTROL_PROP_IDX_HORIZON]] === "right") {
            text_anchor = "end";
            x = right - JV.OUTPUT_OFFSET[JV.OFFSET_IDX_RIGHT];
        } else if (control[JV.CONTROL_PROPS[JV.CONTROL_PROP_IDX_HORIZON]] === "center") {
            text_anchor = "middle";
            x = Math.round((left + right) / 2);
        }
    }
    //*/
    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 inner_draw_text = function (textValue) {
        let dftFontHeight = orgFontHeight;
        pdf_doc.font(fontFile);
        pdf_doc.fontSize(dftFontHeight);
        let actLines = private_splitString(textValue, (area[JV.PROP_RIGHT] - area[JV.PROP_LEFT]), pdf_doc);
        function inner_build_text(innerTxt, innerArea) {
            let innerDftFontHeight = (dftFontHeight * 3 / 4); //SVG的字体与canvas的字体大小的切换, 不用考虑取整
            if (control) {
                if (control[JV.CONTROL_PROPS[JV.CONTROL_PROP_IDX_VERTICAL]] === "top") {
                    y = innerArea[JV.PROP_TOP] + JV.OUTPUT_OFFSET[JV.OFFSET_IDX_TOP];
                } else if (control[JV.CONTROL_PROPS[JV.CONTROL_PROP_IDX_VERTICAL]] === "bottom") {
                    y = innerArea[JV.PROP_BOTTOM] - JV.OUTPUT_OFFSET[JV.OFFSET_IDX_BOTTOM];
                } else if (control[JV.CONTROL_PROPS[JV.CONTROL_PROP_IDX_VERTICAL]] === "center") {
                    y = Math.round((innerArea[JV.PROP_TOP] + innerArea[JV.PROP_BOTTOM] + innerDftFontHeight) / 2 );
                }
            }
            if (font[JV.PROP_NAME] === "宋体") {
                y--;
            }
            destRst.push("<text style='fill:black;font-family:" + font[JV.PROP_NAME] +
                ";font-weight:" + fontWeight +
                ";font-style:" + fontStyle +
                ";font-size:" + innerDftFontHeight + "pt' x='" +
                x +"' y='" + y + "' text-anchor='" + text_anchor + "' xml:space='preserve'>" + innerTxt + "</text>");
        }
        if (actLines.length === 1 || (control && control.Shrink !== 'T')) {
            inner_build_text(textValue, area);
        } else {
            while (true) {
                if (dftFontHeight > 6) {
                    dftFontHeight--;
                    pdf_doc.fontSize(dftFontHeight);
                    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)?1:lines;
                    actLines = private_splitString(textValue, (area[JV.PROP_RIGHT] - area[JV.PROP_LEFT]), pdf_doc);
                    if (lines >= actLines.length) {
                        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];
                        }
                        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_build_text(actLines[lIdx], newArea);
                        }
                        break;
                    }
                } else {
                    inner_build_text(textValue, area);
                    break;
                }
            }
        }
    };
    for (let vidx = 0; vidx < values.length; vidx++) {
        area[JV.IDX_TOP] = cell[JV.PROP_AREA][JV.PROP_TOP] + vidx * (height / values.length);
        area[JV.IDX_BOTTOM] = cell[JV.PROP_AREA][JV.PROP_TOP] + (vidx + 1) * (height / values.length);
        inner_draw_text(values[vidx], area, font, control);
    }
    /*/
    for (let vidx = 0; vidx < values.length; vidx++) {
        //check whether need to adjust the font size
        let dftFontHeight = orgFontHeight;
        pdf_doc.font(fontFile);
        pdf_doc.fontSize(dftFontHeight);
        while ((right - left) <= pdf_doc.widthOfString(values[vidx])) {
            if (dftFontHeight > 6) {
                dftFontHeight--;
                pdf_doc.fontSize(dftFontHeight);
            } else {
                break;
            }
        }
        dftFontHeight = (dftFontHeight * 3 / 4); //SVG的字体与canvas的字体大小的切换, 不用考虑取整
        if (control) {
            if (control[JV.CONTROL_PROPS[JV.CONTROL_PROP_IDX_VERTICAL]] === "top") {
                y = Math.round((top + vidx * stepHeight) + JV.OUTPUT_OFFSET[JV.OFFSET_IDX_TOP]);
            } else if (control[JV.CONTROL_PROPS[JV.CONTROL_PROP_IDX_VERTICAL]] === "bottom") {
                y = Math.round((top + (vidx + 1) * stepHeight) - JV.OUTPUT_OFFSET[JV.OFFSET_IDX_BOTTOM]);
            } else if (control[JV.CONTROL_PROPS[JV.CONTROL_PROP_IDX_VERTICAL]] === "center") {
                y = Math.round(((top + vidx * stepHeight) + (top + (vidx + 1) * stepHeight) + dftFontHeight) / 2 );
            }
        }
        if (font[JV.PROP_NAME] === "宋体") {
            y--;
        }
        destRst.push("<text style='fill:black;font-family:" + font[JV.PROP_NAME] +
            ";font-weight:" + fontWeight +
            ";font-style:" + fontStyle +
            ";font-size:" + dftFontHeight + "pt' x='" +
            x +"' y='" + y + "' text-anchor='" + text_anchor + "' xml:space='preserve'>" + values[vidx] + "</text>");
    }
    //*/
}

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 getPixelSize(pagesData) {
    let rst = [793,1122];
    if (pagesData[JV.NODE_PAGE_INFO] && pagesData[JV.NODE_PAGE_INFO][JV.NODE_PAGE_SIZE]) {
        rst[0] = Math.round(SCREEN_DPI[0] * pagesData[JV.NODE_PAGE_INFO][JV.NODE_PAGE_SIZE][0]);
        rst[1] = Math.round(SCREEN_DPI[1] * pagesData[JV.NODE_PAGE_INFO][JV.NODE_PAGE_SIZE][1]);
    }
    return rst;
}
