/*
 * 特别声明：本技术材料受《中华人民共和国著作权法》、《计算机软件保护条例》等法律、法规、行政
 * 规章以及有关国际条约的保护，赞同科技享有知识产权、保留一切权利并视其为技术秘密。未经本公司书
 * 面许可，任何人不得擅自（包括但不限于：以非法的方式复制、传播、展示、镜像、上载、下载）使用，
 * 不得向第三方泄露、透露、披露。否则，本公司将依法追究侵权者的法律责任。特此声明！
 *
 * 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/4/14.
 */
define(["adoreapp/hotkey/Keys"] ,function(Keys){
    return Fiber.extend(function ()
    {
        var leftAlignment = false;
        var length =  0;
        var KNOWN_FLAGS = "90^$AN!CcFX.";
        var cursorIndex =  -1;
        return {
            // The `init` method serves as the constructor.
            init: function (id, picture, adoreText)
            {
                this.id = id;
                this.textNode = document.getElementById(this.id);

                var tmpPicture = picture;
                // 1. 起始的减号代表左对齐，对内容处理没有任何指导意义
                if (tmpPicture.indexOf("-") == 0) {
                    this.textNode.style.textAlign = "left";
                    this.leftAlignment = true;
                    tmpPicture = tmpPicture.substring(1);
                }
                // 2. 展开picture,例如3"9""^"2转换为999^XX, 引用内容前的数字是倍数，缺省为1，引用内容缺省为X
                var newPictureBuffer = new Array();
                var singleQuotedBuffer = new Array();
                var inQuote = false;
                var num = 0;
                // 2.1 遍历picture进行展开
                for (var index = 0; index < tmpPicture.length; index++) {
                    var c = tmpPicture.charAt(index);
                    if (c == '"') {
                        if (!inQuote) {
                            // 开始新的引用内容
                            singleQuotedBuffer.length = 0;
                            inQuote = true;
                        } else {
                            // 引用内容处理结束
                            if (num == 0) {
                                // 引号前没有指定数字，那么其实就是1次
                                num = 1;
                            }
                            for (var i = 0; i < num; i++) {
                                var temp = singleQuotedBuffer[0];
                                var savedString = newPictureBuffer.pop();
                                var saveString = savedString ? temp + savedString : temp;
                                newPictureBuffer.push(saveString);
                            }
                            num = 0;
                            singleQuotedBuffer.length = 0;
                            inQuote = false;
                        }
                    } else {
                        if (!inQuote) {
                            // 数字的处理
                            if (c < '0' || c > '9') {
                                console.error(this.id + " --> picture init error: " + picture);
                            }
                            // 应该加上括号，要不然数值不对
                            num = num * 10 + (c - '0');
                        } else {
                            // 引用内容的处理
                            var char = singleQuotedBuffer.length == 0 ? c : singleQuotedBuffer.pop() + c;
                            singleQuotedBuffer.push(char);
                        }
                    }
                }
                // 2.2 如果数字没有用掉，说明引用内容被缺省，补上num个X
                for (var i = 0; i < num; i++) {
                    newPictureBuffer.push('X');
                }
                tmpPicture = newPictureBuffer[0];
                // 3. 只保留第一个小数点
                while (tmpPicture.indexOf('.') != tmpPicture.lastIndexOf('.')) {
                    var lastDotIndex = tmpPicture.lastIndexOf('.');
                    tmpPicture = tmpPicture.substring(0, lastDotIndex)
                    + tmpPicture.substring(lastDotIndex + 1);
                }
                // 4. 计算length, 并修改model中的Max_LENGTH
                this.length = tmpPicture.length;
                //TODO changeMaxLength

                adoreText.setMaxLength(this.length);
                //sender.syncAttribute(this.id, IComponentKeys.MAX_LENGTH, tmpPicture.length, EventTypes.ON_MODIFY_EVENT, null);
                // 5. 0或者！的必须输满属性
                if (tmpPicture.charAt(0) == '0' || tmpPicture.charAt(0) == 'C!') {
                    //TODO set mustFill
                    //sender.syncAttribute(this.id, IComponentKeys.MUSTFILL, true, EventTypes.ON_MODIFY_EVENT, null);
                }
                this.picture = tmpPicture;
            },

            handleKeyDownEvent: function (e) {
                var textValue = this.textNode.value;
                if (this.length > 1) {
                    var start = this.textNode.selectionStart;
                    var end = this.textNode.selectionEnd;
                    if (start == end) {
                        if (e.keyCode === Keys.BACKSPACE) {
                            if (KNOWN_FLAGS.indexOf(this.picture.charAt(this.length
                                - this.textNode.value.length + start - 1)) == -1) {
                                this.textNode.selectionStart = --start;
                                this.textNode.selectionEnd = --end;
                            }
                            if (this.textNode.value.indexOf(/-0./) == 0 && start == 2) {
                                this.textNode.value = this.textNode.value.substring(1);
                                this.textNode.selectionStart = 1;
                                this.textNode.selectionEnd = 1;
                                e.preventDefault();
//                                        event.doit = false;
                            }
                        }

                        if (e.keyCode === 127) {
                            if (KNOWN_FLAGS.indexOf(this.picture.charAt(this.picture.length
                                - this.textNode.length + start)) == -1) {
                                this.textNode.selectionStart = ++start;
                            }
                        }
                    }
                }

                if (this.length > 0) {
                    var byteLength = 0;
                    for (var i = 0; i < this.textNode.value.length; i++) {
                        //charCodeAt()获取字符串中某一个字符的编码
                        var c = this.textNode.value.charCodeAt(i);
//单字节加1
                        if ((c >= 0x0001 && c <= 0x007e) || (0xff60 <= c && c <= 0xff9f)) {
                            byteLength++;
                        }
                        else {
                            byteLength += 2;
                        }
                    }

                    if (textValue != null
                        && byteLength >= this.length
                        && (this.textNode.selectionEnd - this.textNode.selectionStart) == 0) {
                        if (e.keyCode != 8 && e.keyCode != 127
                            && e.keyCode != Keys.RIGHT_ARROW
                            && e.keyCode != Keys.LEFT_ARROW) {
                            if (this.picture.length > 0
                                && this.picture.charAt(0) === '$') {
                                return;
                            }
                            if (this.picture.indexOf('.') === -1) {
                                e.preventDefault();
                            } else {
                                if (this.textNode.selectionStart <= this.textNode.value
                                        .indexOf('.') && e.character != '.') {
                                    e.preventDefault();
                                }
                            }
                        }
                    }
                }
            },

            handleModifyEvent: function () {
                // 1. 获取现有值进行提取过滤
                this.cursorIndex = this.textNode.selectionStart;
                var textValue = this.textNode.value;
                // 1.1 过滤左补的$
                if (this.picture.charAt(0) == '$') {
                    while (textValue.indexOf("$") == 0) {
                        textValue = textValue.substring(1, textValue.length - 1);
                        this.cursorIndex--;
                    }
                    this.cursorIndex = Math.max(this.cursorIndex, 0);
                }
                // 1.2 过滤不认识的标志
                textValue = this.removeUnknownFlags(textValue, this.picture, true);
                var refinedPicture = this.removeUnknownFlags(this.picture, this.picture, false);
                // 2. 开始进行处理
                // 为什么要进行截取字符串呢？明显不合理，所以在这里将截取字符串这段代码注释掉
                // textValue = textValue.substring(0,this.cursorIndex);
                // 2.1 处理有小数点时的情况
                if (refinedPicture.indexOf('.') != -1) {
                    // 2.1.1 如果超过一个小数点，只保留第一个小数点，光标落在小数位之后
                    while (textValue.indexOf('.') != textValue.lastIndexOf('.')) {
                        textValue = textValue.substring(0, textValue.lastIndexOf('.'))
                        + textValue.substring(textValue.lastIndexOf('.') + 1);
                        this.cursorIndex = textValue.indexOf('.') + 1;
                    }
                    // 2.1.2 如果没有小数点，在光标之后加一个小数点
                    if (textValue.indexOf('.') == -1) {
                        textValue = textValue.substring(0, this.cursorIndex) + "."
                        + textValue.substring(this.cursorIndex);
                    }
                    // 2.1.3 起始小数点之前需要补0
                    if (textValue.indexOf(".") == 0) {
                        textValue = "0" + textValue;
                        //this.cursorIndex++;
                    }
                    if (textValue.search(/-./) == 0) {
                        textValue = "-0" + textValue.substring(1);
                        this.cursorIndex++;
                    }
                    // 2.1.4 小数点后面的部分进行比对,
                    // 超过picture范围就截取,如果没有到picture的范围就补0
                    var pictureSuffixLength = refinedPicture.length - 1
                        - refinedPicture.indexOf('.');
                    var strSuffixLength = textValue.length - 1 - textValue.indexOf('.');
                    if (strSuffixLength > pictureSuffixLength) {
                        var newLength = textValue.length - strSuffixLength
                            + pictureSuffixLength;
                        textValue = textValue.substring(0, newLength);
                        this.cursorIndex = Math.min(textValue.length, this.cursorIndex);
                    }
                    for (var i = 0; i < pictureSuffixLength - strSuffixLength; i++) {
                        textValue += "0";
                    }

                }
                // 2.2 处理负号, 如果纯数字有负号，必须放在第一个字符位置
                if (textValue.indexOf('-') > 1) {
                    var otherFlag = refinedPicture.replaceAll("[90\\.]", "");
                    if (otherFlag.length == 0) {
                        textValue = '-' + textValue.replaceAll("-", "");
                    }
                }
                // 2.3 长度控制
                if (textValue.length > refinedPicture.length) {
                    if (this.leftAlignment) {
                        textValue = textValue.substring(0, refinedPicture.length);
                    } else {
                        textValue = textValue.substring(textValue.length - refinedPicture.length);
                    }
                    //TODO 弹框提示
//                            getHost().getDomainPanel().popupControlPrompt(
//                                controller.getId(), "文本框输入溢出");
                }
                // 2.4 遍历s，比对picture进行逐个字符的处理
                for (var i = 0; i < textValue.length;) {
                    // 1.6.1 大写转换
                    if (refinedPicture.charAt(refinedPicture.length - textValue.length
                        + i) == '^') {
                        textValue = textValue.substring(0, i) + textValue.charAt(i).toUpperCase()
                        + textValue.substring(i + 1);
                    }
                    // 1.6.2 非法字符过滤
                    if (!this.checkFormat(
                            refinedPicture.charAt(refinedPicture.length
                            - textValue.length + i), textValue.charAt(i), i)) {
                        textValue = textValue.substring(0, i) + textValue.substring(i + 1);
                        this.cursorIndex = i;
                    } else {
                        i++;
                    }
                }
                // 3. 还原
                // 3.1 还原不认识的标志
                textValue = this.addUnknownFlags(textValue, this.picture);
                // 3.2 还原左边的$
                if (this.picture.charAt(0) == '$') {
                    while (textValue.length < this.length) {
                        textValue = '$' + textValue;
                        this.cursorIndex++;
                    }
                }
                // 4. 用格式化处理后的内容修改当前文本内容
//                        innerModify = true;
                this.textNode.value = textValue;
                this.textNode.selectionStart = this.cursorIndex;
                this.textNode.selectionEnd = this.cursorIndex;
                //TODO changeText
                //sender.syncAttribute(this.id, IComponentKeys.TEXT, this.textNode.value, EventTypes.ON_MODIFY_EVENT, "fireOnChange");
            },
            removeUnknownFlags: function (textValue, picture, modifyCursorIndex) {
                // 1. 从picture中提取不认识的标志
                var unknownFlags = "";
                for (var i = 0; i < picture.length; i++) {
                    if (KNOWN_FLAGS.indexOf(picture.charAt(i)) == -1) {
                        unknownFlags += picture.charAt(i);
                    }
                }
                // 2. 从s中把不认识的标志去除
                for (var i = 0; i < unknownFlags.length; i++) {
                    var j = textValue.indexOf(unknownFlags.charAt(i));
                    if (j != -1) {
                        textValue = textValue.substring(0, j) + textValue.substring(j + 1);
                        if (modifyCursorIndex && this.cursorIndex > j) {
                            this.cursorIndex--;
                        }
                    }
                }
                // $. 返回s
                return textValue;
            },
            checkFormat: function (format, c, index) {
                switch (format) {
                    case '$':
                        if (c == '$') {
                            for (var i = 0; i < index; i++) {
                                if (this.textNode.value.charAt(i) != '$')
                                    return false;
                            }
                        }
                        if ((c < '0' || c > '9') && c != '-') {
                            return false;
                        }
                        if (c == '-' && index == 0)
                            return true;
                        if (c == '-') {
                            for (var i = 0; i < index; i++) {
                                if (text.getText().charAt(i) != '$')
                                    return false;
                            }
                        }
                        break;
                    case '9':

                        if ((c < '0' || c > '9') && c != '-') {
                            return false;
                        }
                        if (c == '-' && index != 0)
                            return false;
                        break;
                    case '0':
                        if (c < '0' || c > '9') {
                            return false;
                        }
                        break;
                    case 'A':
                        if ((c < 'a' || c > 'z') && (c < 'A' || c > 'Z')) {
                            return false;
                        }
                        break;
                    case 'N':
                    case '!':
                        if ((c < 'a' || c > 'z') && (c < 'A' || c > 'Z')
                            && (c < '0' || c > '9')) {
                            return false;
                        }
                        break;
                    case 'C':
                        if (c < 0x3400) {

                            return false;
                        }
                        break;
                    case '^':
                        break;
                    case 'c':
                        if (c >= 0x3400)
                            return false;
                        break;
                    case 'F':
                        if (c < 256) {
                            return false;
                        }
                        break;
                    case 'X':
                        break;
                    default:
                        if (c == format)
                            return true;
                        if (c == '-' && index == 0)
                            return true;
                        return false;
                }
                return true;
            },
            addUnknownFlags: function (s, picture) {
                for (var i = 0; i < s.length; i++) {
                    if (KNOWN_FLAGS.indexOf(picture.charAt(picture.length - 1 - i)) == -1) {
                        s = s.substring(0, s.length - i)
                        + picture.charAt(picture.length - 1 - i)
                        + s.substring(s.length - i);
                        if (this.cursorIndex > s.length - 1 - i) {
                            this.cursorIndex++;
                        }
                    }
                }
                return s;
            }
        }
    })
})