odoo.define('web.SwitchCompanyMenu', function (require) {
    "use strict";

    var Model = require('web.Model');
    var session = require('web.session');
    var SystrayMenu = require('web.SystrayMenu');
    var Widget = require('web.Widget');

    var SwitchCompanyMenu = Widget.extend({
        template: 'SwitchCompanyMenu',
        willStart: function () {
            var self = this;
            if (!session.display_switch_company_menu) {
                return $.Deferred().reject();
            } else {
                this._super();
                return new Model('res.users')
                    .call("get_user_company_tree", [session.uid, 'management'], {})
                    .fail(function () {
                        console.log('failed')
                    })
                    .done(function (result) {
                        self.company_tree = result || []
                    });
            }
        },
        onClick: function (event, treeId, treeNode, clickFlag) {
            var company_id = treeNode['id'];
            new Model('res.users').call('write', [
                [session.uid], {
                    'company_id': company_id
                }
            ]).then(function () {
                location.reload();
            });
        },
        start: function () {
            var self = this;
            var zNodes = JSON.parse(self.company_tree);
            var setting = {
                data: {
                    key: {
                        title: "title"
                    },
                },
                callback: {
                    onClick: self.onClick
                }
            };

            $("#org").change(function () {
                var type = $(this).children('option:selected').val();
                new Model('res.users')
                    .call("get_user_company_tree", [session.uid, type], {})
                    .fail(function () {
                        console.log('failed')
                    })
                    .done(function (result) {
                        zNodes = JSON.parse(result);
                        $.fn.zTree.init(self.$('#ztree-content'), setting, zNodes);
                    });
            });

            // 绑定点击事件
            $('#search').click(function () {
                var treeObj = $.fn.zTree.getZTreeObj("ztree-content");
                var keywords = self.$("#search_company_name").val();
                var nodes = treeObj.getNodesByParamFuzzy("name", keywords, null); //根据节点数据的属性搜索，获取条件模糊匹配的节点数据 JSON 对象集合,(keywords)模糊匹配只能针对 String 类型的数据
                if (nodes.length > 0) {
                    treeObj.selectNode(nodes[0]); //会让节点自动滚到到可视区域内
                }
            });

            // 绑定回车事件
            $('#search').keydown(function (event) {
                console.log(event)
                event = window.event;
                if (event.keyCode === 13) {
                    var treeObj = $.fn.zTree.getZTreeObj("ztree-content");
                    var keywords = self.$("#search_company_name").val();
                    var nodes = treeObj.getNodesByParamFuzzy("name", keywords, null); //根据节点数据的属性搜索，获取条件模糊匹配的节点数据 JSON 对象集合,(keywords)模糊匹配只能针对 String 类型的数据
                    if (nodes.length > 0) {
                        treeObj.selectNode(nodes[0]); //会让节点自动滚到到可视区域内
                    }
                }
            });

            // 最近访问的组织
            _.each(session.recent_allowed_company, function (company) {
                var a = '';
                if (company['id'] == session.current_company_id) {
                    a = '<i class="fa fa-check o_current_company"></i>';
                } else {
                    a = '<span class="o_company"/>';
                }
                self.$('#recent').after('<li><a href="#" data-menu="company" data-company-id="' + company['id'] + '">' + a + company['name'] + '</a></li>')
            });
            this.$el.on('click', '.dropdown-menu li a[data-menu]', _.debounce(function (ev) {
                ev.preventDefault();
                var company_id = $(ev.currentTarget).data('company-id');
                new Model('res.users').call('write', [
                    [session.uid], {
                        'company_id': company_id
                    }
                ]).then(function () {
                    location.reload();
                });
            }, 1500, true));
            this.$el.on('click', '.dropdown-menu', function (event) {
                event.stopPropagation();
            });
            self.$('.oe_topbar_name').text(session.current_company_name);
            $.fn.zTree.init(self.$('#ztree-content'), setting, zNodes);
            return this._super();
        }
    });

    // TODO: 将组织切换菜单放到功能菜单最右侧
    SystrayMenu.Items.push(SwitchCompanyMenu);

});