<%@ page language="java" pageEncoding="utf-8" %>
<%@ include file="/WEB-INF/views/include/taglib.jsp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>高校版阅卷系统</title>
    <link rel="stylesheet" href="${ctxStatic}/jcrop/css/jquery.Jcrop.min.css"/>
    <link rel="stylesheet" href="${ctxStatic}/pic-config/css/style.css"/>
    <script type="text/javascript" src="${ctxStatic}/jquery/jquery-1.9.1.min.js"></script>
    <script type="text/javascript" src="${ctxStatic}/jcrop/js/jquery.Jcrop.min.js"></script>
    <script type="text/javascript" src="${ctxStatic}/utils/image-utils.js"></script>
</head>
<body>
<div class="c-box" style="display:none" id="pic-config-div">
    <div class="cont-z">
        <div class="c-top">
            <div class="c-icon">
                <div class="all" id="preview-image-button">选择整图</div>
                <!--
                <div class="iviewer_zoom_in iviewer_common iviewer_button"></div>
                <div class="iviewer_zoom_out iviewer_common iviewer_button"></div>
                <div class="iviewer_zoom_zero iviewer_common iviewer_button"></div>
                <div class="iviewer_zoom_fit iviewer_common iviewer_button"></div>
                -->
            </div>
            <ul class="c-tab cl" id="pic-switch" data-index="">
            </ul>
        </div>
        <div class="c-mn">
            <div class="imgcont" id="image-holder"><img id="pic-content" src=""/></div>
            <canvas id="pic-canvas" style="display:none"></canvas>
        </div>
    </div>
    <div class="cont-y">
        <div class="c-mn">
            <div class="c-preview">
                <ul id="pic-config-preview">
                </ul>
            </div>
        </div>
        <div class="c-bottom cl">
            <a class="c-btn close" id="pic-config-clear" href="javascript:void(0)">清空</a>
            <a class="c-btn s" id="pic-config-save" href="javascript:void(0)">保存</a>
            <a class="c-btn" id="pic-config-cancel" href="javascript:void(0)">取消</a>
        </div>
    </div>
</div>
</body>

<script type="text/javascript">
    var message = '${message}';
    if (message != null && message != '' && message != undefined) {
        alert(message);
    }
    var image_server = '${fileServer}';
    var pictureConfig = '${pictureConfig}';
    var picUrls = '${picUrls}';
    var picUrl = picUrls.split('[')[1].split(']')[0];
    var urls = [];
    for (var j = 0; j < picUrl.split(',').length; j++) {
        urls.push(picUrl.split(',')[j].trim());
    }
    var config = window.localStorage.getItem("pictureConfig");
    if (config != null && config != undefined) {
        pictureConfig = config;
    }

    var saveCallback;
    var jcrop_canvas;
    var jcrop_api;
    var image_array = [];
    $(document).ready(function (e) {
        $('#pic-config-div').css('z-index', 9999);
        $('#pic-config-div').height($(window).height());
        $('#pic-config-div').width($(window).width());
        $('#pic-config-div').offset({top: 0, left: 0});

        $('#pic-config-clear').click(function () {
            $('#pic-config-preview').empty();
        });
        $('#pic-config-save').click(function () {
            var result = [];
            $('#pic-config-preview').find('li').each(function () {
                result.push(JSON.parse($(this).attr('data-config')));
            })
            if (result.length == 0) {
                alert('请至少裁切一张小图后再保存');
                return;
            }
            /* for (var i = 0; i < result.length; i++) {
            	 if(result[i].w>1 && result[i].h>1){
            		 var imageI=result[i].i;
            		 result[i].x = (result[i].x/image_array[imageI - 1].width).toFixed(3);
            		 result[i].y = (result[i].y/image_array[imageI - 1].height).toFixed(3);
            		 result[i].w = (result[i].w/image_array[imageI - 1].width).toFixed(3);
            		 result[i].h = (result[i].h/image_array[imageI - 1].height).toFixed(3);
                 }
            } */
            $('#pic-config-div').hide();
            if (saveCallback != undefined) {
                saveCallback(result);
            }
        });
        $('#pic-config-cancel').click(function () {
            // $('#pic-config-div').hide();
            window.close();
        });
        $('#preview-image-button').click(function () {
            addPreviewImage();
        });
        $('#pic-content').Jcrop({
            //boxWidth: $(window).width()*0.65,
            boxHeight: $(window).height() - 90,
            onDblClick: addPreview
        }, function () {
            jcrop_api = this;
        });
        jcrop_canvas = $('#pic-canvas')[0];

        initPicConfigPopup(urls, pictureConfig, function (result) {
            if (window.opener && !window.opener.closed) {
                window.opener.document.getElementById("picList").value = JSON.stringify(result);
                window.opener.document.getElementById("configuration").innerText = "设置成功";
                window.localStorage.setItem("pictureConfig", JSON.stringify(result));
                window.close();
            }
        });
    });

    function initPicConfigPopup(urls, config, onSave) {
        if (config) {
            config = JSON.parse(config);
        }
        initImages(urls, config);
        saveCallback = onSave;
        $('#pic-config-div').show();
    }

    function initImages(urls, config) {
        let container = $('#pic-switch');
        container.empty();
        container.attr('data-index', '');
        image_array = [];
        new ImageLoader({
            server: image_server,
            flush: true,
            strict: false
        }).load(urls, [], function (images) {
            image_array = images;
            for (let i = 1; i <= image_array.length; i++) {
                let dom = $('<li data-index="' + i + '"><a href="javascript:void(0)">' + i + '</a></li>').appendTo(container);
                dom.find('a').click(function () {
                    let index = parseInt($(this).parent().attr('data-index'));
                    jcrop_api.setImage(image_array[index - 1].src);
                    container.attr('data-index', index);
                    container.find('li').removeClass('on');
                    $(this).parent().addClass('on');
                })
            }
            container.find('li:first a').trigger('click');
            initConfigs(config);
        });
    }

    function initConfigs(config) {
        $('#pic-config-preview').empty();

        if (config != undefined) {
            for (var i = 0; i < config.length; i++) {
                addPreviewByConfig(config[i]);
            }
        }
    }

    function getCropConfig(c) {
        var scaleX = jcrop_api.getScaleFactor()[0];
        var scaleY = jcrop_api.getScaleFactor()[1];
        config = {
            x: c.x * scaleX,
            y: c.y * scaleY,
            w: c.w * scaleX,
            h: c.h * scaleY
        }
        return config;
    }

    function addPreview(c) {
        if (parseInt(c.w) > 0) {
            var config = getCropConfig(c);
            config.i = $('#pic-switch').attr('data-index');
            if (config.i != '') {
                config.i = parseInt(config.i);
                addPreviewByConfig(config);
            }
            jcrop_api.release();
        }
    }

    function addPreviewImage() {
        var index = $('#pic-switch').attr('data-index');
        if (index == '') {
            return;
        }
        var config = {
            i: parseInt(index),
            x: 0,
            y: 0,
            w: 0,
            h: 0
        }
        addPreviewByConfig(config);
    }

    function addPreviewByConfig(config) {
        var container = $('#pic-config-preview');
        if(config.x<=1 && config.y<=1 && config.w<=1 && config.h<=1){
        	config.x = image_array[config.i - 1].width*config.x;
        	config.y = image_array[config.i - 1].height*config.y;
        	config.w = image_array[config.i - 1].width*config.w;
        	config.h = image_array[config.i - 1].height*config.h;
        }
        var width = config.w;
        var height = config.h;
        if (width == 0) {
            width = image_array[config.i - 1].width;
        }
        if (height == 0) {
            height = image_array[config.i - 1].height;
        }
        jcrop_canvas.width = width
        jcrop_canvas.height = height

        jcrop_canvas.getContext("2d").drawImage(image_array[config.i - 1], config.x, config.y, width, height, 0, 0, width, height);

        var dom = $('<li><span class="order">' + config.i + '</span><div class="m"><img src=""/></div><span class="close">&times;</span></li>').appendTo(container);
        dom.attr('data-config', JSON.stringify(config));
        dom.find('img').attr('src', jcrop_canvas.toDataURL());
        dom.find('span.close').click(function () {
            $(this).parent().remove();
        });
    }
</script>

</html>