/*
 * 特别声明：本技术材料受《中华人民共和国著作权法》、《计算机软件保护条例》等法律、法规、行政
 * 规章以及有关国际条约的保护，赞同科技享有知识产权、保留一切权利并视其为技术秘密。未经本公司书
 * 面许可，任何人不得擅自（包括但不限于：以非法的方式复制、传播、展示、镜像、上载、下载）使用，
 * 不得向第三方泄露、透露、披露。否则，本公司将依法追究侵权者的法律责任。特此声明！
 *
 * 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.
 */
import {Widget} from "widget/Widget";
import {EventHub} from "event/EventHub";
import {ADORE} from "ADORE";
import {MessageType} from "event/MessageType";
import {Event as AdoreEvent} from "event/Event";

export class CalendarCombo extends Widget {

    private $dateNode: JQuery;
    private dateElement: HTMLInputElement;
    private pattern: string;
    private text: string;
    private isLayout: boolean;
    private requisite: boolean;
    private hadFocusGain: boolean;
    private hadCloseDatePicker: boolean;
    private defaultPattern: string = "yyyymmmmdd";

    private static template: string = `
    <div class="input-field adore_calendar_combo" tabIndex="-1">
        <i></i>
        <input type="date" class="datepicker" tabIndex="-1">
        <label></label>
    </div>
    `;

    constructor(parentId: string, id: string, style: number) {
        super(parentId, id, style);
        this.$thisNode = $(CalendarCombo.template).attr("id", this.id);
        this.$dateNode = this.$thisNode.find("input");
        this.dateElement = this.$dateNode.get(0) as HTMLInputElement;
        let own = this;
        this.dateElement.readOnly = true;
        this.$dateNode.on("change", function (e: BaseJQueryEventObject) {
            own.handleInput();
        });
        this.$dateNode.on("focus", function (e: BaseJQueryEventObject) {
            if (!own.isHadFocusGain()) {
                own.setHadFocusGain(true);
                own.sendFocusGain();
            } else {
                e.preventDefault();
            }
            own.handleFocus();
        });
        this.$thisNode.on("blur", function (e: BaseJQueryEventObject) {
            own.setHadFocusGain(false);
            own.handleBlur();
        });
        this.$dateNode.attr("id", this.id + "_date");
        this.$thisNode.find("label").attr("for", this.id + "_date");
        this.hadFocusGain = false;
        this.isLayout = false;
        this.enabled = true;
        this.hadCloseDatePicker = true;
        this.pattern = this.defaultPattern; //默认显示格式
    }

    private handleInput() {
        let date: string;
        let charNum: number;
        let charIndexOfMonthIcon: number;
        charIndexOfMonthIcon = this.dateElement.value.indexOf("月");
        date = this.dateElement.value.replace("月", "");
        charNum = date.length;
        //字母数量为奇数时显然需要添0
        if (charNum % 2 === 1) {
            let leftPartOfDate: string = date.slice(0, charIndexOfMonthIcon - 1);
            let rightPartOfDate: string = date.slice(charIndexOfMonthIcon - 1);
            date = `${leftPartOfDate}0${rightPartOfDate}`;
        }
        this.setText({ text: date });
        EventHub.dispatchEvent(MessageType.WIDGET, {
            id: this.id,
            text: date,
            evtType: AdoreEvent.MODIFY,
            syncAttrName: "text"
        });
    }

    public postLayout() {
        let 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 });
        let own = this;
        this.$dateNode.on("close", function () {
            own.handleFocus();
            own.handleClose();
            own.setHadFocusGain(true);
        });
        this.$dateNode.on("open", function () {
            own.handleOpen();
            own.setHadFocusGain(true);
        });
    }

    private isHadFocusGain(): boolean {
        return this.hadFocusGain;
    }

    private setHadFocusGain(hadFocusGain: boolean) {
        this.hadFocusGain = hadFocusGain;
    }

    private handleFocus() {
        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.$thisNode.focus();
        this.setText({ text: this.text }); //此处是为了触发_setRequisite,因为focus的样式跟requisite样式有冲突
    }

    private handleClose() {
        this.hadCloseDatePicker = true;
    }

    private handleOpen() {
        this.hadCloseDatePicker = false;
    }

    private handleBlur() {
        this.$dateNode.removeClass("adore_calendar_combo_focus");
        this.$dateNode.siblings("label").removeClass("adore_calendar_combo_label_focus");
        let val = this.$dateNode.val();
        this.setText({ text: val });
    }

    public setText(args: { text: string }) {
        this.text = args.text;
        if (this.isLayout) {
            this.dateElement.value = this.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 (args.text === null || args.text === "") {
                this.addRequisite();
            } else {
                this.removeRequisite();
            }
        }

    }

    public setRequisite(args: { requisite: boolean }) {
        this.requisite = args.requisite;
        let tempText = this.text;
        this.setText({ text: tempText });
    }
    public setIcon(args: { icon: string }) {
        this.$thisNode.find("i").attr("class", args.icon);
    }

    public setName(args: { name: string }) {
        this.$thisNode.find("label").text(args.name);
    }

    public setEnabled(args: { enabled: boolean }) {
        this.enabled = args.enabled;
        if (this.enabled) {
            this.$thisNode.find("input").removeAttr("disabled");
            this.$thisNode.find("i").removeClass("icon_disabled");
            this.$thisNode.find("label").removeClass("adore_calendar_combo_label_disable");
        } else {
            this.$thisNode.find("input").attr("disabled", "disabled");
            this.$thisNode.find("i").addClass("icon_disabled");
            this.$thisNode.find("label").addClass("adore_calendar_combo_label_disable");
        }
    }

    public setPattern(args: { pattern: string }) {
        this.pattern = args.pattern;
        this.pattern = this.pattern.replace("MM", "mmmm");
        //判断是pattern是否符合输入格式，如果不符合则把其重置为默认格式
        if (this.pattern.length !== 12 && this.pattern.length !== 10) {
            this.pattern = this.defaultPattern; //默认显示格式
        } else if (
            this.pattern.replace("yyyy", "").replace("mmmm", "").replace("dd", "").length !== 0 &&
            this.pattern.replace("yyyy", "").replace("mmmm", "").replace("dd", "").length !== 2
        ) {
            this.pattern = this.defaultPattern; //默认显示格式
        }
        let tmp = this.pattern;
        if (this.isLayout) {
            //这里pickadate的错误提示是因为未引用相关的含有datePiker类的ts库，但实际上编译后可以调用到materalize.js中的该类方法
            this.$dateNode.pickadate({
                format: tmp
            });
        }
    }

    public setFocus() {
        if (this.hadFocusGain) {
            return;
        }
        if (this.hadCloseDatePicker && document.activeElement !== this.$dateNode[0]) {
            this.$dateNode.focus();
        }
    }

    public handleKeyDownEvent(e: Event, hasFilter: boolean) {
        if (this.hadCloseDatePicker) {
            super.handleKeyDownEvent.call(this, e, hasFilter);
        }
    }

    public handleKeyUpEvent(e: Event) {
        if (this.hadCloseDatePicker) {
            super.handleKeyUpEvent.call(this, e);
        }
    }

    private addRequisite() {
        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");
        }
    }

    private removeRequisite() {
        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");
 *
 * */