/**
 * 连线题模板
 * 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 = '';

        /**
         *初始连线题卡片
         */
        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.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.18 + '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.12 + '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.096 + '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'});
        }

        /**
         * pad端控制
         */
        this.padControl = function () {
            _status = 'conform';
            _self.setHtmlStyle();
            var matchLineObj = {}; // 保存用户行为产生的答案
            var isRight = true;
            var hasMatchNum = 0;

            setTimeout(function () {
                var color = "#9C9c9c";

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

                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);
                    } else {
                        answPoints.push(point);
                    }
                });

                console.log(quesPoints, answPoints);

                var indexQ = -1;
                var indexA = -1;

                var idQ = '';
                var idA = '';

                // 点击左侧框
                _dom.find('.card_list_left li').on('tap', function () {
                    _dom.find('.card_list_left li').css({
                        'border': '1px solid rgb(169, 169, 169)'
                    });
                    $(this).css({
                        'border': '2px solid #0099FF'
                    });

                    idQ = $(this).attr('id');
                    indexQ = $(this).index();

                    // 判断左边的框是否连接
                    deleteConnection();

                    judgeConnection();
                });

                // 点击右侧框
                _dom.find('.card_list_right li').on('tap', function () {
                    _dom.find('.card_list_right li').css({
                        'border': '1px solid rgb(169, 169, 169)'
                    });
                    $(this).css({
                        'border': '2px solid #0099FF'
                    });

                    idA = $(this).attr('id');
                    indexA = $(this).index();

                    // 判断右边的框是否连接
                    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;
                            }
                        }
                        console.log(matchLineObj);

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

                // 核定答案  和  再来一次按钮绑定
                _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);
        }

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

        init(); //调用入口
    }

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