<!DOCTYPE html>
<html lang=zh-cn>
<head>
    <meta charset=utf-8>
    <title>纵横计量支付系统</title>
    <meta name=description content=计量支付>
    <meta name=copyright content=smartcost.com.cn>
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <link rel=stylesheet href="{{rootUrl}}global/css/bootstrap.css">
    <link rel="stylesheet" href="{{rootUrl}}global/css/jquery-ui.min.css">
    <link rel=stylesheet href={{rootUrl}}global/css/style.css?20170821>
    <script src={{rootUrl}}global/js/jquery-1.9.1.min.js></script>
    <script src={{rootUrl}}global/js/bootstrap.js></script>
    <script src={{rootUrl}}global/js/jl.js></script>
    <script src="{{rootUrl}}global/js/jquery-ui.min.js"></script>
</head>
<body>
<!-- include "top" -->
<div class="wrapContent">
    <!-- include "left" -->
    	<div class="mainContainer" style="overflow-y:hidden">
    		<!--内容-->
      <div class="mainContent signContent">
      <div class="title clearfix sign-title-height">
          <input type="hidden" value="{{maxwidth}}" id="imgwidth">
          <input type="hidden" value="{{maxheight}}" id="imgheight">
          <div class="fR sign-topbar">
              <a class="btn btn-primary" style="position: relative" href="javascript:void(0);"><i class="glyphicon glyphicon-upload"></i>上传图片<input type="file" id="addpic" accept="image/gif,image/jpeg,image/jpg,image/png,image/svg" style="position: absolute;opacity: 0;filter: alpha(opacity=0);height: 100%;width: 100%;left: 0; top: 0;cursor: pointer;font-size: 0;" /></a>
              <a class="btn btn-success" data-toggle="modal" onclick="checkpicup();" ><i class="glyphicon glyphicon-ok"></i> 完成草图添加</a>
          </div>
          <form action="/sproject/make/intermediate/{{sid}}" id="gotocurrnum" method="post" onsubmit="return checkcurrnum();">
          <div class="fR sign-page-num">
              <!-- if empty({{lastnum}}) --><a class="btn btn-default btn-sm" disabled="disabled" data-num="{{lastnum}}" data-alog="-1"><!-- else --><a class="btn btn-default btn-sm" href="/sproject/make/intermediate/{{sid}}/page/{{lastnum}}" data-num="{{lastnum}}" data-alog="-1"><!-- endif --><i class="glyphicon glyphicon-chevron-left"></i> 上一页</a>&nbsp;<input value="{{currnum}}" min="1" max="{{totalnum}}" style="width: 50px;vertical-align: bottom;font-size: 16px;height: 30px;" type="number" id="currnum"><input type="submit" hidden/> / <span id="totalnum">{{totalnum}}</span> 页&nbsp;<!-- if empty({{nextnum}}) --><a class="btn btn-default btn-sm" disabled="disabled" data-num="{{nextnum}}" data-alog="1"><!-- else --><a class="btn btn-default btn-sm" href="/sproject/make/intermediate/{{sid}}/page/{{nextnum}}" data-num="{{nextnum}}" data-alog="1"><!-- endif -->下一页 <i class="glyphicon glyphicon-chevron-right"></i></a>
          </div>
          </form>
        <h1><a href="/sproject/{{pid}}/section/{{pmid}}/intermediate" title="返回"><span class="closePanel" aria-hidden="true" data-icon="Z"></span></a>&nbsp;{{name}}</h1>
      </div>
      <div class="sign-view clearfix">
          <div class="sign-content">
              <div class="warp-printer" id="intermediateMake">
                  <div class="page" style="width: {{maxwidth}}px" id="intermediatePage{{currnum}}">
                      <input type="hidden" value="{{currnum}}" id="pagecurrnum">
                      <img src="{{rootUrl}}{{attmsg.filepath}}">
                  </div>
              </div>
          </div>
        </div>
  </div>
        <!--内容-->
    	</div>
    </div>
<!-- 完成添加草图 -->
<div id="done" class="modal fade" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog">
  <div class="modal-content">
    <div class="modal-body">
        <h4>完成后报表不可再修改。</h4>
        <h4>完成草图添加后才可以对该报表发起在线签署。</h4>
        <h4>确认完成草图添加？</h4>
    </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
        <a class="btn btn-success" data-dismiss="modal" data-toggle="modal" href="#up" onclick="allpicupset();">确认完成</a>
      </div>
</div>
</div>
</div>
<!-- 完成添加草图 -->

<!-- 进度条 -->
<div id="up" class="modal fade" tabindex="-1" role="dialog" aria-hidden="true" data-backdrop="static" data-keyboard="false">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-body">
                <h4>正在上传合成图，请不要关闭本页面...</h4>
                <br>
                <h4 id="upmsg">正上传&nbsp;  <span id="upnum" style="color: #5bb75b;">1</span>&nbsp;/&nbsp;{{totalnum}}</h4>
            </div>
        </div>
    </div>
</div>

<!-- 完成签署人弹出 -->
<div id="doneonepic" class="modal fade" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-body">
                <h4 class="text-error">本页存在未保存的草图，请先处理。</h4>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <!--<a class="btn btn-success" href="" id="gourl">确认</a>-->
            </div>
        </div>
    </div>
</div>
<script type="text/javascript">autoFlashHeight();</script>
<!--<script src="{{rootUrl}}global/js/jquery.pjax.js"></script>-->
<!--<script src="http://cdn.bootcss.com/jquery/2.2.0/jquery.min.js"></script>-->
<script src="http://cdn.bootcss.com/jquery.pjax/1.9.6/jquery.pjax.min.js"></script>
<script src="{{rootUrl}}global/js/nprogress.js"></script>
<link rel="stylesheet" href="{{rootUrl}}global/css/nprogress.css">
<script>
    if ($.support.pjax) {
        $(document).on('click', '.sign-page-num a', function(event) {
            //设置页码和翻页按钮
            if(!$(this).attr('disabled')){
                var num = parseInt($(this).attr('data-num'));
                if(checkpicmake()){
                    $.pjax.click(event, {container: '#intermediateMake'});
                    if($(this).attr('data-alog') > 0 && num <= parseInt($('#totalnum').text())){
                        if(num == parseInt($('#totalnum').text())){
                            $(this).attr('disabled',true);
                            $(this).attr('href','javascript:void(0);');
                        }else{
                            var curr = num + 1;
                            $(this).attr('data-num',curr);
                            $(this).attr('disabled',false);
                            $(this).attr('href','/sproject/make/intermediate/{{sid}}/page/'+curr);
                        }
                    }else if($(this).attr('data-alog') < 0 && num >= 1){
                        if(num == 1){
                            $(this).attr('disabled',true);
                            $(this).attr('href','javascript:void(0);');
                        }else{
                            var curr = num - 1;
                            $(this).attr('data-num',curr);
                            $(this).attr('disabled',false);
                            $(this).attr('href','/sproject/make/intermediate/{{sid}}/page/'+curr);
                        }
                    }
                    $(this).siblings('a').attr('data-num',parseInt($('#pagecurrnum').val()));
                    $(this).siblings('a').attr('disabled',false);
                    $(this).siblings('a').attr('href','/sproject/make/intermediate/{{sid}}/page/'+parseInt($('#pagecurrnum').val()));

                    $('#currnum').val(num);

                    setaddpic(parseInt($('#currnum').val()));
                }else{
                    return false;
                }
            }
        });

        $(document).on("pjax:start", function() {
            NProgress.start();
        });

        $(document).on("pjax:end", function() {
            NProgress.done();
        })
    }
    $(function() {
        setaddpic(parseInt($('#pagecurrnum').val()));

        $('#addpic').change(function () {
            for(var i = 0; i < this.files.length; i++){
                var reader = new FileReader();
                reader.readAsDataURL(this.files[i]);
                reader.onload = function(){
                    var objUrl = reader.result;
                    setImgForSign(objUrl);
                }
            }
            $(this).val('');
        });
    });

    function setImgForSign(file){
        var width = 300;
        var height = 150;
        var top = 10;
        var left = 10;
        var img = new Image();

        img.src = file;
        // 定时执行获取宽高
        var check = function(){
            // 只要任何一方大于0
            // 表示已经服务器已经返回宽高
            if(img.width>0 || img.height>0){
                width = img.width;
                height = img.height;
                if(width > parseFloat($('#imgwidth').val())){
                    height = parseFloat(height*parseFloat($('#imgwidth').val())/width);
                    width = parseFloat($('#imgwidth').val());
                    top = 0;
                    left = 0;
                }else if(height > parseFloat($('#imgheight').val())){
                    width = parseFloat(width*parseFloat($('#imgheight').val())/height);
                    height = parseFloat($('#imgheight').val());
                    top = 0;
                    left = 0;
                }
                var zindex = $('.user-sign:last').css('z-index');
                if(typeof(zindex) == 'undefined' || zindex == null){
                    zindex = 900;
                }else{
                    zindex = parseInt(zindex) + 1;
                }
                var html = '<div class="user-sign draggable pic_{{sid}}_'+parseInt($('#pagecurrnum').val())+'" id="pic_{{sid}}_'+parseInt($('#pagecurrnum').val())+'_'+zindex+'" style="display: block;position: absolute;top: '+ top +'%;left: '+ left +'%;z-index: '+ zindex +';width:'+ width +'px; height:'+ height +'px"> <div class="img-bar"> <a href="javascript:void(0);" title="确定" class="sign_confirm" onclick="setct('+zindex+')"><span data-icon="T" aria-hidden="true" class="colGreen"></span></a> <a href="javascript:void(0);" title="删除" class="sign_del" onclick="delct('+zindex+')"><span data-icon="U" aria-hidden="true" class="colRed"></span></a> </div> <div class="focus" style="width:100%; height:100%"> <img src="'+ file +'" style="width:100%; height:100%"> </div> </div>';
                $('#intermediatePage'+parseInt($('#pagecurrnum').val())).append(html);

                setdraggrable();
                clearInterval(set);
            }
        };
        var set = setInterval(check,40);
    }

    function setaddpic(num){
        //获取缓存中的图片内容
        var check = function(){
            var html = '';
            for(var i = 900; i <= 999; i++){
                if(localStorage.hasOwnProperty('picbase64_{{sid}}_'+num+'_'+i)){
                    html += '<div class="user-sign pic_{{sid}}_'+num+'" id="pic_{{sid}}_'+num+'_'+i+'" style="'+getstyle(num,i)+'"> <div class="img-bar"> <a href="javascript:void(0);" title="删除" class="sign_del" onclick="delct('+i+')"><span data-icon="U" aria-hidden="true" class="colRed"></span></a> </div> <div class="focus" style="width:100%; height:100%"> <img src="'+ getbase64(num,i) +'" style="width:100%; height:100%"> </div> </div>';
                }
            }
            $('#intermediatePage'+num).append(html);
            clearInterval(set);
        };

        var set = setInterval(check,500);
    }

    function setct(id) {
        $( "#pic_{{sid}}_" + parseInt($('#pagecurrnum').val()) + "_" +id ).resizable("option", "cancel", ".page").draggable( "option", "cancel", ".page" );
        $( "#pic_{{sid}}_" + parseInt($('#pagecurrnum').val()) + "_" +id ).find(".sign_confirm").remove();
        setlocalStorage(parseInt($('#pagecurrnum').val()),id);
    }
    function delct(id) {
        $( "#pic_{{sid}}_" + parseInt($('#pagecurrnum').val()) + "_" +id).remove();
        dellocalStorage(parseInt($('#pagecurrnum').val()),id);
    }

    function setdraggrable(){
        $( ".draggable" ).draggable({ containment: "parent" },{stop: function( event, ui ) {
        }}).resizable({ containment: "parent" },{ handles: 'n, e, s, w, ne, se, sw, nw' },{ maxWidth: parseFloat($('#imgwidth').val())},{maxHeight: parseFloat($('#imgheight').val())},{
            stop: function( event, ui ) {
            }
        });
    }

    function getbase64(num,id){
        var base64 = JSON.parse(localStorage.getItem('picbase64_{{sid}}_'+ num +'_'+ id));
        if(typeof(base64)=='undefined' || base64==null)
        {
            base64 = '';
        }
        return base64;
    }

    function getstyle(num,id){
        var style = JSON.parse(localStorage.getItem('picstyle_{{sid}}_'+ num +'_'+ id));
        if(typeof(style)=='undefined' || style==null)
        {
            style = '';
        }
        return style;
    }

    function setlocalStorage(num,id){
        localStorage.setItem("picbase64_{{sid}}_" + num + "_" + id , JSON.stringify($("#pic_{{sid}}_" + num + "_" +id).find('img').attr('src')));
        localStorage.setItem("picstyle_{{sid}}_" + num + "_" + id , JSON.stringify($("#pic_{{sid}}_" + num + "_" +id).attr('style')));
    }

    function dellocalStorage(num,id){
        localStorage.removeItem("picbase64_{{sid}}_" + num + "_" + id);
        localStorage.removeItem("picstyle_{{sid}}_" + num + "_" + id);
    }

    function allpicupset(){
        var i = 1;
        var check = function(){
            if(i <= parseInt($('#totalnum').text())){
                onepicupset(i);
                i++;
            }else{
                clearInterval(set3);
                $('#upmsg').html('<span style="color: #5bb75b;">上传成功,正为您跳转到报表页...</span>');
                setTimeout(function(){
                    window.location.href = '/sproject/intermediate/view/{{sid}}';
                    $('#up').modal('hide');
                },1500);
            }
        };
        var set3 = setInterval(check,500);

    }

    function onepicupset(num){
        //遍历获取所有localStorage
        var storage = window.localStorage;
        var arr1 = new Array(),
            arr2 = new Array(),
            j =0;
        for (var i=0, len = storage.length; i  <  len; i++){
            var key = storage.key(i);
            if(key.indexOf('picstyle_{{sid}}_' + num) >= 0){
                var id = key.split('_');
                arr1[j] = getbase64(num,id[3]);
                arr2[j] = getpicstyle(num,id[3]);
                j++;
            }
        }
        if(j>0){
            makepicbycanvas(arr1,arr2,j,num);
        }else{
            if(num < parseInt($('#totalnum').text())){
                $('#upnum').text(parseInt($('#upnum').text()) + 1);
            }else{
                uploadmakepic(num,'');
            }
        }
    }


    //生成base64合成图
    function makepicbycanvas(base64Arr,styleArr,num,pagenum){
        var img = new Image();
        img.onload = function(){
            var canvas = document.createElement('canvas'),
                ctx = canvas.getContext('2d');
            canvas.width = img.width;
            canvas.height = img.height;
            ctx.drawImage(img,0,0);
            function drawing(n){
                if(n<num){
                    var image = new Image();
                    image.onload = function(){
                        ctx.drawImage(image,0,0,image.width,image.height,styleArr[n][1],styleArr[n][0],styleArr[n][2],styleArr[n][3]);
                        drawing(n+1);
                    };
                    image.src = base64Arr[n];
                }else{
                    var dataUrl = canvas.toDataURL("image/jpeg");
                    uploadmakepic(pagenum,dataUrl);
                    return;
                }
            }
            drawing(0);
        };
        img.src = '{{rootUrl}}signs/{{sid}}/'+pagenum+'.jpg';
    }

    function uploadmakepic(num,base64){
        $.ajax({
            type: 'post',
            url: '/sproject/upload/intermediate/{{sid}}',
            data:{num:num,data:base64},
            dataType: 'json',
            success:function(result){
                if(result.code == 200){
                    dellocalStoragebyNum(num);
                    $('#upnum').text(parseInt($('#upnum').text()) + 1);
                }else if(result.code == 202){
                    dellocalStoragebyNum(num);
                }
            }
        })
    }

    function dellocalStoragebyNum(num){
        var storage = window.localStorage;
        for (var i=0, len = storage.length; i  <  len; i++){
            var key = storage.key(i);
            if(key.indexOf('picstyle_{{sid}}_' + num) >= 0){
                var id = key.split('_');
                dellocalStorage(num,id[3]);
            }
        }

    }

    function getpicstyle(num,id){
        var style = getstyle(num,id);
        if(style != ''){
            var arr = new Array();
            var arr2 = new Array();
            var arr3 = new Array();
            arr = style.split(';');
            var j = 0;
            for(var i = 0; i < arr.length; i++){
                if(arr[i].trim() != ''){
                    var arr4 = arr[i].split(':');
                    arr2[j] = parseFloat(arr4[1].trim());
                    j++;
                }
            }
            arr3[0] = arr2[2];
            arr3[1] = arr2[3];
            arr3[2] = arr2[5];
            arr3[3] = arr2[6];
            return arr3;
        }else{
            return '';
        }
    }

    function checkcurrnum(){
        if(parseInt($('#currnum').val()) > 0 && parseInt($('#currnum').val()) <= parseInt($('#totalnum').text())){
            if(checkpicmake()){
                window.location.href = '/sproject/make/intermediate/{{sid}}/page/'+parseInt($('#currnum').val());
            }
            return false;
        }else{
            return false;
        }
    }

    //是否存在未上传的图片
    function checkpicmake(){
        if($('.page .user-sign .sign_confirm').length != 0){
            $('#doneonepic').modal('show');
            return false;
        }else{
            return true;
        }
    }

    function checkpicup(){
        if($('.page .user-sign .sign_confirm').length != 0){
            $('#doneonepic').modal('show');
        }else{
            $('#done').modal('show');
        }
    }

</script>
</body>
