
var KeysnType = {
    SealCode: 0,
    Key: 1
};

var signatureJson = {};
import { qzNewUrl } from '@/api'
var serviceUrl = qzNewUrl;

$(function () {
    // load();
})

export function signature(signatureJson, result) {
    var data = {
        'keysn': signatureJson.keysn,
        'scaling': signatureJson.scaling,
        'keysnType': signatureJson.keysnType
    };
    $.ajax({
        async: false,
        type: 'post',
        contentType: 'application/json;charset=utf-8;',
        dataType: 'json',
        data: JSON.stringify(data),
        url: serviceUrl + '/ESCustomApi/esealZhonghuan/signature.do',
        success: function (datas) {
            if (datas.iserror) {
                if (result != undefined) {
                    result(datas);
                }
            } else {
                sessionStorage.setItem('sealImgData', datas.data.sigImgBase64)
                var signatureId = "signature" + Date.parse(new Date());
                var imghtml =
                    '<div name="signatureNew"  id="' + signatureId + '" style="position:absolute;z-index: 1999; width:' + datas.data.w + 'px;height:' + datas.data.h + 'px;"> ' +
                    ' <div id=SigImg' + signatureId
                    + '></div><div style="width:' + datas.data.w + 'px;opacity: 0.7;height:' + datas.data.h + 'px;text-align:center;display:none;" id="menu_' +
                    + '"> </div></div> ';
                console.log(document.getElementById(signatureJson.position).getBoundingClientRect())

                // $("#" + signatureJson.position).append(imghtml);
                $("#" + signatureJson.position).html(imghtml);
                $("#" + signatureJson.position).css('display', "block");
                // moveDiv(signatureId);

                var canvasList = document.getElementById("SigImg" + signatureId);
                var canvas = document.createElement('canvas');
                var ctx = canvas.getContext('2d')
                canvasList.appendChild(canvas);
                canvas.width = datas.data.w;
                canvas.height = datas.data.h;
                canvas.oncontextmenu = function (event) {
                    return false;//屏蔽浏览器自带的右键菜单
                };
                var image = new Image();
                image.src = "data:image/png;base64," + datas.data.sigImgBase64;
                $(image).load(function () {
                    ctx.drawImage(image, 0, 0);
                })


                // var canvasList_menu = document.getElementById("menu_" + signatureId);
                // var canvas_menu = document.createElement('canvas');
                // var ctx_menu = canvas_menu.getContext('2d')
                // canvasList_menu.appendChild(canvas_menu);
                // canvas_menu.width = datas.data.w;
                // canvas_menu.height = "30";      //datas.data.h
                // ctx_menu.fillStyle = 'red';

                // canvas_menu.oncontextmenu = function (event) {
                //     return false;//屏蔽浏览器自带的右键菜单
                // };
                // canvas_menu.onclick = function (event) {

                //     var x = event.offsetX;
                //     var y = event.offsetY;
                //     if (x >= ((datas.data.w / 2) - 15) && x <= ((datas.data.w / 2) + 15)) {
                //         delSig(signatureId);
                //     }
                // };

                // var image_menu = new Image();

                // image_menu.src = "./img/del.png";
                // image_menu.id = "yan" + signatureId;
                // $(image_menu).load(function () {
                //     ctx_menu.drawImage(image_menu, (datas.data.w / 2) - 15, 0, 30, 30);
                // })
            }
        }
    })
}

export function preservSignature(signatureJson, result, value) {
    console.log('success')
    console.log(signatureJson)
    // debugger
    var protectedarr = [];
    // handleChildren();

    for (var i = 0; i < signatureJson.protectedItems.length; i++) {
        if (typeof ($("#" + signatureJson.protectedItems[i]).html()) == "undefined") {
            console.error("缺少保护项" + signatureJson.protectedItems[i]);
            return;
        }
        var SignaturejsoHtml = strTransformation($("#" + signatureJson.protectedItems[i]).html())
        var protectedarrJson = {};

        protectedarrJson.name = signatureJson.protectedItems[i];
        protectedarrJson.content = SignaturejsoHtml;
        protectedarrJson.textContent = $("#" + signatureJson.protectedItems[i]).text();
        protectedarr.push(protectedarrJson);
    }
    var protectedarrStr = JSON.stringify(protectedarr);

    var copposition = document.getElementById(signatureJson.position);


    if ($("[name='signatureNew']").length == 0) {
        alert("当前无章可保存!");
    }
    console.log(($("[name='signatureNew']")))
    $($("[name='signatureNew']")).each(function () {
        // var odiv = document.getElementById($(this).attr("id"));

        // var margintop = odiv.getBoundingCli/entRect().top - copposition.getBoundingClientRect().top;
        // var marginleft = odiv.getBoundingClientRect().left - copposition.getBoundingClientRect().left;
        $.ajax({
            type: 'post',
            contentType: 'application/json;charset=utf-8;',
            dataType: 'json',
            data: JSON.stringify(
                {
                    protectedarr: protectedarrStr,
                    marginTop: 0,
                    marginLeft: 0,
                    keysn: signatureJson.keysn,
                    keysnType: signatureJson.keysnType,
                    signPassword: signatureJson.signPassword,
                    scaling: signatureJson.scaling,
                    documentId: signatureJson.documentId,
                    leftX: "0px",
                    leftY: "0px",
                }
            ),
            url: serviceUrl + '/ESCustomApi/esealZhonghuan/preservSignature.do',
            success: function (datas) {
                // if (result != undefined) {
                //     result(datas);
                // }
                if (datas.iserror == true) {
                    sessionStorage.setItem('sealFlag', 0)
                    sessionStorage.setItem('sealFlagMes', datas.message)
                } else {
                    sessionStorage.setItem('sealFlag', 1)

                }

                // return datas
                // load();
            }
        })

    })

}

export function signatureOnload(sealId, sigImgBase64) {
    var signatureId = "signature" + Date.parse(new Date()) + sealId;
    var imghtml =
        '<div name="signatureNew"  id="' + signatureId + '" style="position:absolute;z-index: 1999; "> ' +
        ' <div id=SigImg' + signatureId
        + '></div><div style="text-align:center;display:none;" id="menu_' +
        + '"> </div></div> ';
    console.log(document.getElementById(sealId).getBoundingClientRect())
    // $("#" + sealId).append(imghtml);
    // console.log(sealId, 'sealId')
    $("#" + sealId).html(imghtml);
    // console.log($("#" + sealId), 'sealId')
    $("#" + sealId).css('display', "block");
    // moveDiv(signatureId);

    var canvasList = document.getElementById("SigImg" + signatureId);
    var canvas = document.createElement('canvas');
    var ctx = canvas.getContext('2d')
    canvasList.appendChild(canvas);
    canvas.oncontextmenu = function (event) {
        return false;//屏蔽浏览器自带的右键菜单
    };
    var image = new Image();
    image.src = "data:image/png;base64," + sigImgBase64;
    $(image).load(function () {
        ctx.drawImage(image, 0, 0);
    })
}

function delSig(id) {
    $("#" + id).remove();
}

function moveDiv(id) {
    var $div = $("div#" + id);
    $div.bind("mousedown", function (event) {
        /* 获取需要拖动节点的坐标 */
        var offset_x = $(this)[0].offsetLeft;//x坐标
        var offset_y = $(this)[0].offsetTop;//y坐标
        /* 获取当前鼠标的坐标 */
        var mouse_x = event.pageX;
        var mouse_y = event.pageY;
        /* 绑定拖动事件 */
        /* 由于拖动时，可能鼠标会移出元素，所以应该使用全局（document）元素 */
        $(document).bind("mousemove", function (ev) {
            /* 计算鼠标移动了的位置 */
            var _x = ev.pageX - mouse_x;
            var _y = ev.pageY - mouse_y;
            /* 设置移动后的元素坐标 */
            var now_x = (offset_x + _x) + "px";
            var now_y = (offset_y + _y) + "px";
            /* 改变目标元素的位置 */
            $div.css({
                top: now_y,
                left: now_x
            });
        });
    });
    /* 当鼠标左键松开，接触事件绑定 */
    $(document).bind("mouseup", function () {
        $(this).unbind("mousemove");
    })
}

function strTransformation(str) {
    if (typeof (str) != "undefined") {
        var re = new RegExp("<", "g");
        str = str.replace(re, "#AYY001#");

        re = new RegExp(">", "g");
        str = str.replace(re, "#AYY002#");

        re = new RegExp("/", "g");
        str = str.replace(re, "#AYY003#");

        re = new RegExp("&", "g");
        str = str.replace(re, "#AYY004#");
        return str;
    } else {
        return "";
    }
}

// function handleChildren() {
//     $("input").each(function () {
//         $(this).attr("value", $(this).val());
//     });
//     $("textarea").each(function () {
//         $(this).text($(this).val());
//     });
// }

