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

let rptPrintHelper = {
    preview: async function () {
        if (zTreeOprObj.checkedRptTplNodes && zTreeOprObj.checkedRptTplNodes.length > 0) {
            let rptIds = [], flags = [], compare_ids = [];
            let params = {};
            params.pageSize = rptControlObj.getCurrentPageSize();
            params.orientation = ((zTreeOprObj.checkedRptTplNodes.length > 1)?null:rptControlObj.getCurrentOrientation());
            params.custCfg = zTreeOprObj.reportPageCfg;
            params.prj_id = projectObj.project.projectInfo.ID;
            for (let tplNode of zTreeOprObj.checkedRptTplNodes) {
                rptIds.push(tplNode.refId);
                let flag = null;
                if (tplNode.hasOwnProperty('flags')) {
                    flag = tplNode.flags;
                    params.prj_ids = rptTplObj.getAllPrjIds();
                    if (flag.auditType === 'audit_compare') {
                        let pids = [];
                        let comp_pid = await compareObject.getCompareID(); //返回单个对应的project ID
                        if (comp_pid !== null) {
                            pids.push(projectObj.project.projectInfo.ID);
                            pids.push(comp_pid);
                        }
                        compare_ids.push(pids);
                    } else {
                        compare_ids.push([]);
                    }
                } else {
                    compare_ids.push([]);
                }
                flags.push(flag);
            }
            params.rpt_ids = rptIds.join(",");
            params.compare_ids = compare_ids;
            params.flags = flags;
            CommonAjax.postEx("report_api/getMultiReports", params, 10000, true,
                function(result){
                    //sessionStorage.currentPageData = JSON.stringify(zTreeOprObj.currentRptPageRst);
                    sessionStorage.multiRptsData = JSON.stringify(result);
                    sessionStorage.pageSize = rptControlObj.getCurrentPageSize();
                    sessionStorage.orientation = rptControlObj.getCurrentOrientation();
                    sessionStorage.scaleFactor = 1;
                    window.open('/rpt_print');
                },
                function(failRst){
                    sessionStorage.currentPageData = null;
                    console.log(failRst);
                },
                function(exceptionRst){
                    sessionStorage.currentPageData = null;
                    console.log(exceptionRst);
                }
            );
        } else {
            //不可能的branch
        }
        // if (zTreeOprObj.currentRptPageRst) {
        //     sessionStorage.currentPageData = JSON.stringify(zTreeOprObj.currentRptPageRst);
        //     sessionStorage.pageSize = rptControlObj.getCurrentPageSize();
        //     sessionStorage.orientation = rptControlObj.getCurrentOrientation();
        //     sessionStorage.scaleFactor = 1;
        //     window.open('/rpt_print');
        // } else {
        //     sessionStorage.currentPageData = null;
        // }
    },
    previewSvgData: function() {
        //
    },
    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]) {
                }
            }
            let svgPageArr = [];
            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) + `,0) 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];
        for (let val of orgValues) {
            let actW = ctx2D.measureText(val).width;
            if (actW > validAreaTxtWidth) {
                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];
            }
        }
    }
}

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("|");
    } 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] + orgFontHeight;
                } 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]), 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;
                }
            }
        }
    };
    for (let vidx = 0; vidx < values.length; vidx++) {
        area[JV.IDX_TOP] = top + vidx * (height / values.length);
        area[JV.IDX_BOTTOM] = top + (vidx + 1) * (height / values.length);
        inner_draw_text(values[vidx]);
    }
}

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;
}
