/*
 * 特别声明：本技术材料受《中华人民共和国著作权法》、《计算机软件保护条例》等法律、法规、行政
 * 规章以及有关国际条约的保护，赞同科技享有知识产权、保留一切权利并视其为技术秘密。未经本公司书
 * 面许可，任何人不得擅自（包括但不限于：以非法的方式复制、传播、展示、镜像、上载、下载）使用，
 * 不得向第三方泄露、透露、披露。否则，本公司将依法追究侵权者的法律责任。特此声明！
 *
 * 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/3/31.
 */
define(["adoreapp/widget/BaseWidget", "adoreapp/widget/EventHub"], function (BaseWidget, EventHub) {
    return BaseWidget.extend(function (base) {
        return {
            _initWidget: function (attrs) {
                var template = attrs.template;
                /**
                 * templates数组:
                 *  0:行标记  1:cellType--NONE 2:cellType--TEXT 3:cellType--CHECK 4:cellType--COMBO 5:select option
                 */
                this.templates = template.split("<!-- split -->");
                this.jqueryNode = $(this.templates[0]).attr("id", this.id);
                this.attachNode = this.jqueryNode;
                var tableId = this.parent;
                var itemId = this.id;
                // 添加click事件
                this.jqueryNode.on("click", function (e) {
                    // 过滤行已选中并再次点击选中事件
                    var preTr = $("#" + tableId).find("tr[hadSelected]");
                    if (preTr.length > 0 && preTr[0] === e.currentTarget) {
                        return;
                    }
                    // 过滤th
                    var th = $(this).find("th");
                    if (th.length > 0) {
                        return;
                    }
                    preTr.removeClass("adore_table_item_selected")
                    preTr.removeAttr("hadSelected");
                    $(this).addClass("adore_table_item_selected");
                    $(this).attr("hadSelected", "true");
                    // 发送onclick事件
                    EventHub.dispatchEvent(EventHub.MSG_TYPE.WIDGET, {
                        id: tableId,
                        itemId: itemId,
                        evtType: EventHub.CLICK
                    });
                });
            },

            _setDatas: function (attrs) {
                var itemId = this.id;
                var datas = attrs.datas;
                var columns = this.father.columns;
                var i, j, data, tdNode, id, comboNode, optionNode, cellText;
                this.jqueryNode.find("td").html("<div style='display:none;'></div>");//把注释内容也清理
                this.jqueryNode.find("td").remove();
                // 添加数据
                for (i = 0; i < columns.length; i++) {
                    data = i >= datas.length ? "" : datas[i];
                    cellText = "NONE";
                    //NONE
                    if (columns[i]._type === "NONE") {
                        tdNode = $(this.templates[1]);
                        tdNode.text(data);
                    }
                    // TEXT
                    else if (columns[i]._type === "TEXT") {
                        tdNode = $(this.templates[2]);
                        tdNode.find("input").val(data);
                        cellText = "input";
                        tdNode.find("input").attr("col", i).on("input", function (e) {
                            EventHub.dispatchEvent(EventHub.MSG_TYPE.WIDGET, {
                                id: itemId,
                                col: $(this).attr("col"),
                                data: this.value,
                                evtType: EventHub.MODIFY
                            });
                        });
                    }
                    //CHECK
                    else if (columns[i]._type === "CHECK") {
                        tdNode = $(this.templates[3]);
                        id = columns[i].id + "_" + this.id;
                        tdNode.find("input").attr("id", id);
                        tdNode.find("label").attr("for", id);
                        cellText = "input";
                        if (data === "true") {
                            tdNode.find("input").prop("checked", true);
                        }
                        tdNode.find("input").attr("col", i).on("change", function (e) {
                            EventHub.dispatchEvent(EventHub.MSG_TYPE.WIDGET, {
                                id: itemId,
                                col: $(this).attr("col"),
                                data: this.checked + "",
                                evtType: EventHub.MODIFY
                            });
                        });
                    }
                    // COMBO
                    else if (columns[i]._type === "COMBO") {
                        tdNode = $(this.templates[4]);
                        cellText = "select";
                        if (columns[i]._options) {
                            comboNode = tdNode.find("select");
                            for (j = 0; j < columns[i]._options.length; j++) {
                                optionNode = $(this.templates[6]).text(columns[i]._options[j]);
                                if (columns[i]._options[j] === data) {
                                    optionNode.prop("selected", true);
                                }
                                optionNode.appendTo(comboNode);
                            }
                            comboNode.attr("col", i + "").on("change", function (e) {
                                EventHub.dispatchEvent(EventHub.MSG_TYPE.WIDGET, {
                                    id: itemId,
                                    col: $(this).attr("col"),
                                    data: this.value,
                                    evtType: EventHub.MODIFY
                                });
                            });
                        }
                    }
                    // BUTTON
                    else if (columns[i]._type === "BUTTON") {
                        tdNode = $(this.templates[5]);
                        var begin = data.indexOf("${");
                        var end = data.indexOf("}");
                        cellText = "a";
                        if (begin !== -1 && end > begin) {
                            var clazz = data.substring(begin + 2, end);
                            if (clazz.indexOf("-") !== -1) {
                                tdNode.find("i").addClass(clazz);
                            } else {
                                tdNode.find("i").addClass("adr-" + clazz);
                            }
                        } else {
                            tdNode.find("a").text(data);
                        }
                        tdNode.find("a").attr("col", i + "").on("click", function (e) {
                            EventHub.dispatchEvent(EventHub.MSG_TYPE.WIDGET, {
                                id: itemId,
                                col: $(this).attr("col"),
                                data: data,
                                evtType: EventHub.MODIFY
                            });
                        });
                    }
                    tdNode.appendTo(this.jqueryNode);
                    //setVisible
                    if (columns[i].visible === false) {
                        tdNode.css("display", "none");
                    }
                    //setEnable
                    if (columns[i].enabled === false && cellText !== "NONE") {
                        tdNode.find(cellText).attr("disabled", "disabled");
                    }
                    //setAlignment
                    if (columns[i].alignmentContent) {
                        tdNode.css("text-align", columns[i].alignmentContent);
                    }
                }
            },

            append: function () {
                if (this.parent) {
                    if (this.father._tBody) {
                        //把行标记添加到tbody中
                        this.jqueryNode.appendTo(this.father._tBody);
                    } else {
                        this.jqueryNode.appendTo(this.father.attachNode);
                    }
                }
                else {
                    this.jqueryNode.appendTo(document.body);
                }
            },

            _layout: function () {
                this.append();
            },

            _clearSelection: function () {
                this.jqueryNode.removeClass("adore_table_item_selected")
                this.jqueryNode.removeAttr("hadSelected");
            },

            _setSelection: function () {
                this.jqueryNode.addClass("adore_table_item_selected");
                this.jqueryNode.attr("hadSelected", "true");
            },

            _setColor: function (attrs) {
                this.jqueryNode.css("color", attrs.color);
            },

            _setEnabled: function (attrs) {
                //由TableColumn控制
            },

            _setVisible: function (attrs) {
                //由TableColumn控制
            },

            _dispose: function () {
                base._dispose.call(this);
                if (this.father) {
                    var index = this.father.items.indexOf(this);
                    this.father.items.splice(index, 1);
                }
            }
        };
    });
})