/**
 * 连线题模板
 * Created by hyt on 14-9-15.
 * @vision 1.0
 */
define(function (require, exports, module) {
    var _cardbase = require('./cardbase');
    var _define = require('../define');
    var tplparse = require('../thirdparty/template');

    function MatchCard(option, currenthight, currentwidth, zoox, zooy) {
        if (!('items' in option)) {
            throw new Error('option Parameters!');
        }
        var _dom;
        var _self = this;
        var _cardNum = option.items.question.length;
        var _status = 'conform'; // conform / clear
        var quesHtml = '';
        var answHtml = '';
        var _random = '';

        var _quesArr = [];
        var _answArr = [];

        var quesPoints = [];
        var answPoints = [];

        var matchLineObj = {}; // 保存用户行为产生的答案
        var isRight = true;
        var hasMatchNum = 0;

        var indexQ = -1;
        var indexA = -1;
        var idQ = '';
        var idA = '';

        var _upperCanvas;
        var _upperCanvasContext;
        var _selectedIDGroup = [];

        /**
         *初始连线题卡片
         */
        function init() {
            _self.getTemplate().done(function (tpl) {
                _random = _self.randomString(5);

                for (var i = 0; i < option.items.question.length; i++) {
                    if (option.items.question[i].type === 'img') {
                        quesHtml += '<li class="lxt_edit lxt_bf_li match_item_img" id="' + _random + option.items.question[i].id + '"><span class="lxt_bf_li_img"><img src="' + option.items.question[i].value + '"></span><em class="lxt_ic asb_r"></em></li>';
                    } else {
                        quesHtml += '<li class="lxt_edit lxt_bf_li match_item_txt" id="' + _random + option.items.question[i].id + '"><div style="width: 100%;height: 100%;overflow: hidden"><span class="lxt_bf_li_text" style="vertical-align: middle;display: table-cell;text-align: center;">' + option.items.question[i].value + '</span></div><em class="lxt_ic asb_r"></em></li>';
                    }
                    if (option.items.answer[i].type === 'img') {
                        answHtml += '<li class="lxt_edit lxt_bf_li match_item_img" id="' + _random + option.items.answer[i].id + '"><span class="lxt_bf_li_img"><img src="' + option.items.answer[i].value + '"></span><em class="lxt_ic asb_l"></em></li>';
                    } else {
                        answHtml += '<li class="lxt_edit lxt_bf_li match_item_txt" id="' + _random + option.items.answer[i].id + '"><div style="width: 100%;height: 100%;overflow: hidden"><span class="lxt_bf_li_text" style="vertical-align: middle;display: table-cell;text-align: center;">' + option.items.answer[i].value + '</span></div><em class="lxt_ic asb_l"></em></li>';
                    }
                }
                tpl = tpl.replace("{{answHtml}}", answHtml).replace('{{quesHtml}}', quesHtml);
                var html = tplparse.render(tpl, option);
                _dom = $(html);
                _self.initUpperCanvas();
            });

            _self.padControl();
        }

        this.getContent = function () {
            return _dom;
        };

        this.setHtmlStyle = function () {
            // 设置样式
            if (_cardNum <= 3) {
                _dom.find('.match_item_img').css({'height': currenthight * 0.18 + 'px', 'line-height': currenthight * 0.22 + 'px', 'width': currentwidth * 0.3 + 'px'});
                _dom.find('.match_item_txt,.match_item_txt span').css({'height': currenthight * 0.18 + 'px', 'width': currentwidth * 0.3 + 'px', 'word-break': 'break-word'});
            } else if (_cardNum <= 5) {
                _dom.find('.match_item_img').css({'height': currenthight * 0.12 + 'px', 'line-height': currenthight * 0.16 + 'px', 'width': currentwidth * 0.3 + 'px'});
                _dom.find('.match_item_txt,.match_item_txt span').css({'height': currenthight * 0.12 + 'px', 'width': currentwidth * 0.3 + 'px', 'word-break': 'break-word'});
            } else if (_cardNum > 5) {
                _dom.find('.match_item_img').css({'height': currenthight * 0.096 + 'px', 'line-height': currenthight * 0.13 + 'px', 'width': currentwidth * 0.3 + 'px'});
                _dom.find('.match_item_txt,.match_item_txt span').css({'height': currenthight * 0.096 + 'px', 'width': currentwidth * 0.3 + 'px', 'word-break': 'break-word'});
            }
            _dom.find('.match_ct_list').css({'height': currenthight * 0.80 + 'px'});
        }

        this.getLineDotPoz = function () {
            if ( answPoints.length > 0) return;
            var _dom_top = _dom.offset().top;
            var _dom_left = _dom.offset().left;

            _dom.find('.lxt_ic').each(function (i) {
                var point = new Point();
                var _prog = $(this).offset();
                point.x = _prog.left - _dom_left;
                point.y = _prog.top - _dom_top;

                if (i < _cardNum) {
                    quesPoints.push(point);
                    _quesArr.push($(this).parent('li').attr('id'));
                } else {
                    answPoints.push(point);
                    _answArr.push($(this).parent('li').attr('id'));
                }
            });
        }

        /**
         * pad端控制
         */
        this.padControl = function () {
            _status = 'conform';
            _self.setHtmlStyle();

            setTimeout(function () {

                // 核定答案  和  再来一次按钮绑定
                _dom.find('#btn_conform').on('tap', function () {
                    indexQ = -1;
                    indexA = -1;
                    idQ = '';
                    idA = '';

                    _dom.find('.card_list_left li,.card_list_right li').css({
                        'border': '1px solid rgb(169, 169, 169)'
                    });

                    if (_status == 'conform') {
                        _status = 'clear';
                        _self.changeStatus();

                        hasMatchNum = 0;
                        isRight = true;
                        for (var key in matchLineObj) {

                            if (key.replace(_random, '').replace('q', '') !== matchLineObj[key].replace(_random, '').replace('a', '')) {
                                isRight = false;

                                // 变换红色提示
                                _dom.find('#lineSprite #line_' + key + ' svg line').css('stroke', '#eb5338');

                                _dom.find('.card_list_left li#' + key).find('em').addClass('lxt_ic_on');
                                _dom.find('.card_list_right li#' + matchLineObj[key]).find('em').addClass('lxt_ic_on');
                            }
                            hasMatchNum++;
                        }

                        if (isRight) {
                            if (hasMatchNum === _cardNum) {
                                _dom.find('.resultImg').attr('src', 'share/assert/images/congratulation.png');
                            } else {
                                _dom.find('.resultImg').attr('src', 'share/assert/images/encourage.png');
                            }
                        } else {
                            _dom.find('.resultImg').attr('src', 'share/assert/images/encourage.png');
                        }

                        _dom.find('.resultImg').show().animate({"height": "86px", "bottom": "60px", "opacity": "1"}, 300);
                        setTimeout(function () {
                            _dom.find('.resultImg').animate({"height": "60px", "bottom": "60px", "opacity": "0"}, 300).hide();
                        }, 2000);

                    } else {
                        _dom.find('#lineSprite').html('');
                        _dom.find('.card_list_left,.card_list_right').find('em').removeClass('lxt_ic_on');

                        _status = 'conform';
                        _self.changeStatus();
                        matchLineObj = {};
                    }
                });

            }, 300);
        }

        /**
         * 连线判断操作（给canvas碰撞后使用）
         * @param _selectIDs
         */
        this.matchLineOpration = function(_selectIDs) {
            _self.getLineDotPoz();
            var selectIDsArrTmp = _selectIDs;
            if(selectIDsArrTmp[0].replace(_random, '').indexOf('q') > -1){
                idQ = _selectIDs[0];
                idA = _selectIDs[1];
            } else {
                idQ = _selectIDs[1];
                idA = _selectIDs[0];
            }
            indexQ = _quesArr.indexOf(idQ);
            indexA = _answArr.indexOf(idA);

            // 判断右边的框是否连接
            deleteConnection();
            judgeConnection();
        }

        // 连线操作
        function judgeConnection() {
            if (indexQ > -1 && indexA > -1) {
                drowSvgLine(quesPoints[indexQ].x, quesPoints[indexQ].y, answPoints[indexA].x, answPoints[indexA].y, true, idQ);
                matchLineObj[idQ] = idA;
                _status = 'conform';
                _self.changeStatus();

                indexA = -1;
                indexQ = -1;

                setTimeout(function () {
                    _dom.find('.card_list_left li,.card_list_right li').css({
                        'border': '1px solid rgb(169, 169, 169)'
                    });
                }, 500);
            }
        }

        // 删除连接
        function deleteConnection() {
            if (indexQ !== -1 && indexA !== -1) {
                // 断开连接
                _dom.find('.card_list_left li#' + idQ).find('em').removeClass('lxt_ic_on');
                _dom.find('.card_list_right li#' + matchLineObj[idQ]).find('em').removeClass('lxt_ic_on');

                _dom.find("#lineSprite #line_" + idQ).html(''); // 断开左侧
                delete matchLineObj[idQ];

                for (var key in matchLineObj) {
                    if (matchLineObj[key] === idA) {
                        _dom.find('.card_list_left li#' + key).find('em').removeClass('lxt_ic_on');
                        _dom.find('.card_list_right li#' + matchLineObj[key]).find('em').removeClass('lxt_ic_on');
                        _dom.find("#lineSprite #line_" + key).html(''); // 断开右侧
                        delete matchLineObj[key];
                        break;
                    }
                }
                _status = 'conform';
                _self.changeStatus();

                setTimeout(function () {
                    _dom.find('.card_list_left li,.card_list_right li').css({
                        'border': '1px solid rgb(169, 169, 169)'
                    });
                }, 500);
            }
        }

        /************************pad端划线方法****************************************/

        /**
         * 画svg连线
         * @param prmFromX
         * @param prmFromY
         * @param prmToX
         * @param prmToY
         * @param prmType
         * @param prmId
         */
        function drowSvgLine(prmFromX, prmFromY, prmToX, prmToY, prmType, prmId) {
            prmFromX = addX(prmFromX); //修正X坐标
            prmFromY = addY(prmFromY); //修正Y坐标
            prmToX = addX(prmToX); //修正X坐标
            prmToY = addY(prmToY); //修正Y坐标

            if (!_dom.find('#lineSprite #line_' + prmId).length > 0 && prmType) {
                _dom.find("#lineSprite").append('<div style="position: absolute;left: 0;right: 0;width: 100%;height: 100%" id="line_' + prmId + '"></div>');
            }

            var tmp = $('<svg xmlns="http://www.w3.org/2000/svg" version="1.1" style="width: 100%;height: 100%"><line x1="' + prmFromX + '" y1="'
                + prmFromY + '" x2="' + prmToX + '" y2="' + prmToY + '" style="stroke:#9C9c9c;stroke-width:3" /></svg>');

            (prmType ? _dom.find("#lineSprite #line_" + prmId) : _dom.find("#prewLineSprite")).append(tmp);
        }

        function Point() {
            'x';
            'y';
        };

        /* 计算线条坐标的水平偏移量 */
        function addX(prmX) {
            return (prmX + 9) / zoox;
        }

        /* 计算线条坐标的垂直偏移量 */
        function addY(prmY) {
            return (prmY + 9) / zooy;
        }

        /******************************************************************/

        this.changeStatus = function () {
            if (_status == 'conform') {
                _dom.find("#btn_conform").html("核对答案");
            } else {
                _dom.find("#btn_conform").html("再来一次");
            }
        };

        this.randomString = function (a) {
            var b = "";
            a = 0 < parseInt(a) ? parseInt(a) : 10;
            for (var c = 0; c < a; c++)
                 var d = Math.floor(61 * Math.random()), b = b + "ABCDEFGHIJKLMNOPQRSTUVWXTZ0123456789abcdefghiklmnopqrstuvwxyz".substring(d, d + 1);
            return b
        };

        //上层canvas遮罩用来画线
        this.initUpperCanvas = function () {
            _upperCanvas = $("<canvas class='upperCanvas'></canvas>");
            _upperCanvas.css({"position": "absolute", "left": "0px", "top": "60px", "zIndex": 1});
            _upperCanvas.attr("width", "600px");
            _upperCanvas.attr("height", "380px");
            var _upperCanvasContext = _upperCanvas[0].getContext("2d");
            _upperCanvasContext.lineWidth = 4;
            _upperCanvasContext.lineJoin = 'round';
            _upperCanvasContext.lineCap = 'round';
            _upperCanvasContext.strokeStyle = "#9C9c9c";
            _upperCanvasContext.fillStyle = "#9C9c9c";
            _upperCanvas.unbind();
            var _isPainting = false;
            var startPoint = {x: 0, y: 0};
            var endPoint = {x: 0, y: 0};
            _upperCanvas.bind("mousedown", function (evt) {
                _selectedIDGroup = [];
                var startX = (evt.clientX - _dom.find(".upperCanvas").offset().left) / zoox;
                var startY = (evt.clientY - _dom.find(".upperCanvas").offset().top) / zooy;
                _upperCanvasContext.beginPath();
                //在仅仅点击鼠标时，需要画出一个点，如果不加上这0.01个像素，则画不出来
                startPoint.x = startX + 2;
                startPoint.y = startY + 2;
                _isPainting = true;
                _self.getComputedMatch(startPoint);
                evt.preventDefault();
            });
            _upperCanvas.bind("mousemove", function (evt) {
                if (_isPainting) {
                    endPoint.x = (evt.clientX - _dom.find(".upperCanvas").offset().left) / zoox + 2;
                    endPoint.y = (evt.clientY - _dom.find(".upperCanvas").offset().top) / zooy + 2;
                    _upperCanvasContext.clearRect(0, 0, 600, 380);
                    _upperCanvasContext.beginPath();
                    _upperCanvasContext.moveTo(startPoint.x, startPoint.y);
                    _upperCanvasContext.lineTo(endPoint.x, endPoint.y);
                    _upperCanvasContext.stroke();
                }
                evt.preventDefault();
            });
            _upperCanvas.bind("mouseup", function (evt) {
                _self.getComputedMatch(endPoint);
                if (_selectedIDGroup.length === 2 && (_selectedIDGroup[0] != _selectedIDGroup[1])) {
                    console.log(_selectedIDGroup);
                    //TODO:传递id数组并连线
                    _upperCanvasContext.clearRect(0, 0, 600, 380);
                    _self.matchLineOpration(_selectedIDGroup);
                } else {
                    _upperCanvasContext.clearRect(0, 0, 600, 380);
                }
                _isPainting = false;
                evt.preventDefault();
            });
            _upperCanvas.bind("mouseout", function (evt) {
                _upperCanvasContext.clearRect(0, 0, 600, 380);
                _isPainting = false;
                evt.preventDefault();
            });


            _upperCanvas.bind("touchstart", function (evt) {
                _selectedIDGroup = [];
                var startX = (evt.originalEvent.touches[0].clientX - _dom.find(".upperCanvas").offset().left) / zoox;
                var startY = (evt.originalEvent.touches[0].clientY - _dom.find(".upperCanvas").offset().top) / zooy;
                _upperCanvasContext.beginPath();
                //在仅仅点击鼠标时，需要画出一个点，如果不加上这0.01个像素，则画不出来
                startPoint.x = startX + 2;
                startPoint.y = startY + 2;
                _isPainting = true;
                _self.getComputedMatch(startPoint);
                evt.preventDefault();
            });
            _upperCanvas.bind("touchmove", function (evt) {
                if (_isPainting) {
                    endPoint.x = (evt.originalEvent.touches[0].clientX - _dom.find(".upperCanvas").offset().left) / zoox + 2;
                    endPoint.y = (evt.originalEvent.touches[0].clientY - _dom.find(".upperCanvas").offset().top) / zooy + 2;
                    _upperCanvasContext.clearRect(0, 0, 600, 380);
                    _upperCanvasContext.beginPath();
                    _upperCanvasContext.moveTo(startPoint.x, startPoint.y);
                    _upperCanvasContext.lineTo(endPoint.x, endPoint.y);
                    _upperCanvasContext.stroke();
                }
                evt.preventDefault();
            });
            _upperCanvas.bind("touchend", function (evt) {
                _self.getComputedMatch(endPoint);
                if (_selectedIDGroup.length === 2 && (_selectedIDGroup[0] != _selectedIDGroup[1])) {
                    console.log(_selectedIDGroup);
                    //TODO:传递id数组并连线
                    _upperCanvasContext.clearRect(0, 0, 600, 380);
                    _self.matchLineOpration(_selectedIDGroup);
                } else {
                    _upperCanvasContext.clearRect(0, 0, 600, 380);
                }
                _isPainting = false;
                evt.preventDefault();
            });


            _dom.append(_upperCanvas);
        }

        /**
         *  碰撞计算
         * @param point
         */
        this.getComputedMatch = function (point) {
            //先获取每个选项相对于canvas的位置信息
            var posInfoObjArr = [];
            _dom.find(".lxt_edit").each(function () {
                var posInfo = {left: ($(this).offset().left - _dom.offset().left) / zoox,
                    top: ($(this).offset().top - _dom.offset().top) / zooy - 60};
                var right = posInfo.left + $(this).width();
                var bottom = posInfo.top + $(this).height();
                posInfo.right = right;
                posInfo.bottom = bottom;
                var posInfoObj = {id: $(this).attr("id"), posInfo: posInfo};
                posInfoObjArr.push(posInfoObj);
                if (point.x >= posInfo.left && point.y >= posInfo.top && point.x <= posInfo.right && point.y <= posInfo.bottom) {
                    _selectedIDGroup.push($(this).attr("id"));
                }
            });
        }
        init(); //调用入口
    }

    MatchCard.prototype = new _cardbase.CardBase();
    MatchCard.prototype.constructor = MatchCard;
    MatchCard.prototype.getCardName = function () {
        return _define.CardName.Matchcard;
    };
    exports.Constructor = MatchCard;
});
