/*
 * 特别声明：本技术材料受《中华人民共和国著作权法》、《计算机软件保护条例》等法律、法规、行政
 * 规章以及有关国际条约的保护，赞同科技享有知识产权、保留一切权利并视其为技术秘密。未经本公司书
 * 面许可，任何人不得擅自（包括但不限于：以非法的方式复制、传播、展示、镜像、上载、下载）使用，
 * 不得向第三方泄露、透露、披露。否则，本公司将依法追究侵权者的法律责任。特此声明！
 *
 * Special Declaration: These technical material reserved as the technical secrets by AGREE 
 * TECHNOLOGY have been protected by the "Copyright Law" "ordinances on Protection of Computer 
 * Software" and other relevant administrative regulations and international treaties. Without 
 * the written permission of the Company, no person may use (including but not limited to the 
 * illegal copy, distribute, display, image, upload, and download) and disclose the above 
 * technical documents to any third party. Otherwise, any infringer shall afford the legal 
 * liability to the company.
 */
/**
 * Created by liushuai on 2015/1/13.
 */
define(["adoreapp/widget/BaseWidget"
        , "adoreapp/widget/EventHub"
        , "adoreapp/widget/validator/PictureValidator"
        , "adoreapp/widget/validator/MaxLengthValidator"
        , "adoreapp/util/AppEventUtil"]
    , function (BaseWidget, EventHub, PictureValidator, MaxLengthValidator, AppEventUtil) {
        return BaseWidget.extend(function (base) {
            var maxLength = -1;
            return {
                _initWidget: function (attrs) {
                    var id = this.id;
                    var own = this;
                    this.jqueryNode = $(attrs.template).attr({
                        id: this.id + "_containerNode",
                        class: "input-field col"
                    });
                    this.jqueryNode.find("input").attr("id", this.id).on("input", function (e) {
                        own.handleOnInput();
                        EventHub.dispatchEvent(EventHub.MSG_TYPE.WIDGET, {
                            id: id,
                            text: $(this).val(),
                            evtType: EventHub.MODIFY,
                            syncAttrName: "text"
                        })
                    }).on('focus', function () {
                        own.sendFocusGain();
                        AppEventUtil._handleSoftwareKeyboardShowed();
                    }).on('blur', function () {
                        own.checkRequisite();
                    });
                    this.jqueryNode.find("label").attr("for", this.id);
                    var password = 0x13;
                    if ((attrs.style & password) === password) {
                        this.jqueryNode.find("input").attr("type", "password");
                    }
                    this.editable = true;
                    this.enabled = true;
                },

                handleOnInput: function () {
                    this.maxLengthValidator.handleModifyEvent();
                    if (this.picture)
                        this.picture.handleModifyEvent();
                    this.checkRequisite('请输入数据!');
                },

                checkRequisite: function (msg) {
                    if (this.requisite) {
                        var inputSelector = this.jqueryNode.find('input');
                        var value = inputSelector.val();
                        //不可编辑or不可用or已经有值时
                        if (!this.enabled || !this.editable || value) {
                            this.removeRequisite();
                        } else {
                            this.addRequisite();
                            if (msg) {
                                this.showSpan(msg);
                            }
                        }
                    }
                },

                _setRequisite: function (attrs) {
                    this.requisite = attrs.requisite;
                    this.checkRequisite("");
                },

                _setEnabled: function (attrs) {
                    this.enabled = attrs.enabled;
                    var input = this.jqueryNode.find("input");
                    if (this.enabled) {
                        input.removeAttr("disabled");
                        this.jqueryNode.find("i").removeClass("icon_disabled");
                    } else {
                        this.jqueryNode.find("input").attr("disabled", "disabled");
                        this.jqueryNode.find("i").addClass("icon_disabled");
                    }
                    this.checkRequisite("");
                },

                _setFocus: function () {
                    if (document.activeElement !== this.jqueryNode.find("input")[0]) {
                        this.jqueryNode.find("input").focus();
                    }
                },

                addRequisite: function () {
                    this.jqueryNode.find('input').addClass('adore_InputRequisite');
                    this.jqueryNode.find("label").addClass('adore_requisiteColor');
                    this.jqueryNode.find("i").addClass('adore_requisiteColor');
                },

                removeRequisite: function () {
                    this.jqueryNode.find('input').removeClass('adore_InputRequisite');
                    this.jqueryNode.find("label").removeClass('adore_requisiteColor');
                    this.jqueryNode.find("i").removeClass('adore_requisiteColor');
                    this.hideSpan();
                },

                _setText: function (attrs) {
                    var inputNode = this.jqueryNode.find("input");
                    inputNode.val(attrs.text);
                    if (attrs.text.length > 0) {
                        inputNode.siblings('label, i').addClass('active');
                    } else {
                        inputNode.siblings('label, i').removeClass('active');
                    }
                    this.checkRequisite("");
                },

                showSpan: function (msg) {
                    this.jqueryNode.find('span').html(msg).css('display', 'block');
                },

                hideSpan: function () {
                    this.jqueryNode.find('span').css('display', 'none');
                },

                _setIcon: function (attrs) {
                    this.jqueryNode.find("i").addClass(attrs.icon);
                    if (this.jqueryNode.find("input").val().length > 0)
                        this.jqueryNode.find("input").siblings('label, i').addClass('active');
                    this.jqueryNode.find('span').addClass('span_prefix');
                },

                _setName: function (attrs) {
                    this.jqueryNode.find("label").text(attrs.name);
                },

                _setPicture: function (attrs) {
                    this.picture = attrs.picture;
                },

                _handleKeyDownEvent: function (e, hasFilter) {
                    if (this.picture)
                        this.picture.handleKeyDownEvent(e);
                    base._handleKeyDownEvent.call(this, e, hasFilter);
                },

                handleMaxLength: function (picture) {
                    this.maxLengthValidator = new MaxLengthValidator(this.id, this.maxLength);
                },

                setMaxLength: function (maxLength) {
                    if (this.maxLengthValidator)
                        this.maxLengthValidator.setMaxLength(maxLength);
                },

                handlePicture: function (picture) {
                    // 0.1 对没有引号的picture做初步的合法性检查
                    if (picture.length > 0 && picture.indexOf('\"') < 0) {
                        // 防止逗号和点号出现
                        if (picture.indexOf(',') >= 0 || picture.indexOf('.') >= 0) {
                            //TODO 处理error
                            console.error("非法的picutre:" + picture);
                            picture = "";
                        }
                        // 防止一个纯数字的大数字
                        var allNum = true;
                        for (var i = 0; i < picture.length; i++) {
                            var c = picture.charAt(i);
                            if (c < '0' || c > '9') {
                                allNum = false;
                                break;
                            }
                        }
                        if (allNum && picture.length > 2) {
                            //TODO 处理error
                            console.error("非法的picture:" + picture);
                            picture = "";
                        }
                    }
                    this.picture = new PictureValidator(this.id, picture, this);
                },

                _setMaxLength: function (attrs) {
                    maxLength = attrs.maxLength;
                },

                _layout: function () {
                    base._layout.call(this);
                    this.handleMaxLength();
                    if (this.picture)
                        this.handlePicture(this.picture);
                },

                _setPanelID: function (attr) {
                    this.panelID = attr.panelID;
                },

                _setEditable: function (attrs) {
                    this.editable = attrs.editable;
                    if (this.editable) {
                        this.jqueryNode.find("input").removeAttr("readOnly");
                    } else {
                        this.jqueryNode.find("input").attr("readOnly", "readOnly");
                    }
                    this.checkRequisite("");
                }
            };
        });
    });
