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

/**
 * Created by heweijun on 2016/10/25.
 */

export class DateText extends Widget {

    private static TemplateCotainer: string = `
            <div class="input-field">
                <input type="text">
                <label></label>
                <span class="span_base"></span>
            </div>
            `;

    private maxLength: number;
    private maxLengthValidator: MaxLengthValidator;
    private format: string;
    private requisite: boolean;


    constructor(parentId: string, id: string, style: number) {
        super(parentId, id, style);
        this.$thisNode = $(DateText.TemplateCotainer).attr({id: this.id + "_containerNode"});
        let own = this;
        this.maxLength = 8;
        this.$thisNode.find("input").attr("id", this.id).on("input", function (e) {
            own.handleOnInput();
            EventHub.dispatchEvent(MessageType.WIDGET, {
                id: id,
                text: $(this).val(),
                evtType: Event.MODIFY,
                syncAttrName: "text"
            })
        }).on('focus', function () {
            own.sendFocusGain();
            SoftwareKeyboardUtil.refresh();
        }).on('blur', function () {
            own.checkRequisite();
            own.handleOnBlur();
        });
    }

    private handleOnInput() {
        this.maxLengthValidator.handleModifyEvent();
        this.checkRequisite();
        if (!this.format) {
            this.format = "yyyy-MM-dd";
        }
        let content = this.$thisNode.find("input").val();
        if (content.length === 8) {
            //判断输入日期是否正确
            let year = content.substr(0, 4);
            let month = content.substr(4, 2);
            let day = content.substr(6, 2);
            let date = new Date(year + "," + month + "," + day);
            if (date.toString().indexOf("Invalid") === -1) {
                let format_date = this.format;
                format_date = format_date.replace(/yyyy/, year).replace(/MM/, month).replace(/dd/, day);
                this.$thisNode.find("input").val(format_date);
                this.maxLengthValidator.setMaxLength(this.format.length);
            }
        }
    }

    private handleOnBlur() {
        let $inputNode = this.$thisNode.find("input");
        if (!this.format) {
            this.format = "yyyy-MM-dd";
        }
        let content = $inputNode.val();
        if (content !== null) {
            if (content === "19000101" || content === "") {
                return;
            } else if (content.length >= 8) {
                //判断输入日期是否正确
                let year: string, month: string, day: string;
                if (content.indexOf("-") !== -1) {
                    let dateArray1 = content.split("-");
                    year = dateArray1[0];
                    month = dateArray1[1];
                    day = dateArray1[2];
                } else if (content.indexOf("/") !== -1) {
                    let dateArray2 = content.split("/");
                    year = dateArray2[0];
                    month = dateArray2[1];
                    day = dateArray2[2];
                } else if (content.indexOf(".") === -1) {
                    year = content.substr(0, 4);
                    month = content.substr(4, 2);
                    day = content.substr(6, 2);
                }
                let date = new Date(year + "," + month + "," + day);
                if (year !== "" && month !== "" && day !== "" && date.toString().indexOf("Invalid") === -1) {
                    let format_date = this.format;
                    format_date = format_date.replace(/yyyy/, year).replace(/MM/, month).replace(/dd/, day);
                    $inputNode.val(format_date);
                    return;
                }
            }
        }
        this.showSpan("输入有误，请重新输入！");
        this.$thisNode.find("input").focus();
    }

    private checkRequisite() {
        if (this.requisite) {
            let inputSelector = this.$thisNode.find("input");
            let value = inputSelector.val();
            if (value) {
                this.removeRequisite();
            } else {
                this.addRequisite();
                this.showSpan("请输入数据！");
            }
        }
    }

    public setRequisite(args: {requisite: boolean}) {
        this.requisite = args.requisite;
        if (this.requisite) {
            if (this.$thisNode.find("input").val()) {
                this.removeRequisite();
            } else {
                this.addRequisite();
            }
        }
    }

    public setEnabled(args: {enabled: boolean}) {
        let enabled = args.enabled;
        let input = this.$thisNode.find("input");
        if (enabled) {
            input.removeAttr("disabled");
            this.$thisNode.find("i").removeClass("icon_disabled");
            if (this.requisite) {
                if (input.val() === null || input.val() === "") {
                    this.addRequisite();
                }
            }
        } else {
            this.$thisNode.find("input").attr("disabled", "disabled");
            if (this.requisite) {
                this.removeRequisite();
            }
            this.$thisNode.find("i").addClass("icon_disabled");
        }
    }

    private addRequisite() {
        this.$thisNode.find("input").addClass("adore_InputRequisite");
        this.$thisNode.find("label").addClass("adore_requisiteColor");
        this.$thisNode.find("i").addClass("adore_requisiteColor");
    }

    private removeRequisite() {
        this.$thisNode.find("input").removeClass("adore_InputRequisite");
        this.$thisNode.find("label").removeClass("adore_requisiteColor");
        this.$thisNode.find("i").removeClass("adore_requisiteColor");
    }

    public handleKeyDownEvent(e: KeyboardEvent, hasFilter: boolean) {
        // Shift+tab,tab,enter,backspace,上箭头，下箭头，左右箭头除外，忽略一切非数字输入
        if (e.keyCode !== Keys.SHIFT && e.keyCode !== Keys.TAB
            && e.keyCode !== Keys.ENTER && e.keyCode !== Keys.LEFT_ARROW
            && e.keyCode !== Keys.UP_ARROW && e.keyCode !== Keys.RIGHT_ARROW
            && e.keyCode !== Keys.DOWN_ARROW && e.keyCode !== Keys.BACKSPACE && (e.keyCode < Keys.NUM_0 || e.keyCode > Keys.NUM_9)
            && (e.keyCode < Keys.NUMPAD_0 || e.keyCode > Keys.NUMPAD_9)) {
            e.preventDefault();
        }
        let value = this.$thisNode.find("input").val();
        if (value.length > 8 && e.keyCode === Keys.BACKSPACE) {
            value = value.replace(/-/g, "").replace(/\//g, "");
            this.$thisNode.find("input").val(value);
            this.maxLengthValidator.setMaxLength(this.maxLength);
        }
        super.handleKeyDownEvent(e, hasFilter);
    }

    public setMaxLength(args: {maxLength: number}) {
        this.maxLength = args.maxLength;
    }

    private handleMaxLength() {
        let textNode = this.$thisNode.find("input")[0] as HTMLInputElement;
        this.maxLengthValidator = new MaxLengthValidator(this.id, textNode, this.maxLength);
    }

    public setText(args: {text: string}) {
        let inputNode = this.$thisNode.find("input");
        inputNode.val(args.text);
        if (args.text.length > 0) {
            inputNode.siblings('label, i').addClass('active');
        } else {
            inputNode.siblings('label, i').removeClass('active');
        }
    }

    public showSpan(msg: string) {
        if (this.$thisNode.find("span").css("display") === "none") {
            this.$thisNode.find("span").html(msg).show().delay(2000).fadeOut(300);
        }
    }

    public setIcon(args: {icon: string}) {
        this.$thisNode.find("i").addClass(args.icon);
        if (this.$thisNode.find("input").val().length > 0) {
            this.$thisNode.find("input").siblings("label, i").addClass("active");
        }
        this.$thisNode.find("span").addClass("span_prefix");
    }

    public setFocus() {
        if (document.activeElement !== this.$thisNode.find("input")[0]) {
            this.$thisNode.find("input").focus();
        }
    }

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

    public setFormat(args: {format: string}) {
        this.format = args.format;
    }

    public postLayout() {
        super.postLayout();
        this.handleMaxLength();
    }


}