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

export class Text extends Widget {

    protected editable: boolean = true; //默认可编辑
    protected requisite: boolean = false; // 默认非必输
    private maxLength = -1;
    private picture: string;
    public panelID: string;
    private maxLengthValidator: MaxLengthValidator;
    private pictureValidator: PictureValidator;
    protected $inputNode: JQuery;

    private static Template = `
            <div class="input-field">
                <i class="icon_normal"></i>
                <input type="text">
                <label></label>
                <span class="span_base"></span>
            </div>
    `;

    constructor(parentId: string, id: string, style: number) {
        super(parentId, id, style);
        let own = this;
        this.$thisNode = $(Text.Template).attr({
            id: this.id + "_containerNode"
        });
        this.$inputNode = this.$thisNode.find("input");
        this.$inputNode.attr("id", this.id).on("input", function (e) {
            // 如果是中文正在输入
            if ($(this).prop('comStart')) return;
            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 () {
            RequisiteUtil.checkRequisite(own.requisite, own, own.editable, own.$inputNode.val(), "请输入数据!");
        }).on('compositionstart', function () {
            // 中文开始输入
            $(this).prop('comStart', true);
        }).on('compositionend', function () {
            // 中文输入结束
            $(this).prop('comStart', false);
        });
        this.$thisNode.find("label").attr("for", this.id);
        if ((this.style & ADORE.Password) === ADORE.Password) {
            this.$inputNode.attr("type", "password");
        }
    }

    protected handleOnInput() {
        this.maxLengthValidator.handleModifyEvent();
        if (this.pictureValidator)
            this.pictureValidator.handleModifyEvent();
        RequisiteUtil.checkRequisite(this.requisite, this, this.editable, this.$inputNode.val(), "请输入数据!");
    }

    public setRequisite(args: { requisite: boolean }) {
        this.requisite = args.requisite;
        RequisiteUtil.checkRequisite(this.requisite, this, this.editable, this.$inputNode.val(), "");
    }

    public setEnabled(args: { enabled: boolean }) {
        this.enabled = args.enabled;
        if (this.enabled) {
            this.$inputNode.removeAttr("disabled");
            this.$thisNode.find("i").removeClass("icon_disabled");
        } else {
            this.$inputNode.attr("disabled", "disabled");
            this.$thisNode.find("i").addClass("icon_disabled");
        }
        RequisiteUtil.checkRequisite(this.requisite, this, this.editable, this.$inputNode.val(), "");
    }

    public setFocus() {
        if (document.activeElement !== this.$inputNode[0]) {
            this.$inputNode.focus();
        }
        RequisiteUtil.checkRequisite(this.requisite, this, this.editable, this.$inputNode.val(), "请输入数据!");
    }

    public setText(args: { text: string }) {
        this.$inputNode.val(args.text);
        if (args.text.length > 0) {
            this.$inputNode.siblings("label, i").addClass("active");
        } else {
            this.$inputNode.siblings("label, i").removeClass("active");
        }
        RequisiteUtil.checkRequisite(this.requisite, this, this.editable, this.$inputNode.val(), "");
    }

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

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

    public setPicture(args: { picture: string }) {
        this.picture = args.picture;
    }

    public handleKeyDownEvent(e: KeyboardEvent, hasFilter: boolean) {
        if (this.pictureValidator)
            this.pictureValidator.handleKeyDownEvent(e);
        super.handleKeyDownEvent(e, hasFilter);
    }

    private handleMaxLength() {
        this.maxLengthValidator = new MaxLengthValidator(this.id, this.$inputNode[0] as HTMLInputElement, this.maxLength);
    }

    public setMaxLength(maxLength: number) {
        if (this.maxLengthValidator)
            this.maxLengthValidator.setMaxLength(maxLength);
    }

    private handlePicture(picture: string) {
        // 0.1 对没有引号的picture做初步的合法性检查
        if (picture.length > 0 && picture.indexOf("\"") < 0) {
            // 防止逗号和点号出现
            if (picture.indexOf(",") >= 0 || picture.indexOf(".") >= 0) {
                //TODO 处理error
                console.error("非法的picutre:" + picture);
                picture = "";
            }
            // 防止一个纯数字的大数字
            let allNum = true;
            for (let i = 0; i < picture.length; i++) {
                let 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.pictureValidator = new PictureValidator(this.id, this.$inputNode[0] as HTMLInputElement, picture, this);
    }

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

    public postLayout() {
        this.handleMaxLength();
        if (this.picture)
            this.handlePicture(this.picture);
    }

    public setPanelID(args: { panelID: string }) {
        this.panelID = args.panelID;
    }

    public setEditable(args: { editable: boolean }) {
        this.editable = args.editable;
        if (this.editable) {
            this.$inputNode.removeAttr("readOnly");
        } else {
            this.$inputNode.attr("readOnly", "readOnly");
        }
        RequisiteUtil.checkRequisite(this.requisite, this, this.editable, this.$inputNode.val(), "");
    }

    public toString(): string {
        return "Text";
    }

    public setTooltip(args : {tooltip : string}){
        // 移除掉旧资源
        this.$inputNode.tooltip('remove');
        if(args.tooltip !== ""){
            // 重新建立资源
            this.$inputNode.attr("data-position","right");
            this.$inputNode.attr("data-tooltip",args.tooltip);
            this.$inputNode.tooltip({delay : 50});
        }
    }

}