define('Plugin', ['modelFactory',
    'json',
    'dialog',
    'common'],
    function (modelFactory) {
        var mkey = "Plugin";
        var common = {
            openTmpl: openTmpl,
            createGrid: createGrid,
            msgBox: messageBox
        }
        function getPluginVmid(key) {
            return mkey + "_" + key;
        }
        var notPostFilter = function (treeId, parentNode, responseData) {
            var CBCRM = avalon.vmodels.CBCRM
            var ret = [], len = 0, curr, hasEmp = false
            if (responseData.data && responseData.data.groups.length)
                len = responseData.data.groups.length
            while (len) {
                curr = responseData.data.groups[--len]
                //curr.nocheck = true
                hasEmp = false
                curr.Posts.forEach(function (p, i) {
                    p.Users.forEach(function (u, i) {
                        if (u.Id === CBCRM.memberShip.Id) return true
                        u.ParentId = p.Boss ? p.Boss.Id : p.Group
                        u.Post = p.Name;
                        u.Name = u.FullName + "(" + u.Post + ")";
                        ret.push(u)
                    })
                    if (!hasEmp) {
                        hasEmp = p.Users.length > 0
                    }
                })
                ret.push(curr);
            }
            return ret
        }
        var _plugin = {
            /// <summary>
            /// 选择员工
            /// </summary>
            selectUser: function (tmpl, lang, paramData)
            {
                paramData=paramData||{};
                var dialog,ops = avalon.mix(true,{
                    callback: null, dataAuth: null,isJoin:null,
                    ignore: null, ignoreChecked: true, multiple: false,
                    required:true,emsg:"请选择员工！"
                }, paramData);
                if (!ops.dataAuth && ops.isJoin == null) ops.isJoin = true;
                else if (ops.isJoin === -1) ops.isJoin = null;
                var CBCRM = avalon.vmodels.CBCRM, vmid = getPluginVmid("selectUser");
                var mvvm = CBCRM.define(vmid, function (vm) {
                    vm.$skipArray = ['lang']
                    vm.lang = lang
                    vm.destroy = function () {

                    }
                    vm.title = "选择员工";
                    vm.wWidth = 700;
                    vm.wHeight = 600;
                    //初始化
                    vm.init = function (initOps) {
                        var arg = avalon.mix({}, initOps, {
                            btns: [
                                {
                                    name: "确定选择",
                                    focus: true,
                                    callback: mvvm.selectOk
                                }
                            ],
                            afterscan: function () {
                                mvvm.createTree();
                            }
                        });
                        dialog= common.openTmpl(arg);
                        mvvm.initSelect();
                    }
                    vm.initSelect = function () {
                        if (ops.listData && ops.listData.length) {
                            var data = { uids: ops.listData.join(","), resourceId: ops.dataAuth, isJoin: ops.isJoin };
                            if (!data.uids) return;
                            $.post("/Settings/GetUsersByIds", data, function (ret) {
                                if (!ret || !ret.result) return CBCRM.showResult(ret);
                                ret.data.forEach(function (item) {
                                    item.checked = true;
                                    mvvm.grid1.addRow(item);
                                    mvvm.gridm.selectId(item.Id);
                                });
                            });
                        }
                    }
                    vm.selectOk = function () {
                        var list = mvvm.grid1.list.$model;
                        if (ops.required && list.length == 0) {
                            common.msgBox.warning(ops.emsg);
                            return false;
                        }
                        var callback = ops.callback;
                        if (typeof (callback) == "function") {
                            return callback.call(mvvm, list);
                        }
                    }
                    vm.onDblClick = function (item) {
                        item.checked = true;
                        var b = mvvm.selectOk.call(dialog);
                        if (b !== false && dialog) dialog.close();
                    }
                    vm.keyword = "";
                    vm.treeId = vmid + "_catTree";
                    vm.createTree = function () {
                        var treeopts = {
                            async: {
                                url: function (treeId, treeNode) {
                                    var url = '/Settings/GetGroupPost/' + (ops.dataAuth ? ops.dataAuth : "");
                                    url += "?getPost=false";
                                    return url
                                },
                                enable: true,
                                type: 'get',
                                dataFilter: function (treeId, parentNode, ret) {
                                    if (!ret || !ret.result) {
                                        CBCRM.showResult(ret);
                                        return [];
                                    }
                                    var filter = ops.dataFilter;
                                    if (filter) {
                                        var data = filter.apply(this, arguments);
                                        return data;
                                    }
                                    return ret.data;
                                }
                            },
                            callback: {
                                onClick: function (e, treeId, treeNode) {
                                    var gids;
                                    gids = treeNode.Id == 1 ? "" : getNodeIds(treeNode).join(",");
                                    mvvm.addQuery("gids", gids);
                                }
                            },
                            data: {
                                simpleData: {
                                    enable: true,
                                    idKey: 'Id',
                                    pIdKey: 'ParentId'
                                },
                                key: {
                                    name: 'Name'
                                }
                            },
                            check: {
                                enable: false
                            }
                        }
                        $.fn.zTree.init($("#"+mvvm.treeId), treeopts);
                    }
                    vm.$expanTree = true;
                    vm.expanTree = function () {
                        var a = $(this), b = !mvvm.$expanTree;
                        mvvm.$expanTree = b;
                        a.html(b ? "- 收起" : "+ 展开");
                        var tree = $.fn.zTree.getZTreeObj(mvvm.treeId);
                        var nodes = tree.getNodes();
                        if (nodes.length > 0) tree.expandNode(nodes[0], b, true);
                        if (!b) tree.expandNode(nodes[0], !b, false);
                    }
                    vm.grid1=common.createGrid({
                        $lang: lang,
                        multiple:ops.multiple,
                        onRemove: function (ids1, ids,rows) {
                            ids.forEach(function (id) {
                                //mvvm.grid1.removeRow(id);
                                var item = mvvm.gridm.getRow(id);
                                if (item != null) item.checked = false;
                                else {
                                    mvvm.grid1.removeRow(id);
                                }
                            });
                        }
                    });
                    vm.createGridM = function () {
                        var grid = common.createGrid({
                            $lang: lang,
                            multiple:ops.multiple,
                            url: "/Settings/GetMemberShipUsers",
                            pageid: vmid + "_gridm_page",
                            pageOps:{enablesetsize:false,showtotal:true},
                            createQuery: function () {
                                return mvvm.createQuery();
                            },
                            onLoadData:function(ret,list){
                                if (ops.listData && ops.listData.length) {
                                    list.forEach(function (item) {
                                        if (mvvm.grid1.getRow(item.Id)!=null) {
                                            item.checked = true;
                                        }
                                    });
                                }
                                if (ops.ignore && ops.ignore.length) {
                                    var b = typeof (ops.ignore[0]) == "string";
                                    list.forEach(function (item) {
                                        if (ops.ignore.indexOf(b ? item.Id.toString() : item.Id) != -1) {
                                            item.chkDisabled = true;
                                            item.checked = ops.ignoreChecked;
                                        }
                                    });
                                }
                            },
                            onSelectChange: function (index,item,checked) {
                                if (!ops.multiple) mvvm.grid1.clear();
                                var row = mvvm.grid1.getRow(item.Id);
                                if (checked) {
                                    if (row == null)
                                        mvvm.grid1.addRow(item.$model);
                                } else {
                                    if(row!=null)
                                        mvvm.grid1.removeRow(item.Id);
                                }
                            }
                        });
                        return grid;
                    }
                    vm.gridm = vm.createGridM();
                    vm.clear = function () {
                        mvvm.grid1.removeChecked(false);
                    }
                    vm.createQueryData = function () {
                        var queryData = {
                            keyword: { label: "关键词", val: "" },
                            gids: { label: "部门", val: "" },
                            resourceId: { label: "权限资源id", val: ops.dataAuth },
                            isJoin: { label: "是否加入通讯录", val: ops.isJoin }
                        };
                        return queryData;
                    }
                    initQuerys(vm, function (data, name, val, type) {
                        mvvm.gridm.loadData(data);
                    });
                    vm.queryData = vm.createQueryData();
                })
                mvvm.grid1.init();
                mvvm.gridm.init();
                return mvvm;
            },
            /// <summary>
            /// 选择客户
            /// </summary>
            selectCustomer: function (tmpl, lang, paramData) {
                paramData = paramData || {};
                var $const = { CUSTOMER: "customer", CONTACTS: "contacts" }, dialog;
                var ops = avalon.mix(true, {
                    type: $const.CUSTOMER, title: "选择客户",
                    callback: null, customerName: "", superiorCategoryId: "",
                    ignore: null, ignoreChecked: true, multiple: false, brandId: "",
                    required: { cu: true, con: paramData.type == $const.CONTACTS ? true : false },
                    emsgs: { noCu: "请选择客户！", noCon: "请选择联系人！" }
                }, paramData);
                var CBCRM = avalon.vmodels.CBCRM, vmid = getPluginVmid("selectCustomer");
                var mvvm = CBCRM.define(vmid, function (vm) {
                    vm.CONST = $const;
                    vm.$skipArray = ['lang']
                    vm.lang = lang
                    vm.destroy = function () {

                    }
                    vm.type = ops.type;
                    vm.title = ops.title;
                    vm.wWidth = 800;
                    vm.wHeight = 600;
                    //初始化
                    vm.init = function (initOps) {
                        var arg = avalon.mix({}, initOps, {
                            btns: [
                                {
                                    name: "确定选择",
                                    focus: true,
                                    callback: mvvm.selectOk
                                }
                            ],
                            afterscan: function () {
                                mvvm.createTree();
                            }
                        });
                        dialog = common.openTmpl(arg);
                        mvvm.initSelect();
                    }
                    vm.initSelect = function () {
                        if (ops.listData && ops.listData.length) {
                            var ids = [], cids = [];
                            ops.listData.forEach(function (item) {
                                if (item.id) {
                                    ids.push(item.id);
                                    if (item.cid) cids.push(item.cid);
                                } else
                                    ids.push(item);
                            });
                            if (mvvm.type == $const.CUSTOMER) {
                                var data = { ids: ids.join(",") };
                                if (!data.ids) return;
                                $.get("/Customer/GetCustomerContacts", data, function (ret) {
                                    if (!ret || !ret.result) return CBCRM.showResult(ret);
                                    ret.data.customers.forEach(function (item) {
                                        item.checked = true;
                                        if (item.Contacts) {
                                            item.Contacts.forEach(function (c) {
                                                if (cids.indexOf(c.Id) != -1) c.checked = true;
                                            });
                                        }
                                        mvvm.grid1.addRow(item);
                                        //mvvm.gridm.selectId(item.Id);
                                    });
                                });
                            }
                        }
                    }
                    vm.selectOk = function () {
                        var callback = ops.callback,b;
                        if (typeof (callback) != "function") return;
                        if (mvvm.type == $const.CONTACTS) {
                            var cus = mvvm.gridm.getChecked("$model"),
                                cons = mvvm.grid1.getChecked("$model");
                            if (ops.required.cu && cus.length == 0) {
                                messageBox.warning(ops.emsgs.noCu);
                                return false;
                            }
                            if (ops.required.con && cons.length == 0) {
                                messageBox.warning(ops.emsgs.noCon);
                                return false;
                            }
                             b=callback.call(mvvm, cus, cons);
                        } else {
                            var cus = mvvm.grid1.list.$model;
                            if (ops.required.cu && cus.length == 0) {
                                messageBox.warning(ops.emsgs.noCu);
                                return false;
                            }
                            b = callback.call(mvvm, cus);
                        }
                        if (b == null) return;
                        else return b;
                    }
                    vm.onDblClick = function (item) {
                        item.checked = true;
                        var b = mvvm.selectOk.call(dialog);
                        if (b !== false && dialog) dialog.close();
                    }
                    vm.keyword = "";
                    vm.treeId = vmid + "_catTree";
                    vm.createTree = function () {
                        var treeopts = {
                            async: {
                                url: function (treeId, treeNode) {
                                    var cuCatDid=100026
                                    var url = '/Settings/DictionaryAndChild/' + cuCatDid;
                                    return url
                                },
                                enable: true,
                                type: 'get',
                                dataFilter: function (treeId, parentNode, ret) {
                                    if (!ret || !ret.result) {
                                        CBCRM.showResult(ret);
                                        return [];
                                    }
                                    var filter = ops.dataFilter;
                                    if (filter) {
                                        var data = filter.apply(this, arguments);
                                        return data;
                                    } else {
                                        ret.data.forEach(function (item) {
                                            item.ParentId = 1;
                                            item.children = item.Child;
                                            item.selected = true;
                                            delete item.Child;
                                        });
                                        var rows = [{
                                            Id: 1,
                                            Data: "全部客户",
                                            open:true,
                                            children: ret.data
                                        }];
                                        return rows;
                                    }
                                }
                            },
                            callback: {
                                onClick: function (e, treeId, treeNode) {
                                    var data = { superiorCategoryId: "", categoryId: "" };
                                    if (treeNode.Id != 1) {
                                        if (treeNode.ParentId==1) data.superiorCategoryId = treeNode.Id
                                        else data.categoryId = treeNode.Id;
                                    }
                                    mvvm.addQuerys(data);
                                },
                                onAsyncSuccess: function (event, treeId, treeNode, ret) {
                                    if (ops.superiorCategoryId) {
                                        var tree = $.fn.zTree.getZTreeObj(treeId);
                                        var node = tree.getNodeByParam("Id", ops.superiorCategoryId);
                                        if (node != null) tree.selectNode(node, false);
                                    }
                                }
                            },
                            data: {
                                simpleData: {
                                    enable: true,
                                    idKey: 'Id',
                                    pIdKey: 'ParentId'
                                },
                                key: {
                                    name: 'Data'
                                }
                            },
                            check: {
                                enable: false
                            }
                        }
                        $.fn.zTree.init($("#" + mvvm.treeId), treeopts);
                    }
                    vm.grid1 = common.createGrid({
                        $lang: lang,
                        multiple: ops.multiple,
                        onRemove: function (ids1, ids, rows) {
                            if (mvvm.type == $const.CUSTOMER) {
                                ids.forEach(function (id) {
                                    var item = mvvm.gridm.getRow(id);
                                    if (item != null) item.checked = false;
                                    mvvm.grid1.removeRow(id);
                                });
                            }
                        }
                    });
                    vm.createGridM = function () {
                        var grid = common.createGrid({
                            $lang: lang,
                            url: "/Customer/GetCustomerContacts",
                            multiple: ops.multiple,
                            listkey: "customers",
                            pageid: vmid + "_gridm_page",
                            pageOps: {
                                enablesetsize: false, showtotal: true,
                                pagesizeopts: [20, 50, 100, 200, 500, 1000],
                                pagesize:50
                            },

                            createQuery: function () {
                                return mvvm.createQuery();
                            },
                            onLoadData: function (ret, list) {
                                if (ops.listData && ops.listData.length) {
                                    list.forEach(function (item) {
                                        if (mvvm.grid1.getRow(item.Id) != null) {
                                            item.checked = true;
                                        }
                                        if (item.Contacts) {
                                            item.Contacts.forEach(function (c) {
                                                c.checked = false;
                                            });
                                        }
                                    });
                                }
                                if (ops.ignore && ops.ignore.length) {
                                    var b = typeof (ops.ignore[0]) == "string";
                                    list.forEach(function (item) {
                                        if (ops.ignore.indexOf(b ? item.Id.toString() : item.Id) != -1) {
                                            item.chkDisabled = true;
                                            item.checked = ops.ignoreChecked;
                                        }
                                    });
                                }

                                if (mvvm.type == $const.CONTACTS) {
                                    mvvm.grid1.clear();
                                }
                            },
                            onSelectChange: function (index, item, checked) {
                                if (mvvm.type == $const.CUSTOMER) {
                                    if (!ops.multiple) mvvm.grid1.clear();
                                    var row = mvvm.grid1.getRow(item.Id);
                                    if (checked) {
                                        if (row == null) {
                                            var newItem = $.extend(true, {}, item.$model);
                                            //if (newItem.Contacts) newItem.Contacts = where(newItem.Contacts, function (c) { return c.checked });
                                            mvvm.grid1.addRow(newItem);
                                        }
                                    } else {
                                        if (row != null)
                                            mvvm.grid1.removeRow(item.Id);
                                    }
                                } else if (mvvm.type == $const.CONTACTS) {
                                    mvvm.grid1.clear();
                                    if (checked) mvvm.setConcats(item.Contacts);
                                }
                            }
                        });
                        return grid;
                    }
                    vm.gridm = vm.createGridM();
                    vm.clear = function () {
                        mvvm.grid1.removeChecked(false);
                    }
                    vm.setConcats = function (contacts) {
                        mvvm.grid1.clear();
                        if (contacts) {
                            if (contacts.$model) contacts = contacts.$model;
                            contacts.forEach(function (con) {
                                var c = $.extend(true, {}, con);
                                if (c.IsFirst) c.checked = true;
                                mvvm.grid1.addRow(c);
                            });
                        }
                    }
                    vm.createQueryData = function () {
                        var queryData = {
                            customerName: { label: "客户名称", val: ops.customerName },
                            superiorCategoryId: { label: "客户形态", val: ops.superiorCategoryId},
                            categoryId: { label: "客户分类", val: ops.categoryId },
                            brandId: { label: "品牌id", val: ops.brandId }
                        };
                        return queryData;
                    }
                    initQuerys(vm, function (data, name, val, type) {
                        mvvm.gridm.loadData(data);
                    });
                    vm.queryData = vm.createQueryData();
                    //新增联系人
                    vm.addContact = function () {
                        var cus = mvvm.gridm.getChecked();
                        if (cus.length == 0) {
                            return messageBox.warning("请先选择客户！");
                        }
                        var cu = cus[0];
                        var cid = cu.Id;
                        var url = '/Customer/Contacts/' + cid + '/toadd';
                        var data = {
                            customerId: cid, customerName: cu.Name,
                            onSave: function (ret, c) {
                                if (cid) {
                                    $.get("/Customer/GetCustomerContacts", { ids: cid }, function (ret) {
                                        if (ret.result && ret.data.customers.length>0) {
                                            var ncu = ret.data.customers[0];
                                            cu.Contacts = ncu.Contacts;
                                            mvvm.setConcats(ncu.Contacts);
                                        }
                                    })
                                }
                            }
                        }
                        goto(url, true, data);
                    }
                })
                mvvm.grid1.init();
                mvvm.gridm.init();
                return mvvm;
            },
            /// <summary>
            /// 选择合同
            /// </summary>
            selectContract: function (tmpl, lang, paramData) {
                paramData = paramData || {};
                var $const = { CONTRACT: "contract", PRODUCTLIST: "ProductList" }, dialog;
                var ops = avalon.mix(true, {
                    type: $const.CONTRACT, title: "选择合同订单",
                    callback: null, contractName: "", 
                    ignore: null, ignoreChecked: true, multiple: {con:false,det:true}, brandId: "",
                    required: { con: true, detail: paramData.type == $const.CONTRACT? true : false },
                    emsgs: { noCon: "请选择合同订单！", noDetail: "请选择款项期次！" },
                    emsg:"请选择合同订单！",
                }, paramData);
                var CBCRM = avalon.vmodels.CBCRM, vmid = getPluginVmid("selectContract");
                var mvvm = CBCRM.define(vmid, function (vm) {
                    vm.CONST = $const;
                    vm.$skipArray = ['lang']
                    vm.lang = lang
                    vm.destroy = function () {
                    }
                    vm.type = ops.type;
                    vm.title = ops.title;
                    vm.wWidth = 800;
                    vm.wHeight = 550;
                    //初始化
                    vm.init = function (initOps) {
                        var arg = avalon.mix({}, initOps, {
                            btns: [
                                {
                                    name: "确定选择",
                                    focus: true,
                                    callback: mvvm.selectOk
                                }
                            ],
                            afterscan: function () {
                            }
                        });
                        dialog = common.openTmpl(arg);
                        //mvvm.initSelect();
                    }
                    vm.initGrid1Select = function (contractId) {
                        if (!contractId)
                            return;
                        $.post("/FinancialAffairs/GetPlanOfPays", { 'contractid': contractId }, function (ret) {
                            if (!ret || !ret.result)
                                return CBCRM.showResult(ret);
                            mvvm.grid1.initList(ret.data.Source);
                            mvvm.grid1.selectAll(true);
                        });
                    }
                    vm.selectOk = function () {
                        var callback = ops.callback, b;
                        if (mvvm.type == $const.CONTRACT) {
                            var con = mvvm.gridm.getChecked("$model"),
                                detail = mvvm.grid1.getChecked("$model");
                            if (ops.required.con && con.length == 0) {
                                messageBox.warning(ops.emsgs.noDetail);
                                return false;
                            }
                            if (ops.required.detail && detail.length == 0) {
                                messageBox.warning(ops.emsgs.noDetail);
                                return false;
                            }
                            b = callback.call(mvvm, con, detail);
                        } else {
                            var con = mvvm.grid1.list.$model;
                            if (ops.required.con && con.length == 0) {
                                messageBox.warning(ops.emsgs.noCon);
                                return false;
                            }
                            b = callback.call(mvvm, con);
                        }
                    }
                    vm.onDblClick = function (item) {
                        item.checked = true;
                        var b = mvvm.selectOk.call(dialog);
                        if (b !== false && dialog) dialog.close();
                    }
                    vm.keyword = "";
                    vm.grid1=common.createGrid({
                        $lang: lang,
                        multiple:ops.multiple.det,
                        onRemove: function (ids1, ids,rows) {
                        },
                        onSelectChange: function (index, item, checked) {
                            
                        }
                    });
                    vm.createGridM = function () {
                        var grid = common.createGrid({
                            $lang: lang,
                            multiple:ops.multiple.con,
                            url: "/Market/Contract",
                            pageid: vmid + "_gridm_page",
                            pageOps:{enablesetsize:false,showtotal:true},
                            createQuery: function () {
                                return mvvm.createQuery();
                            },
                            onLoadData:function(ret,list){
                                if (ops.listData && ops.listData.length) {
                                    list.forEach(function (item) {
                                        if (mvvm.grid1.getRow(item.Id)!=null) {
                                            item.checked = true;
                                        }
                                    });
                                }
                                if (ops.ignore && ops.ignore.length) {
                                    var b = typeof (ops.ignore[0]) == "string";
                                    list.forEach(function (item) {
                                        if (ops.ignore.indexOf(b ? item.Id.toString() : item.Id) != -1) {
                                            item.chkDisabled = true;
                                            item.checked = ops.ignoreChecked;
                                        }
                                    });
                                }
                            },
                            onSelectChange: function (index, item, checked) {
                                if (mvvm.type == $const.CONTRACT) {
                                    if (!ops.multiple)
                                        mvvm.grid1.clear();
                                    var row = mvvm.grid1.getRow(item.Id);
                                    if (checked) {
                                        if (row == null) {
                                            //var newItem = $.extend(true, {}, item.$model);
                                            // mvvm.grid1.addRow(newItem);
                                            mvvm.initGrid1Select(item.$model.Id);
                                        }
                                    } else {
                                        if (row != null)
                                            mvvm.grid1.removeRow(item.Id);
                                    }
                                } else if (mvvm.type == $const.PRODUCTLIST) {
                                    mvvm.grid1.clear();
                                    if (checked) 
                                        mvvm.initGrid1Select(item.$model.Id);
                                }
                            }
                        });
                        return grid;
                    }
                    vm.gridm = vm.createGridM();
                    vm.clear = function () {
                        mvvm.grid1.removeChecked(false);
                    }
                    vm.createQueryData = function () {
                        var queryData = {
                            key: { label: "关键词", val: "" }
                        };
                        return queryData;
                    }
                    initQuerys(vm, function (data, name, val, type) {
                        mvvm.gridm.loadData(data);
                    });
                    vm.queryData = vm.createQueryData();
                })
                mvvm.grid1.init();
                mvvm.gridm.init();
                return mvvm;

            },
            /// <summary>
            /// 选择员工档案
            /// </summary>
            selectEmy: function (tmpl, lang, paramData) {
                paramData = paramData || {};
                var dialog, ops = avalon.mix(true, {
                    callback: null, dataAuth: null, 
                    ignore: null, ignoreChecked: true, multiple: false,
                    required: true, emsg: "请选择员工！"
                }, paramData);
                var CBCRM = avalon.vmodels.CBCRM, vmid = getPluginVmid("selectEmy");
                var mvvm = CBCRM.define(vmid, function (vm) {
                    vm.$skipArray = ['lang']
                    vm.lang = lang
                    vm.destroy = function () {

                    }
                    vm.title = "选择员工";
                    vm.wWidth = 700;
                    vm.wHeight = 600;
                    //初始化
                    vm.init = function (initOps) {
                        var arg = avalon.mix({}, initOps, {
                            btns: [
                                {
                                    name: "确定选择",
                                    focus: true,
                                    callback: mvvm.selectOk
                                }
                            ],
                            afterscan: function () {
                                mvvm.createTree();
                            }
                        });
                        dialog = common.openTmpl(arg);
                        mvvm.initSelect();
                    }
                    vm.initSelect = function () {
                        if (ops.listData && ops.listData.length) {
                            var data = { uids: ops.listData.join(","), resourceId: ops.dataAuth};
                            if (!data.uids) return;
                            //$.post("/Settings/GetUsersByIds", data, function (ret) {
                            //    if (!ret || !ret.result) return CBCRM.showResult(ret);
                            //    ret.data.forEach(function (item) {
                            //        item.checked = true;
                            //        mvvm.grid1.addRow(item);
                            //        mvvm.gridm.selectId(item.Id);
                            //    });
                            //});
                        }
                    }
                    vm.selectOk = function () {
                        var list = mvvm.grid1.list.$model;
                        if (ops.required && list.length == 0) {
                            common.msgBox.warning(ops.emsg);
                            return false;
                        }
                        var callback = ops.callback;
                        if (typeof (callback) == "function") {
                            return callback.call(mvvm, list);
                        }
                    }
                    vm.onDblClick = function (item) {
                        item.checked = true;
                        var b = mvvm.selectOk.call(dialog);
                        if (b !== false && dialog) dialog.close();
                    }
                    vm.keyword = "";
                    vm.treeId = vmid + "_catTree";
                    vm.createTree = function () {
                        var treeopts = {
                            async: {
                                url: function (treeId, treeNode) {
                                    var url = '/Settings/GetGroupPost/' + (ops.dataAuth ? ops.dataAuth : "");
                                    url += "?getPost=false";
                                    return url
                                },
                                enable: true,
                                type: 'get',
                                dataFilter: function (treeId, parentNode, ret) {
                                    if (!ret || !ret.result) {
                                        CBCRM.showResult(ret);
                                        return [];
                                    }
                                    var filter = ops.dataFilter;
                                    if (filter) {
                                        var data = filter.apply(this, arguments);
                                        return data;
                                    }
                                    return ret.data;
                                }
                            },
                            callback: {
                                onClick: function (e, treeId, treeNode) {
                                    var gid = treeNode.Id;
                                    if (gid == 1) gid = "";
                                    mvvm.addQuery("gid", gid);
                                }
                            },
                            data: {
                                simpleData: {
                                    enable: true,
                                    idKey: 'Id',
                                    pIdKey: 'ParentId'
                                },
                                key: {
                                    name: 'Name'
                                }
                            },
                            check: {
                                enable: false
                            }
                        }
                        $.fn.zTree.init($("#" + mvvm.treeId), treeopts);
                    }
                    vm.$expanTree = true;
                    vm.expanTree = function () {
                        var a = $(this), b = !mvvm.$expanTree;
                        mvvm.$expanTree = b;
                        a.html(b ? "- 收起" : "+ 展开");
                        var tree = $.fn.zTree.getZTreeObj(mvvm.treeId);
                        var nodes = tree.getNodes();
                        if (nodes.length > 0) tree.expandNode(nodes[0], b, true);
                        if (!b) tree.expandNode(nodes[0], !b, false);
                    }
                    vm.grid1 = common.createGrid({
                        $lang: lang,
                        multiple: ops.multiple,
                        onRemove: function (ids1, ids, rows) {
                            ids.forEach(function (id) {
                                //mvvm.grid1.removeRow(id);
                                var item = mvvm.gridm.getRow(id);
                                if (item != null) item.checked = false;
                                else {
                                    mvvm.grid1.removeRow(id);
                                }
                            });
                        }
                    });
                    vm.createGridM = function () {
                        var grid = common.createGrid({
                            $lang: lang,
                            multiple: ops.multiple,
                            url: "/HR/Archive",
                            pageid: vmid + "_gridm_page",
                            pageOps: { enablesetsize: false, showtotal: true },
                            createQuery: function () {
                                return mvvm.createQuery();
                            },
                            onLoadData: function (ret, list) {
                                if (ops.listData && ops.listData.length) {
                                    list.forEach(function (item) {
                                        if (mvvm.grid1.getRow(item.Id) != null) {
                                            item.checked = true;
                                        }
                                    });
                                }
                                if (ops.ignore && ops.ignore.length) {
                                    var b = typeof (ops.ignore[0]) == "string";
                                    list.forEach(function (item) {
                                        if (ops.ignore.indexOf(b ? item.Id.toString() : item.Id) != -1) {
                                            item.chkDisabled = true;
                                            item.checked = ops.ignoreChecked;
                                        }
                                    });
                                }
                            },
                            onSelectChange: function (index, item, checked) {
                                if (!ops.multiple) mvvm.grid1.clear();
                                var row = mvvm.grid1.getRow(item.Id);
                                if (checked) {
                                    if (row == null)
                                        mvvm.grid1.addRow(item.$model);
                                } else {
                                    if (row != null)
                                        mvvm.grid1.removeRow(item.Id);
                                }
                            }
                        });
                        return grid;
                    }
                    vm.gridm = vm.createGridM();
                    vm.clear = function () {
                        mvvm.grid1.removeChecked(false);
                    }
                    vm.createQueryData = function () {
                        var queryData = {
                            keyword: { label: "关键词", val: "" },
                            gid: { label: "部门", val: "" },
                            resourceId: { label: "权限资源id", val: ops.dataAuth }
                        };
                        return queryData;
                    }
                    initQuerys(vm, function (data, name, val, type) {
                        mvvm.gridm.loadData(data);
                    });
                    vm.queryData = vm.createQueryData();
                })
                mvvm.grid1.init();
                mvvm.gridm.init();
                return mvvm;
            }
        }
        var Plugin = {
            create: function (key,paramData) {
                var CBCRM = avalon.vmodels.CBCRM,
                    root = location.protocol + "//" + location.host,
                    tPath = "/" + mkey + "/" + key, version = CBCRM.version;
                var jsExt = '.js?v=' + version;
                var tmplPath = 'text!' + root + CBCRM.tmplRoot + tPath + '.html?v=' + version;
                var langPath = root + CBCRM.langRoot + '/' + CBCRM.lang + '/' + mkey + jsExt;
                var _r = Math.random();
                if (CBCRM.$debug) {
                    tmplPath += "&_r=" + _r;
                    langPath += "&_r=" + _r;
                }
                require([tmplPath, langPath], function (tmpl, lang) {
                    var call = _plugin[key];
                    if (typeof (call) != "function") {
                        console.log("plugin " + key + " not found!");
                        return;
                    }
                    tmpl = tmpl.replace("{{pluginVmid}}", getPluginVmid(key));
                    var mvvm = call(tmpl, lang, paramData);
                    if (typeof (mvvm.init) == "function") {
                        var ops = {
                            vm: mvvm, title: mvvm.title || "", w: mvvm.wWidth || null, h: mvvm.wHeight?mvvm.wHeight +20: null,
                            tmplid:tmpl, iscontent: true,
                            onclose: function () {
                                if (typeof (mvvm.destroy) == "function") mvvm.destroy();
                            }
                        }
                        mvvm.init(ops);
                    }
                });
            }
        };
        function bindKeyFn(key) {
            return function (paramData) {
                Plugin.create(key, paramData);
            }
        }
        for (var key in _plugin) {
            Plugin[key]=bindKeyFn(key);
        }
        return Plugin;
    })