/**
 * Created by Tony on 2018/4/24.
 */

let rptPrintHelper = {
    preview: function () {
        if (zTreeOprObj.isFreeUser && !commonUtil.isGLYun()) {//2020-11-25  zhang 公路云版，免费版允许打印、导出报表
            hintBox.versionBox('对不起，您当前使用的是学习版，不提供导出、打印报表功能，请联系我们的客服人员。');
            return;
        }
        if (zTreeOprObj.checkedRptTplNodes && zTreeOprObj.checkedRptTplNodes.length > 0) {
            let refRptTplIds = [], refBillSumPrjsIds = [], refGljSumPrjsIds = [];
            let prj_ids_arr = [];
            rptControlObj.getTplIdsCommon(refRptTplIds, refBillSumPrjsIds, refGljSumPrjsIds, null, null, null, prj_ids_arr);
            let params = rptControlObj.creatCommonExportParam(refRptTplIds, refBillSumPrjsIds, refGljSumPrjsIds);
            params.rpt_ids = refRptTplIds;
            params.prj_ids_arr = prj_ids_arr;
            params.rpt_bill_tpl_ids = refBillSumPrjsIds;
            params.rpt_glj_tpl_ids = refGljSumPrjsIds;
            CommonAjax.postEx("report_api/getMultiReports", params, 10000, true,
                function(result){
                    sessionStorage.multiRptsData = JSON.stringify(result);
                    sessionStorage.pageSize = rptControlObj.getCurrentPageSize();
                    sessionStorage.orientation = rptControlObj.getCurrentOrientation();
                    sessionStorage.scaleFactor = 1;
                    window.open('/printReport/' + sessionStorage.pageSize);
                },
                function(failRst){
                    sessionStorage.currentPageData = null;
                    console.log(failRst);
                },
                function(exceptionRst){
                    sessionStorage.currentPageData = null;
                    console.log(exceptionRst);
                }
            );
        } else {
            //不可能的branch
        }
    },
    buildSvgArr: function (pagesData, actAreaArr, offsetX, offsetY) {
        let styles = pagesData[JV.NODE_STYLE_COLLECTION],
            fonts = pagesData[JV.NODE_FONT_COLLECTION],
            controls = pagesData[JV.NODE_CONTROL_COLLECTION]
        ;
        let rst = [];
        let canvas = document.getElementById("chkCanvas");
        let pixelSize = getPixelSize(pagesData);
        let isHtoV = false;
        if (pixelSize[0] > pixelSize[1]) {
            // changeHtoV(pagesData, pixelSize);
            isHtoV = true;
        }
        for (let idx = 0; idx < pagesData.items.length; idx++) {
            let page = pagesData.items[idx];
            let actAreaOffsetX = 0, actAreaOffsetY = 0;
            if (actAreaArr) {
                actAreaOffsetX = actAreaArr[idx].Left;
                actAreaOffsetY = actAreaArr[idx].Top;
                if (pixelSize[0] > pixelSize[1]) {
                    //引用了padding，这里要处理下了
                }
            }
            let svgPageArr = [];
            // console.log(pixelSize);
            svgPageArr.push("<svg width='" + pixelSize[0] + "' height='" + pixelSize[1] + "'>");
            // let adjustY = 0.5 * ((idx + 1) % 2);
            let adjustY = 0.5;
            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 - actAreaOffsetX, offsetY - actAreaOffsetY, adjustY, canvas, isHtoV, pixelSize, actAreaArr[idx]));
            }
            svgPageArr.push("</svg>");
            rst.push(svgPageArr);
        }
        return rst;
    }
};

function getActualBorderStyle(cell, styles, mergeBorderStyle, pageBorderArea, borderStr) {
    let rst = styles[cell[JV.PROP_STYLE]][borderStr];
    if (rst && parseFloat(rst[JV.PROP_LINE_WEIGHT]) === 1) {
        rst[JV.PROP_LINE_WEIGHT] = 0.5;
    }
    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, canvas, isHtoV, pixelSize, actArea) {
    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
    ;
    let HtoVStr = "";
    if (isHtoV) {
        // HtoVStr = ` transform="translate(`+ (actArea.Bottom - actArea.Top + 5) + `,` + (actArea.Left - actArea.Top ) + `) rotate(90)"`;
        //引用了padding后，top坐标不用考虑offset了
        HtoVStr = ` transform="translate(${(actArea.Bottom - actArea.Top + 2)},0) rotate(90)"`;
    }
    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] + "'" + HtoVStr + "/>")
        }
        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] +"'" + HtoVStr + "/>")
        }
        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] +"'" + HtoVStr + "/>")
        }
        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] +"'" + HtoVStr + "/>")
        }
    }
    let control = cell[JV.PROP_CONTROL];
    if (typeof control === 'string') {
        control = controls[cell[JV.PROP_CONTROL]];
    }
    buildText(rst, cell, font, control, offsetX, offsetY, adjustY, canvas, isHtoV, HtoVStr);

    return rst.join("");
}

function _splitValues(cell, control, orgValues, ctx2D) {
    //根据control的 自动折行 及 缩放优先 这俩属性 来分解cell value
    if (control[JV.CONTROL_PROPS[JV.CONTROL_PROP_IDX_WRAP]] === 'T' && control[JV.CONTROL_PROPS[JV.CONTROL_PROP_IDX_SHRINK_FIRST]] !== 'T') {
        let vals = [];
        let validAreaTxtWidth = cell[JV.PROP_AREA][JV.PROP_RIGHT] - JV.OUTPUT_OFFSET[JV.OFFSET_IDX_RIGHT] - cell[JV.PROP_AREA][JV.PROP_LEFT] - JV.OUTPUT_OFFSET[JV.OFFSET_IDX_LEFT] - 1;
        for (let val of orgValues) {
            let actW = ctx2D.measureText(val).width;
            if (actW > (validAreaTxtWidth - 4)) {
                //减4个像素是考虑到导出excel的情况
                vals = vals.concat(private_splitString(val, validAreaTxtWidth, ctx2D));
            } else {
                vals.push(val);
            }
        }
        if (vals.length > orgValues.length) {
            for (let idx = 0; idx < vals.length; idx++) {
                orgValues[idx] = vals[idx];
            }
        }
    }
}

const strReplaceReg1 = new RegExp('\n\r', 'gm'),
    strReplaceReg2 = new RegExp('\r\n', 'gm'),
    strReplaceReg3 = new RegExp('\n', 'gm'),
    strReplaceReg4 = new RegExp('\r', 'gm')
;

function _preHandleSpliter(orgVal) {
    let rst = orgVal;
    if (rst !== null && rst !== '') {
        rst = rst.replace(strReplaceReg1, '|').replace(strReplaceReg2, '|').replace(strReplaceReg3, '|').replace(strReplaceReg4, '|');
    }
    return rst;
}

function buildText(destRst, cell, font, control, offsetX, offsetY, adjustY, canvas, isHtoV, HtoVStr) {
    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 fontUnderline = (font[JV.FONT_PROPS[JV.FONT_PROP_IDX_UNDERLINE]] === 'T')?"underline":"normal";
    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 === undefined || value === null) {
        value = "";
    }
    let values = null;
    if (typeof value === "string") {
        // values = value.split("|");
        values = _preHandleSpliter(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 area = [0,0,0,0];
    area[JV.IDX_TOP] = top;
    area[JV.IDX_BOTTOM] = bottom;
    area[JV.IDX_LEFT] = left;
    area[JV.IDX_RIGHT] = right;
    let height = bottom - top;
    let ctx = canvas.getContext("2d");
    ctx.font = ((font[JV.FONT_PROPS[JV.FONT_PROP_IDX_BOLD]] === 'T')?"bold ":"") + ((font[JV.FONT_PROPS[JV.FONT_PROP_IDX_ITALIC]] === 'T')?"italic":"") + orgFontHeight + "px " + font[JV.PROP_NAME];
    _splitValues(cell, control, values, ctx);
    let inner_draw_text = function (textValue) {
        let dftFontHeight = orgFontHeight;
        ctx.font = ((font[JV.FONT_PROPS[JV.FONT_PROP_IDX_BOLD]] === 'T')?"bold ":"") + ((font[JV.FONT_PROPS[JV.FONT_PROP_IDX_ITALIC]] === 'T')?"italic":"") + dftFontHeight + "px " + font[JV.PROP_NAME];
        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.IDX_TOP] + JV.OUTPUT_OFFSET[JV.IDX_TOP];
                } else if (control[JV.CONTROL_PROPS[JV.CONTROL_PROP_IDX_VERTICAL]] === "bottom") {
                    y = innerArea[JV.IDX_BOTTOM] - JV.OUTPUT_OFFSET[JV.IDX_BOTTOM];
                } else if (control[JV.CONTROL_PROPS[JV.CONTROL_PROP_IDX_VERTICAL]] === "center") {
                    y = Math.round((innerArea[JV.IDX_TOP] + innerArea[JV.IDX_BOTTOM] + innerDftFontHeight) / 2 );
                }
            } else {
                y = innerArea[JV.IDX_TOP] + JV.OUTPUT_OFFSET[JV.IDX_TOP];
            }
            if (font[JV.PROP_NAME] === "宋体") {
                y--;
            }
            destRst.push("<text style='fill:black;font-family:" + font[JV.PROP_NAME] +
                ";font-weight:" + fontWeight +
                ";font-style:" + fontStyle +
                ";text-decoration:" + fontUnderline +
                // ";text-decoration:normal" +
                ";font-size:" + innerDftFontHeight + "pt' x='" +
                x +"' y='" + y + "' text-anchor='" + text_anchor + "' xml:space='preserve'" + HtoVStr + ">" + innerTxt + "</text>");
        }
        let actLines = private_splitString(textValue, (area[JV.IDX_RIGHT] - area[JV.IDX_LEFT] - JV.OUTPUT_OFFSET[JV.IDX_LEFT] - JV.OUTPUT_OFFSET[JV.IDX_RIGHT]), ctx);
        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 (actLines.length === 1  || (control && control.Shrink !== 'T' && validTxtLines < actLines)) {
            inner_build_text(textValue, area);
        } else {
            while (true) {
                let lines = Math.floor((area[JV.IDX_BOTTOM] - area[JV.IDX_TOP]) / (dftFontHeight + JV.OUTPUT_OFFSET[JV.IDX_BOTTOM] + JV.OUTPUT_OFFSET[JV.IDX_TOP] + 4));
                lines = (lines === 0 || (control.Shrink === 'T' && control.ShrinkFirst === 'T'))?1:lines;
                actLines = private_splitString(textValue, (area[JV.IDX_RIGHT] - area[JV.IDX_LEFT] - JV.OUTPUT_OFFSET[JV.IDX_LEFT] - JV.OUTPUT_OFFSET[JV.IDX_RIGHT]), ctx);
                if (actLines.length > lines && dftFontHeight >= 6) {
                    dftFontHeight--;
                    ctx.font = ((font[JV.FONT_PROPS[JV.FONT_PROP_IDX_BOLD]] === 'T')?"bold ":"") + ((font[JV.FONT_PROPS[JV.FONT_PROP_IDX_ITALIC]] === 'T')?"italic":"") + dftFontHeight + "px " + font[JV.PROP_NAME];
                } else {
                    let aH = dftFontHeight + JV.OUTPUT_OFFSET[JV.IDX_BOTTOM] + JV.OUTPUT_OFFSET[JV.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;
                }
            }
        }
    };
    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;
    //     }
    // }
    const isCloseOutput = _chkIfCloseOutput(control, values.length, area, orgFontHeight);
    let closeTopOffset = 0;
    if (isCloseOutput) {
        closeTopOffset = (height - (orgFontHeight + 4) * values.length) / 2;
    }
    for (let vidx = 0; vidx < values.length; vidx++) {
        if (isCloseOutput) {
            area[JV.IDX_TOP] = top + closeTopOffset + vidx * (orgFontHeight + 4);
            area[JV.IDX_BOTTOM] = top + closeTopOffset + (vidx + 1) * (orgFontHeight + 4);
        } else {
            area[JV.IDX_TOP] = top + vidx * (ah / values.length) + restTopH;
            area[JV.IDX_BOTTOM] = top + (vidx + 1) * (ah / values.length) + restBottomH;
        }
        inner_draw_text(values[vidx]);
    }
}

function _chkIfCloseOutput(control, actLines, area, fontHeight) {
    let rst = false;
    if (control.CloseOutput === 'T' && actLines > 1) {
        rst = true;
    }
    return rst;
}

function private_splitString(strVal, areaWidth, ctx) {
    let rst = [];
    if (strVal) {
        let preSIdx = 0, txtWidth = 0;
        let currentW = 0;
        let chnW = ctx.measureText('一').width, otherW = ctx.measureText('_').width;
        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];
    let SCREEN_DPI = [96,96];
    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;
}
