/*
 * 特别声明：本技术材料受《中华人民共和国著作权法》、《计算机软件保护条例》等法律、法规、行政
 * 规章以及有关国际条约的保护，赞同科技享有知识产权、保留一切权利并视其为技术秘密。未经本公司书
 * 面许可，任何人不得擅自（包括但不限于：以非法的方式复制、传播、展示、镜像、上载、下载）使用，
 * 不得向第三方泄露、透露、披露。否则，本公司将依法追究侵权者的法律责任。特此声明！
 *
 * 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 huangdeyun on 2015/4/14.
 */
define(["adoreapp/widget/BaseWidget", "adoreapp/widget/EventHub"], function (BaseWidget, EventHub) {
    return BaseWidget.extend(function (base) {
        return {
            _initWidget: function (attrs) {
                this.jqueryNode = $(attrs.template).attr("id", this.id);
                this.dateNode = this.jqueryNode.find("input");
                this.dateNode.attr("readonly", "");
                var own = this;
                this.dateNode.on("change", function (e) {
                    own.handleInput(e);
                });
                this.dateNode.on("focus", function (e) {
                    if (!own.isHadFocusGain()) {
                        own.setHadFocusGain(true);
                        own.sendFocusGain();
                    } else {
                        e.preventDefault();
                    }
                    own.handleFocus();
                });

                this.jqueryNode.on("blur", function (e) {
                    own.setHadFocusGain(false);
                    own.handleBlur();
                });
                this.dateNode.attr("id", this.id + "_date");
                this.jqueryNode.find("label").attr("for", this.id + "_date");
                this.hadFocusGain = false;
                this.isLayout = false;
                this.enabled = true;
                this.hadCloseDatePicker = true;
                this.pattern = "yyyymmmmdd";//默认显示格式
            },

            handleInput: function (e) {
                var dateText = this.dateNode.val();
                var p = this.pattern.replace("yyyy", "").replace("dd", "").replace("mmmm", "");
                if (p.length === 0) {
                    var index = dateText.indexOf("月");
                    var tM = dateText.substring(4, index);
                    dateText = dateText.replace("月", "");
                    if (tM.length === 1) {
                        var tY = dateText.substring(0, 4);
                        var tD = dateText.substring(5);//0123456
                        dateText = tY + "0" + tM + tD;
                    }
                } else {
                    dateText = dateText.replace("月", "");
                    var split = p.substring(0, 1);
                    var arr = dateText.split(split);
                    if (arr[1].length === 1) {
                        dateText = arr[0] + split + "0" + arr[1] + split + arr[2];
                    }
                }
                this._setText({text: dateText});
                EventHub.dispatchEvent(EventHub.MSG_TYPE.WIDGET, {
                    id: this.id,
                    text: dateText,
                    evtType: EventHub.MODIFY,
                    syncAttrName: "text"
                });
            },

            _layout: function () {
                base._layout.call(this);
                var tmp = this.pattern;
                this.dateNode.pickadate({
                    selectMonths: true, // Creates a dropdown to control month
                    selectYears: 30, // Creates a dropdown of 30 years to control year
                    format: tmp,
                    monthsFull: ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"],
                    monthsShort: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
                    weekdaysFull: ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'],
                    today: '今天',
                    clear: '清除',
                    close: '关闭'
                });
                this.isLayout = true;
                this._setText({text: this.text});
                var own = this;
                this.dateNode.on("close", function (e) {
                    own.handleFocus();
                    own.handleClose();
                    own.setHadFocusGain(true);
                });
                this.dateNode.on("open", function (e) {
                    own.handleOpen();
                    own.setHadFocusGain(true);
                });
            },

            isHadFocusGain: function () {
                return this.hadFocusGain;
            },

            setHadFocusGain: function (hadFocusGain) {
                this.hadFocusGain = hadFocusGain;
            },

            handleFocus: function () {
                this.dateNode.addClass("adore_calendar_combo_focus");
                this.dateNode.siblings("label").addClass("adore_calendar_combo_label_focus");
                this.dateNode.siblings('label, i').addClass('active');
                this.jqueryNode.focus();
                this._setText({text: this.text});//此处是为了触发_setRequisite,因为focus的样式跟requisite样式有冲突
            },

            handleClose: function () {
                this.hadCloseDatePicker = true;
            },

            handleOpen: function () {
                this.hadCloseDatePicker = false;
            },

            handleBlur: function () {
                this.dateNode.removeClass("adore_calendar_combo_focus");
                this.dateNode.siblings("label").removeClass("adore_calendar_combo_label_focus");
                var val = this.dateNode.val();
                this._setText({text: val});
            },

            _setText: function (attrs) {
                this.text = attrs.text;
                if (this.isLayout) {
                    this.dateNode.val(attrs.text);
                    if (this.text && this.text.length > 0) {
                        this.dateNode.siblings('label, i').addClass('active');
                    } else {
                        this.dateNode.siblings('label, i').removeClass('active');
                    }
                }
                if (this.requisite) {
                    if (attrs.text === null || attrs.text === "") {
                        this.addRequisite();
                    } else {
                        this.removeRequisite();
                    }
                }
            },

            _setRequisite: function (attrs) {
                this.requisite = attrs.requisite;
                var tempText = this.text;
                this._setText({text: tempText});
            },

            _setIcon: function (attrs) {
                this.jqueryNode.find("i").attr("class", attrs.icon);
            },

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

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

            _setPattern: function (attrs) {
                this.pattern = attrs.pattern;
                this.pattern = this.pattern.replace("MM", "mmmm");
                var tmp = this.pattern;
                if (this.isLayout) {
                    this.dateNode.pickadate({
                        format: tmp
                    });
                }
            },

            _setFocus: function () {
                if (this.hadFocusGain) {
                    return;
                }
                if (this.hadCloseDatePicker && document.activeElement !== this.dateNode[0]) {
                    this.dateNode.focus();
                }
            },

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

            _handleKeyUpEvent: function (e) {
                if (this.hadCloseDatePicker) {
                    base._handleKeyUpEvent.call(this, e);
                }
            },

            addRequisite: function () {
                if (this.enabled) {
                    this.dateNode.addClass('adore_InputRequisite');
                    this.dateNode.siblings("label").addClass('adore_requisiteColor');
                    this.dateNode.siblings("i").addClass('adore_requisiteColor');
                    this.dateNode.removeClass("adore_calendar_combo_focus");
                    this.dateNode.siblings("label").removeClass("adore_calendar_combo_label_focus");
                }
            },

            removeRequisite: function () {
                this.dateNode.removeClass('adore_InputRequisite');
                this.dateNode.siblings("label").removeClass('adore_requisiteColor');
                this.dateNode.siblings("i").removeClass('adore_requisiteColor');
                if (this.enabled && this.hadFocusGain) {
                    this.dateNode.addClass("adore_calendar_combo_focus");
                    this.dateNode.siblings("label").addClass("adore_calendar_combo_label_focus");
                }
            }

        };
    });
})
/**
 * 日期样式(更新materialize.less时需要把下面的样式替换到该文件中  2015-06-02)：
 *
 .picker__day--selected, .picker__day--selected:hover, .picker--focused .picker__day--selected {
  background-color: #ea6953;
}

 .picker__weekday-display {
  background-color: #ea6953;
}

 .picker__date-display {
  background-color: #e5e1e1;
}

 .picker__month-display {
  color: #ea6953;
 }
 .picker__day-display {
  color: #ea6953;
}
 .picker__year-display {
  color: #ea6953;
}

 ##添加日期选择框的open、close发送事件

 需要在materialize.js的3761行代码（close代码块的setTimeout方法最末尾hidden日期选择器后）后面添加如下语句：
 $("#"+STATE.id).trigger("close");

 需要在materialize.js的3643行代码（open代码块的setTimeout方法最末端，打开日期选择器后）后面添加如下语句：
 $("#"+STATE.id).trigger("open");
 *
 * */