CooWorkApp.controller('admincategory', function ($rootScope, $scope, $location, $sce, cooConfig, g, rest,ngDialog) {
    var openAlert = function (msg) {
        $scope.message = msg;
        $scope.cDlgId = ngDialog.open({
            template: 'tmpl/alert.html',
            className: 'ngdialog-theme-default-dialog',
            controller: 'dialogController',
            overlay: false,
            scope: $scope
        });
    };




    var etor = {
        key:"category"
    };

    $scope.result = [];


    $.when(rest.adminList(etor)).done(function (result) {

        $scope.result = result;
        $("#rowcount").val(result.length);
        $scope.$apply();
        g.jqueryInit('',0);
    });

    $scope.adapter = function () {

        var insertList = [];
        var updateList = [];
        var delIds = [];

        var check = true;
        var reqCheck = true;
        $("[tag='edit']").each(function (i) {
            if ($(this).attr("vad") && $(this).attr("vad") != '' && $(this).attr("vad") != 'null' && $(this).val() != '' && !$(this).parent('div').parent('td').parent('tr').hasClass('hide')) {
                var regx = new RegExp(decodeURIComponent($(this).attr("vad")));
                if (!regx.test($.trim($(this).val()))) {
                    $(this).addClass("fieldInvalid");
                    openAlert($(this).parent('div').find('span').text() + " 格式不对");
                    check = false;
                    return false;
                }
            }
        });

        $("[req='true']").each(function () {
            if ($(this).val() == '' && !$(this).parent('div').parent('td').parent('tr').hasClass('hide')) {
                reqCheck = false;
                openAlert("必填项未填!" + $(this).attr('name'));
                //    window.external.MessageBox("必填项未填!");
                return false;
            }
        });



        if (check && reqCheck) {
            var RArray = [];
            $(".childTable").each(function (i, t) {
                $rows = $(t).find("tr");
                $rows.each(function (j, tr) {
                    if (j > 1) {
                        var rowFlag = false;
                        var erow = {
                            ID: 0,
                            categoryName: '',
                            cOrder: '',
                            status: false,
                            eName: ''
                        };
                        var tid = $(this).find('[name="ID"]').val();
                        if (tid != '' && parseInt(tid) > 0) {
                            erow = g.filterListById($scope.result, parseInt(tid))[0];
                        }
                        $(tr).find("[tag='edit'][v='e']").each(function (i) {
                            rowFlag = true;
                            if (erow.hasOwnProperty($(this).attr('name'))) {
                                var v = $(this).val();
                                if ($(this).is(':checkbox'))
                                    v = $(this).is(":checked");
                                erow[$(this).attr('name')] = v;
                            }
                        });

                        if (rowFlag) {
                            if (tid != '' && parseInt(tid) > 0) {
                                updateList.push(erow);
                            } else {
                                insertList.push(erow);
                            }
                        }

                    }
                });
            });


            var d2 = JSON.stringify(RArray);

            var delv = $('#rowdel').val();
            var delist = [];
            if (delv != undefined && delv != '') {
                delv = delv.toString().substring(1);
                var args = delv.split(',');
                $(args).each(function (i, o) {
                    delist.push(parseInt(o));
                });
            }

            var etor = {
                key: 'category',
                insertList: JSON.stringify(insertList),
                updateList: JSON.stringify(updateList),
                delIds: delist
            };

            if (!checkdupe()) {
                openAlert('分类名称(或英文)重复');
            }
            else {
                console.log(etor);

                if (insertList.length + updateList.length + delist.length == 0) {
                    openAlert('无变化！');

                }
                else {
                    $.when(rest.adminAdapter(etor)).done(function (result) {
                        console.log(result);
                        openAlert('已更新');
                        // console.log(result);
                    });
                }
            }
        }
    };

    var checkdupe = function () {
        var checklist = [];
        var chk = true;
        $rows = $('.childTable').find("tr");
        $rows.each(function (j, tr) {
            if (j > 1) {
                var c = $(tr).find("[name='eName']").val();
                checklist.push(c);
            }
        });
        var flag = [];
        $(checklist).each(function (i, o) {
            if (!flag[o]) {
                flag[o] = true;
            }
            else {
                chk = false;
            }
        });

        return chk;
    };


    $scope.addChild = function () {

        var s = 'table_admin';
        var $table = $("[tag='" + s + "']");
        var $row = $table.find("tr:nth-child(2)").clone();
        $row.removeClass("hide");
        $table.append($row);
        $row.find('select').attr('v', 'e');
        $("#rowCount").val(parseInt($("#rowCount").val()) + 1);
        $('.date-pick').datePicker({ startDate: '1996-01-01' });

    };
});



CooWorkApp.controller('admincategoryauth', function ($rootScope, $scope, $location, $sce, cooConfig, g, rest, ngDialog) {

    var openAlert = function (msg) {
        $scope.message = msg;
        $scope.cDlgId = ngDialog.open({
            template: 'tmpl/alert.html',
            className: 'ngdialog-theme-default-dialog',
            controller: 'dialogController',
            overlay: false,
            scope: $scope
        });
    };




    var etor = {
        key: "categoryAuth"
    };

    var etorRole = {
        key:"roles"
    };

    var etorCate = {
        key: "category"
    };

    $scope.result = [];
    $scope.roles = [];
    $scope.cates = [];

    $.when(rest.adminList(etor), rest.adminList(etorRole), rest.adminList(etorCate)).done(function (result, roles,cates) {


        $(roles).each(function (i,o) {
            o.RoleName = o.RoleName.replace(/^\d+:/ig,'');
        });

        $scope.roles = roles;
        $scope.cates = cates;

        $scope.result = result;
        $("#rowcount").val(result.length);
        $scope.$apply();
        g.jqueryInit('',0);
    });

    $scope.adapter = function () {

        var insertList = [];
        var updateList = [];
        var delIds = [];

        var check = true;
        var reqCheck = true;
        $("[tag='edit']").each(function (i) {
            if ($(this).attr("vad") && $(this).attr("vad") != '' && $(this).attr("vad") != 'null' && $(this).val() != '' && !$(this).parent('div').parent('td').parent('tr').hasClass('hide')) {
                var regx = new RegExp(decodeURIComponent($(this).attr("vad")));
                if (!regx.test($.trim($(this).val()))) {
                    $(this).addClass("fieldInvalid");
                    openAlert($(this).parent('div').find('span').text() + " 格式不对");
                    check = false;
                    return false;
                }
            }
        });

        $("[req='true']").each(function () {
            if ($(this).val() == '' && !$(this).parent('div').parent('td').parent('tr').hasClass('hide')) {
                reqCheck = false;
                openAlert("必填项未填!" + $(this).attr('name'));
                //    window.external.MessageBox("必填项未填!");
                return false;
            }
        });
        


        if (check && reqCheck) {
            var RArray = [];
            $(".childTable").each(function (i, t) {
                $rows = $(t).find("tr");
                $rows.each(function (j, tr) {
                    if (j > 1) {
                        var rowFlag = false;
                        var erow = {
                            ID: 0,
                            categoryId:0,
                            roleId: '00000000-0000-0000-0000-000000000000'
                        };
                        var tid = $(this).find('[name="ID"]').val();
                        if (tid != '' && parseInt(tid) > 0) {
                            erow = g.filterListById($scope.result, parseInt(tid))[0];
                        }
                        $(tr).find("[tag='edit'][v='e']").each(function (i) {
                            rowFlag = true;
                            if (erow.hasOwnProperty($(this).attr('name'))) {
                                var v = $(this).val();
                                if ($(this).is(':checkbox'))
                                    v = $(this).is(":checked");
                                erow[$(this).attr('name')] = v;
                            }
                        });

                        if (rowFlag) {
                            if (tid != '' && parseInt(tid) > 0) {
                                updateList.push(erow);
                            } else {
                                insertList.push(erow);
                            }
                        }

                    }
                });
            });


            var d2 = JSON.stringify(RArray);

            var delv = $('#rowdel').val();
            var delist = [];
            if (delv != undefined && delv != '') {
                delv = delv.toString().substring(1);
                var args = delv.split(',');
                $(args).each(function (i, o) {
                    delist.push(parseInt(o));
                });
            }

            var etor = {
                key: 'categoryAuth',
                insertList: JSON.stringify(insertList),
                updateList: JSON.stringify(updateList),
                delIds: delist
            };

            if (!checkdupe()) {
                openAlert('分类，角色重复设置');
            }
            else {
               // console.log(etor);

                if (insertList.length + updateList.length + delist.length == 0) {
                    openAlert('无变化！');

                }
                else {
                    $.when(rest.adminAdapter(etor)).done(function (result) {
                        console.log(result);
                        openAlert('已更新');
                        // console.log(result);
                    });
                }
            }
        }
    };

    var checkdupe = function () {

        var checklist = [];
        var chk = true;
        $rows = $('.childTable').find("tr");
        $rows.each(function (j, tr) {
            if (j > 1) {
                var c = $(tr).find("[name='categoryId']").val();
                var d = $(tr).find("[name='roleId']").val();
                checklist.push(JSON.stringify({ c: c, d: d }));
            }
        });
        var flag = [];        
        $(checklist).each(function (i, o) {
            if (!flag[o])
            {
                flag[o] = true;
            }
            else
            {
                chk = false;
            }
        });  
        return chk;     
    };



    $scope.addChild = function () {

        var s = 'table_admin';
        var $table = $("[tag='" + s + "']");
        var $row = $table.find("tr:nth-child(2)").clone();
        $row.removeClass("hide");
        $table.append($row);
        $row.find('select').attr('v','e');
        $("#rowCount").val(parseInt($("#rowCount").val()) + 1);
        $('.date-pick').datePicker({ startDate: '1996-01-01' });

    };
});



CooWorkApp.controller('adminauth', function ($rootScope, $scope, $location, $sce, $routeParams, cooConfig, g, rest, ngDialog) {

    var openAlert = function (msg) {
        $scope.message = msg;
        $scope.cDlgId = ngDialog.open({
            template: 'tmpl/alert.html',
            className: 'ngdialog-theme-default-dialog',
            controller: 'dialogController',
            overlay: false,
            scope: $scope
        });
    };


   
    var etorRole = {
        key: "roles"
    };

    var etorCate = {
        key: "category"
    };
  

    var categoryId = $routeParams.categoryId;
    if (categoryId == undefined) categoryId = 0;
    $scope.categoryId = categoryId;

    var etor = {
        key: "auth",
        categoryId:categoryId
    };

    var etorPattern = {
        key: "pattern",
        categoryId: categoryId
    };

    $scope.result = [];
    $scope.roles = [];
    $scope.cates = [];
    $scope.patterns = [];

    $scope.patterns.push({ ID: 0, pName: '请选择' });
    $scope.roles.push({ RoleId: '00000000-0000-0000-0000-000000000000', RoleName: '请选择' });

    $.when(rest.adminList(etorCate)).done(function (cates) {

        $scope.cates = cates;
        if (categoryId > 0)
        {
            $scope.category = g.filterListById(cates, categoryId)[0];

            $.when(rest.adminList(etor), rest.adminList(etorRole), rest.adminList(etorPattern)).done(function (result, roles, patterns) {

                $(roles).each(function (i, o) {
                    o.RoleName = o.RoleName.replace(/^\d+:/ig, '');
                    $scope.roles.push(o);
                });

                $(patterns).each(function (i, o) {
                    if (o.pTypeId == 12 || o.pTypeId == 19) {
                        $scope.patterns.push(o);
                    }
                });          
             
                console.log(result);

                $scope.result = result;
                $("#rowcount").val(result.length);
                $scope.$apply();
                g.jqueryInit('', 0);

            });         
        }
        $scope.$apply();
    });

    $scope.adapter = function () {

        var insertList = [];
        var updateList = [];
        var delIds = [];

        var check = true;
        var reqCheck = true;
        $("[tag='edit']").each(function (i) {
            if ($(this).attr("vad") && $(this).attr("vad") != '' && $(this).attr("vad") != 'null' && $(this).val() != '' && !$(this).parent('div').parent('td').parent('tr').hasClass('hide')) {
                var regx = new RegExp(decodeURIComponent($(this).attr("vad")));
                if (!regx.test($.trim($(this).val()))) {
                    $(this).addClass("fieldInvalid");
                    openAlert($(this).parent('div').find('span').text() + " 格式不对");
                    check = false;
                    return false;
                }
            }
        });

        $("[req='true']").each(function () {
            if ($(this).val() == '' && !$(this).parent('div').parent('td').parent('tr').hasClass('hide')) {
                reqCheck = false;
                openAlert("必填项未填!" + $(this).attr('name'));
                //    window.external.MessageBox("必填项未填!");
                return false;
            }
        });



        if (check && reqCheck) {
            var RArray = [];
            $(".childTable").each(function (i, t) {
                $rows = $(t).find("tr");
                $rows.each(function (j, tr) {
                    if (j > 1) {
                        var rowFlag = false;
                        var erow = {
                            ID: 0,
                            categoryId: categoryId,
                            RoleId: '00000000-0000-0000-0000-000000000000',
                            userPatternId: 0,
                            isReadable: false,
                            isEditable:false
                        };
                        var tid = $(this).find('[name="ID"]').val();
                        if (tid != '' && parseInt(tid) > 0) {
                            erow = g.filterListById($scope.result, parseInt(tid))[0];
                        }
                        $(tr).find("[tag='edit'][v='e']").each(function (i) {
                            rowFlag = true;
                            if (erow.hasOwnProperty($(this).attr('name'))) {
                                var v = $(this).val();
                                if ($(this).is(':checkbox'))
                                    v = $(this).is(":checked");
                                erow[$(this).attr('name')] = v;
                            }
                        });

                        if (rowFlag) {
                            if (tid != '' && parseInt(tid) > 0) {
                                updateList.push(erow);
                            } else {
                                insertList.push(erow);
                            }
                        }

                    }
                });
            });


            var d2 = JSON.stringify(RArray);

            var delv = $('#rowdel').val();
            var delist = [];
            if (delv != undefined && delv != '') {
                delv = delv.toString().substring(1);
                var args = delv.split(',');
                $(args).each(function (i, o) {
                    delist.push(parseInt(o));
                });
            }

            var etor = {
                key: 'auth',
                insertList: JSON.stringify(insertList),
                updateList: JSON.stringify(updateList),
                delIds: delist
            };

            if (!checkdupe()) {
                openAlert('角色,用户列重复设置');
            }
            else {
                 console.log(etor);

                if (insertList.length + updateList.length + delist.length == 0) {
                    openAlert('无变化！');

                }
                else {
                    $.when(rest.adminAdapter(etor)).done(function (result) {
                        console.log(result);
                        openAlert('已更新');
                        // console.log(result);
                    });
                }
            }
        }
    };

    var checkdupe = function () {

        var checklist1 = [];
        var checklist2 = [];
        var chk = true;
        $rows = $('.childTable').find("tr");
        $rows.each(function (j, tr) {
            if (j > 1) {
                var c = $(tr).find("[name='RoleId']").val();
                var d = $(tr).find("[name='userPatternId']").val();
                checklist1.push(c);
                checklist2.push(d);
            }
        });
        var flag1 = [];
        $(checklist1).each(function (i, o) {
            if (o != '00000000-0000-0000-0000-000000000000') {
                if (!flag1[o]) {
                    flag1[o] = true;
                }
                else {
                    chk = false;
                }
            }
        });

        $(checklist2).each(function (i, o) {
            if (o != 0) {
                if (!flag1[o]) {
                    flag1[o] = true;
                }
                else {
                    chk = false;
                }
            }
        });

        return chk;
    };



    $scope.addChild = function () {

        var s = 'table_admin';
        var $table = $("[tag='" + s + "']");
        var $row = $table.find("tr:nth-child(2)").clone();
        $row.removeClass("hide");
        $table.append($row);
        $row.find('select').attr('v', 'e');
        $("#rowCount").val(parseInt($("#rowCount").val()) + 1);
        $('.date-pick').datePicker({ startDate: '1996-01-01' });

    };
});



CooWorkApp.controller('adminpattern', function ($rootScope, $scope, $location, $sce, $routeParams, cooConfig, _, g, rest, ngDialog) {
    var openAlert = function (msg) {
        $scope.message = msg;
        $scope.cDlgId = ngDialog.open({
            template: 'tmpl/alert.html',
            className: 'ngdialog-theme-default-dialog',
            controller: 'dialogController',
            overlay: false,
            scope: $scope
        });
    };


    $scope.result = [];
    $scope.categoryResult = [];

    var categoryId = $routeParams.categoryId;
    if (categoryId == undefined) categoryId = 0;
    $scope.categoryId = categoryId;
    $scope.pTypes = cooConfig.pTypes;
    $scope.category = _.find(cooConfig.allcategory, function (c) { return c.ID == categoryId });

    var etor = {
        key: "pattern",
        categoryId:categoryId
    };

    var etorCate = {
        key:"category"
    };


    $.when(rest.adminList(etorCate)).done(function (categoryResult) {

        $scope.categoryResult = categoryResult;

        console.log(categoryResult);

     //   $scope.category = g.filterListById(categoryResult,categoryId)[0];

        if (categoryId != 0) {
            $.when(rest.adminList(etor)).done(function (result) {
 

                $scope.result = result;

                console.log(result);

                $("#rowcount").val(result.length);
                $scope.$apply();
                g.jqueryInit('',0);
            });
        }

        $scope.$apply();
    });



    $scope.openBase = function () {

        $('#create').attr('disabled',false);
        $('#edit').attr('disabled', false);
        $('#list').attr('disabled', false);
        $('#import').attr('disabled', false);
        $('#export').attr('disabled', false);
        $('#view').attr('disabled', false);
        $('#report').attr('disabled', false);
    };


    $scope.adapter = function () {

        var insertList = [];
        var updateList = [];
        var delIds = [];        

        var check = true;
        var reqCheck = true;      
        $("[tag='edit']").each(function (i) {
            if ($(this).attr("vad") && $(this).attr("vad") != '' && $(this).attr("vad") != 'null' && $(this).val() != ''&& !$(this).parent('div').parent('td').parent('tr').hasClass('hide')) {
                var regx = new RegExp(decodeURIComponent($(this).attr("vad")));
                if (!regx.test($.trim($(this).val()))) {
                    $(this).addClass("fieldInvalid");
                    openAlert($(this).parent('div').find('span').text() + " 格式不对");
                    check = false;
                    return false;
                }
            }
        });

        $("[req='true']").each(function () {
            if ($(this).val() == '' && !$(this).parent('div').parent('td').parent('tr').hasClass('hide')) {
                reqCheck = false;
                openAlert("必填项未填!" + $(this).attr('name'));
                //    window.external.MessageBox("必填项未填!");
                return false;
            }
        });

         


        if (check && reqCheck) {
            var RArray = [];
            $(".childTable").each(function (i, t) {
                $rows = $(t).find("tr");
                $rows.each(function (j, tr) {
                    if (j > 1) {
                        var rowFlag = false;
                        var erow = {
                            ID: 0,
                            pName: '',
                            pTypeId: 1,
                            eName: '',
                            validator: '',
                            required: false,
                            disabled: false,
                            isUnique: false,
                            isSortStatistic: -1,
                            categoryId: categoryId
                        };
                        var tid = $(this).find('[name="ID"]').val();
                        if (tid != '' && parseInt(tid) > 0) {
                            erow = g.filterListById($scope.result, parseInt(tid))[0];
                        }
                        $(tr).find("[tag='edit'][v='e']").each(function (i) {
                            rowFlag = true;
                            if (erow.hasOwnProperty($(this).attr('name'))) {
                                var  v= $(this).val();
                                if ($(this).is(':checkbox'))
                                    v = $(this).is(":checked");

                                if ($(this).attr('name') == 'isSortStatistic') {
                                    if (v) { v = 101 } else { v = -1 };
                                }

                                erow[$(this).attr('name')] = v;
                            }
                        });

                        if (rowFlag) {
                            if (tid != '' && parseInt(tid) > 0) {
                                updateList.push(erow);
                            } else {
                                insertList.push(erow);
                            }
                        }

                    }
                });
            });


            var d2 = JSON.stringify(RArray);

            var delv = $('#rowdel').val();
            var delist = [];
            if (delv != undefined && delv != '') {
                delv = delv.toString().substring(1);
                var args = delv.split(',');
                $(args).each(function (i, o) {
                    delist.push(parseInt(o));
                });
            }



            var etor = {
                key: 'pattern',
                insertList: JSON.stringify(insertList),
                updateList: JSON.stringify(updateList),
                delIds: delist
            };


            console.log(etor);

            if (insertList.length+updateList.length+delist.length==0)
            {
                openAlert('无变化！');

            }
            else
            {
                var dic = [];
                if ($('#base').is(':checked'))
                {
                    dic.push('base');
                    if ($('#create').is(':checked')) { dic.push('create'); }
                    if ($('#edit').is(':checked')) { dic.push('edit'); }
                    if ($('#list').is(':checked')) { dic.push('list'); }
                    if ($('#import').is(':checked')) { dic.push('import'); }
                    if ($('#export').is(':checked')) { dic.push('export'); }
                    if ($('#view').is(':checked')) { dic.push('view'); }
                    if ($('#report').is(':checked')) { dic.push('report'); }
                }


                if (dic.length > 0) {
                    etor['dic'] = dic;

                    console.log(etor);

                    $.when(rest.adminAdapterPattern(etor)).done(function (result) {
                        console.log(result);
                        openAlert('已更新');
                    });


                } else {
                    $.when(rest.adminAdapter(etor)).done(function (result) {
                        console.log(result);
                        openAlert('已更新');
                    });
                }
            }
        }        
    };

    $scope.addChild = function () {

        var s = 'table_admin';
        var $table = $("[tag='" + s + "']");
        var $row = $table.find("tr:nth-child(2)").clone();
        $row.removeClass("hide");
        $table.append($row);
        $row.find('select').attr('v', 'e');
        $("#rowCount").val(parseInt($("#rowCount").val()) + 1);
        $('.date-pick').datePicker({ startDate: '1996-01-01' });

    };
});



CooWorkApp.controller('admincolumnauth', function ($rootScope, $scope, $location, $sce, $routeParams, cooConfig, g, rest, ngDialog) {
    var openAlert = function (msg) {
        $scope.message = msg;
        $scope.cDlgId = ngDialog.open({
            template: 'tmpl/alert.html',
            className: 'ngdialog-theme-default-dialog',
            controller: 'dialogController',
            overlay: false,
            scope: $scope
        });
    };




    $scope.result = [];
    $scope.cates = [];
    $scope.roles = [];
    $scope.patterns = [];
    $scope.roles.push({ RoleId: '00000000-0000-0000-0000-000000000000', RoleName: '请选择' });

    var categoryId = $routeParams.categoryId;
    if (categoryId == undefined) categoryId = 0;
    $scope.categoryId = categoryId;
    $scope.pTypes = cooConfig.pTypes;

    var etor = {
        key: "columnAuth",
        categoryId: categoryId
    };

    var etorRole = {
        key: "roles"
    };

    var etorCate = {
        key: "category"
    };

    var etorPattern = {
        key: "pattern",
        categoryId: categoryId
    };


    $.when(rest.adminList(etorCate)).done(function (cates) {

        $scope.cates = cates;
        $scope.category = g.filterListById(cates, categoryId)[0];

        if (categoryId != 0) {
            $.when(rest.adminList(etor),rest.adminList(etorRole),rest.adminList(etorPattern)).done(function (result,roles,patterns) {

                $(roles).each(function (i, o) {
                    o.RoleName = o.RoleName.replace(/^\d+:/ig, '');
                    $scope.roles.push(o);
                });
                $scope.patterns = patterns;
                $scope.result = result;
                $("#rowcount").val(result.length);
                $scope.$apply();
                g.jqueryInit('', 0);
            });
        }

        $scope.$apply();
    });

    $scope.adapter = function () {

        var insertList = [];
        var updateList = [];
        var delIds = [];

        var check = true;
        var reqCheck = true;
        $("[tag='edit']").each(function (i) {
            if ($(this).attr("vad") && $(this).attr("vad") != '' && $(this).attr("vad") != 'null' && $(this).val() != '' && !$(this).parent('div').parent('td').parent('tr').hasClass('hide')) {
                var regx = new RegExp(decodeURIComponent($(this).attr("vad")));
                if (!regx.test($.trim($(this).val()))) {
                    $(this).addClass("fieldInvalid");
                    openAlert($(this).parent('div').find('span').text() + " 格式不对");
                    check = false;
                    return false;
                }
            }
        });

        $("[req='true']").each(function () {
            if ($(this).val() == '' && !$(this).parent('div').parent('td').parent('tr').hasClass('hide')) {
                reqCheck = false;
                openAlert("必填项未填!" + $(this).attr('name'));
                //    window.external.MessageBox("必填项未填!");
                return false;
            }
        });



        if (check && reqCheck) {
            var RArray = [];
            $(".childTable").each(function (i, t) {
                $rows = $(t).find("tr");
                $rows.each(function (j, tr) {
                    if (j > 1) {
                        var rowFlag = false;
                        var erow = {
                            ID: 0,
                            patternId:0,
                            categoryId: categoryId,
                            roleId: '00000000-0000-0000-0000-000000000000',                         
                            isReadable: false,
                            isEditable: false
                        };
                        var tid = $(this).find('[name="ID"]').val();
                        if (tid != '' && parseInt(tid) > 0) {
                            erow = g.filterListById($scope.result, parseInt(tid))[0];
                        }
                        $(tr).find("[tag='edit'][v='e']").each(function (i) {
                            rowFlag = true;
                            if (erow.hasOwnProperty($(this).attr('name'))) {
                                var v = $(this).val();
                                if ($(this).is(':checkbox'))
                                    v = $(this).is(":checked");
                                erow[$(this).attr('name')] = v;
                            }
                        });

                        if (rowFlag) {
                            if (tid != '' && parseInt(tid) > 0) {
                                updateList.push(erow);
                            } else {
                                insertList.push(erow);
                            }
                        }

                    }
                });
            });


            var d2 = JSON.stringify(RArray);

            var delv = $('#rowdel').val();
            var delist = [];
            if (delv != undefined && delv != '') {
                delv = delv.toString().substring(1);
                var args = delv.split(',');
                $(args).each(function (i, o) {
                    delist.push(parseInt(o));
                });
            }

            var etor = {
                key: 'columnAuth',
                insertList: JSON.stringify(insertList),
                updateList: JSON.stringify(updateList),
                delIds: delist
            };

            if (!checkdupe()) {
                openAlert('列+角色重复设置');
            }
            else {
                console.log(etor);

                if (insertList.length + updateList.length + delist.length == 0) {
                    openAlert('无变化！');

                }
                else {
                    $.when(rest.adminAdapter(etor)).done(function (result) {
                        console.log(result);
                        openAlert('已更新');
                        // console.log(result);
                    });
                }
            }
        }
    };

    var checkdupe = function () {

        var checklist = [];
        var chk = true;
        $rows = $('.childTable').find("tr");
        $rows.each(function (j, tr) {
            if (j > 1) {
                var c = $(tr).find("[name='patternId']").val();
                var d = $(tr).find("[name='roleId']").val();
                checklist.push(JSON.stringify({ c: c, d: d }));
            }
        });
        var flag = [];
        $(checklist).each(function (i, o) {
            if (!flag[o]) {
                flag[o] = true;
            }
            else {
                chk = false;
            }
        });
        return chk;
    };


    $scope.addChild = function () {

        var s = 'table_admin';
        var $table = $("[tag='" + s + "']");
        var $row = $table.find("tr:nth-child(2)").clone();
        $row.removeClass("hide");
        $table.append($row);
        $row.find('select').attr('v', 'e');
        $("#rowCount").val(parseInt($("#rowCount").val()) + 1);
        $('.date-pick').datePicker({ startDate: '1996-01-01' });

    };
});



CooWorkApp.controller('adminpage', function ($rootScope, $scope, $location, $sce, $routeParams, cooConfig, g, rest, ngDialog) {
    var openAlert = function (msg) {
        $scope.message = msg;
        $scope.cDlgId = ngDialog.open({
            template: 'tmpl/alert.html',
            className: 'ngdialog-theme-default-dialog',
            controller: 'dialogController',
            overlay: false,
            scope: $scope
        });
    };




    $scope.result = [];
    $scope.cates = [];
    $scope.pages = [];
    $scope.pages.push({ID:0,UIname:'请选择'});

    var categoryId = $routeParams.categoryId;
    if (categoryId == undefined) categoryId = 0;
    $scope.categoryId = categoryId;
    $scope.pageTypes = cooConfig.pageTypes;

    var etor = {
        key: "page",
        categoryId: categoryId
    };
        

    var etorCate = {
        key: "category"
    };

    var etorPage = {
        key: "page"      
    };


    $.when(rest.adminList(etorCate)).done(function (cates) {

        $scope.cates = cates;
        $scope.category = g.filterListById(cates, categoryId)[0];

        if (categoryId != 0) {
            $.when(rest.adminList(etor), rest.adminList(etorPage)).done(function (result, pages) {
               
                $(pages).each(function (j, p) {
                    if (p.pageType==10||p.pageType==16||p.pageType==99||p.pageType==100||p.pageType==101)
                    {
                        $scope.pages.push(p);
                    }
                });               
               

                $scope.result = result;
                $("#rowcount").val(result.length);
                $scope.$apply();
                g.jqueryInit('', 0);
            });
        }

        $scope.$apply();
    });

    $scope.adapter = function () {

        var insertList = [];
        var updateList = [];
        var delIds = [];

        var check = true;
        var reqCheck = true;
        $("[tag='edit']").each(function (i) {
            if ($(this).attr("vad") && $(this).attr("vad") != '' && $(this).attr("vad") != 'null' && $(this).val() != '' && !$(this).parent('div').parent('td').parent('tr').hasClass('hide')) {
                var regx = new RegExp(decodeURIComponent($(this).attr("vad")));
                if (!regx.test($.trim($(this).val()))) {
                    $(this).addClass("fieldInvalid");
                    openAlert($(this).parent('div').find('span').text() + " 格式不对");
                    check = false;
                    return false;
                }
            }
        });

        $("[req='true']").each(function () {
            if ($(this).val() == '' && !$(this).parent('div').parent('td').parent('tr').hasClass('hide')) {
                reqCheck = false;
                openAlert("必填项未填!" + $(this).attr('name'));
                //    window.external.MessageBox("必填项未填!");
                return false;
            }
        });



        if (check && reqCheck) {
            var RArray = [];
            $(".childTable").each(function (i, t) {
                $rows = $(t).find("tr");
                $rows.each(function (j, tr) {
                    if (j > 1) {
                        var rowFlag = false;
                        var erow = {
                            ID: 0,                          
                            categoryId: categoryId,
                            pageName: '',
                            pageType:2,
                            UIname:'',
                            parentId:null,
                            pageOrder:0
                        };
                        var tid = $(this).find('[name="ID"]').val();
                        if (tid != '' && parseInt(tid) > 0) {
                            erow = g.filterListById($scope.result, parseInt(tid))[0];
                        }
                        $(tr).find("[tag='edit'][v='e']").each(function (i) {
                            rowFlag = true;
                            if (erow.hasOwnProperty($(this).attr('name'))) {
                                var v = $(this).val();
                                if ($(this).is(':checkbox'))
                                    v = $(this).is(":checked");
                                erow[$(this).attr('name')] = v;
                            }
                        });

                        if (rowFlag) {
                            if (tid != '' && parseInt(tid) > 0) {
                                updateList.push(erow);
                            } else {
                                insertList.push(erow);
                            }
                        }

                    }
                });
            });


            var d2 = JSON.stringify(RArray);

            var delv = $('#rowdel').val();
            var delist = [];
            if (delv != undefined && delv != '') {
                delv = delv.toString().substring(1);
                var args = delv.split(',');
                $(args).each(function (i, o) {
                    delist.push(parseInt(o));
                });
            }

            var etor = {
                key: 'page',
                insertList: JSON.stringify(insertList),
                updateList: JSON.stringify(updateList),
                delIds: delist
            };

            if (!checkdupe()) {
                openAlert('页面名称或英文名称重复');
            }
            else {
                console.log(etor);

                if (insertList.length + updateList.length + delist.length == 0) {
                    openAlert('无变化！');

                }
                else {
                    $.when(rest.adminAdapter(etor)).done(function (result) {
                        console.log(result);
                        openAlert('已更新');
                        // console.log(result);
                    });
                }
            }
        }
    };

    var checkdupe = function () {

        var checklist1 = [];
        var checklist2 = [];
        var chk = true;
        $rows = $('.childTable').find("tr");
        $rows.each(function (j, tr) {
            if (j > 1) {
                var c = $(tr).find("[name='pageName']").val();
                var d = $(tr).find("[name='UIname']").val();
                checklist1.push(c);
                checklist2.push(d);
            }
        });
        var flag1 = [];
        $(checklist1).each(function (i, o) {            
                if (!flag1[o]) {
                    flag1[o] = true;
                }
                else {
                    chk = false;
                }            
        });

        $(checklist2).each(function (i, o) {
            if (!flag1[o]) {
                flag1[o] = true;
            }
            else {
                chk = false;
            }
        });
        return chk;
    };


    $scope.addChild = function () {

        var s = 'table_admin';
        var $table = $("[tag='" + s + "']");
        var $row = $table.find("tr:nth-child(2)").clone();
        $row.removeClass("hide");
        $table.append($row);
        $row.find('select').attr('v', 'e');
        $("#rowCount").val(parseInt($("#rowCount").val()) + 1);
        $('.date-pick').datePicker({ startDate: '1996-01-01' });

    };
});



CooWorkApp.controller('adminpageauth', function ($rootScope, $scope, $location, $sce, $routeParams, cooConfig, g, rest, ngDialog) {
    var openAlert = function (msg) {
        $scope.message = msg;
        $scope.cDlgId = ngDialog.open({
            template: 'tmpl/alert.html',
            className: 'ngdialog-theme-default-dialog',
            controller: 'dialogController',
            overlay: false,
            scope: $scope
        });
    };


    $scope.result = [];
    $scope.cates = [];
    $scope.roles = [];
    $scope.pages = [];
    $scope.roles.push({ RoleId: '00000000-0000-0000-0000-000000000000', RoleName: '请选择' });

    var categoryId = $routeParams.categoryId;
    if (categoryId == undefined) categoryId = 0;
    $scope.categoryId = categoryId;


    var etor = {
        key: "pageAuth",
        categoryId: categoryId
    };

    var etorRole = {
        key: "roles"
    };

    var etorCate = {
        key: "category"
    };

    var etorPage = {
        key: "page",
        categoryId: categoryId
    };


    $.when(rest.adminList(etorCate)).done(function (cates) {

        $scope.cates = cates;
        $scope.category = g.filterListById(cates, categoryId)[0];

        if (categoryId != 0) {
            $.when(rest.adminList(etor), rest.adminList(etorRole), rest.adminList(etorPage)).done(function (result, roles, pages) {

                $(roles).each(function (i, o) {
                    o.RoleName = o.RoleName.replace(/^\d+:/ig, '');
                    $scope.roles.push(o);
                });
                $scope.pages = pages;
                $scope.result = result;
                $("#rowcount").val(result.length);
                $scope.$apply();
                g.jqueryInit('', 0);
            });
        }

        $scope.$apply();
    });

    $scope.adapter = function () {

        var insertList = [];
        var updateList = [];
        var delIds = [];

        var check = true;
        var reqCheck = true;
        $("[tag='edit']").each(function (i) {
            if ($(this).attr("vad") && $(this).attr("vad") != '' && $(this).attr("vad") != 'null' && $(this).val() != '' && !$(this).parent('div').parent('td').parent('tr').hasClass('hide')) {
                var regx = new RegExp(decodeURIComponent($(this).attr("vad")));
                if (!regx.test($.trim($(this).val()))) {
                    $(this).addClass("fieldInvalid");
                    openAlert($(this).parent('div').find('span').text() + " 格式不对");
                    check = false;
                    return false;
                }
            }
        });

        $("[req='true']").each(function () {
            if ($(this).val() == '' && !$(this).parent('div').parent('td').parent('tr').hasClass('hide')) {
                reqCheck = false;
                openAlert("必填项未填!" + $(this).attr('name'));
                //    window.external.MessageBox("必填项未填!");
                return false;
            }
        });



        if (check && reqCheck) {
            var RArray = [];
            $(".childTable").each(function (i, t) {
                $rows = $(t).find("tr");
                $rows.each(function (j, tr) {
                    if (j > 1) {
                        var rowFlag = false;
                        var erow = {
                            ID: 0,
                            pageId: 0,
                            categoryId: categoryId,
                            roleId: '00000000-0000-0000-0000-000000000000',
                            isReadable: false,
                            isEditable: false
                        };
                        var tid = $(this).find('[name="ID"]').val();
                        if (tid != '' && parseInt(tid) > 0) {
                            erow = g.filterListById($scope.result, parseInt(tid))[0];
                        }
                        $(tr).find("[tag='edit'][v='e']").each(function (i) {
                            rowFlag = true;
                            if (erow.hasOwnProperty($(this).attr('name'))) {
                                var v = $(this).val();
                                if ($(this).is(':checkbox'))
                                    v = $(this).is(":checked");
                                erow[$(this).attr('name')] = v;
                            }
                        });

                        if (rowFlag) {
                            if (tid != '' && parseInt(tid) > 0) {
                                updateList.push(erow);
                            } else {
                                insertList.push(erow);
                            }
                        }

                    }
                });
            });


            var d2 = JSON.stringify(RArray);

            var delv = $('#rowdel').val();
            var delist = [];
            if (delv != undefined && delv != '') {
                delv = delv.toString().substring(1);
                var args = delv.split(',');
                $(args).each(function (i, o) {
                    delist.push(parseInt(o));
                });
            }

            var etor = {
                key: 'pageAuth',
                insertList: JSON.stringify(insertList),
                updateList: JSON.stringify(updateList),
                delIds: delist
            };

            if (!checkdupe()) {
                openAlert('页面+角色重复设置');
            }
            else {
                console.log(etor);

                if (insertList.length + updateList.length + delist.length == 0) {
                    openAlert('无变化！');

                }
                else {
                    $.when(rest.adminAdapter(etor)).done(function (result) {
                        console.log(result);
                        openAlert('已更新');
                        // console.log(result);
                    });
                }
            }
        }
    };

    var checkdupe = function () {

        var checklist = [];
        var chk = true;
        $rows = $('.childTable').find("tr");
        $rows.each(function (j, tr) {
            if (j > 1) {
                var c = $(tr).find("[name='pageId']").val();
                var d = $(tr).find("[name='roleId']").val();
                checklist.push(JSON.stringify({ c: c, d: d }));
            }
        });
        var flag = [];
        $(checklist).each(function (i, o) {
            if (!flag[o]) {
                flag[o] = true;
            }
            else {
                chk = false;
            }
        });
        return chk;
    };


    $scope.addChild = function () {

        var s = 'table_admin';
        var $table = $("[tag='" + s + "']");
        var $row = $table.find("tr:nth-child(2)").clone();
        $row.removeClass("hide");
        $table.append($row);
        $row.find('select').attr('v', 'e');
        $("#rowCount").val(parseInt($("#rowCount").val()) + 1);
        $('.date-pick').datePicker({ startDate: '1996-01-01' });

    };
});



CooWorkApp.controller('adminelement', function ($rootScope, $scope, $location, $sce, $routeParams, cooConfig, g, rest, _, ngDialog) {
    var openAlert = function (msg) {
        $scope.message = msg;
        $scope.cDlgId = ngDialog.open({
            template: 'tmpl/alert.html',
            className: 'ngdialog-theme-default-dialog',
            controller: 'dialogController',
            overlay: false,
            scope: $scope
        });
    };


    $scope.result = [];
    $scope.cates = [];
    $scope.pages = [];
    $scope.catepages = [];
    $scope.patterns = [];

    var categoryId = $routeParams.categoryId;
    var pageId = $routeParams.pageId;
    if (categoryId == undefined) categoryId = 0;
    if (pageId == undefined) pageId = 0;
    $scope.categoryId = categoryId;
    $scope.pageId = pageId;
 

    var etor = {
        key: "element",
        categoryId:categoryId
    };

    var etorCate = {
        key: "category"
    };

    var etorPage = {
        key: "page"
    };

    var etorPattern = {
        key: "pattern"       
    };
    
    var etorJoin = {
        key:"join",
        categoryId:categoryId
    };


    $.when(rest.adminList(etorCate), rest.adminList(etorPage)).done(function (cates,pages) {

        $scope.cates = cates;
        $scope.category = g.filterListById(cates, categoryId)[0];
        $scope.pages = pages;
        $scope.page = g.filterListById(pages, pageId)[0];

        $(cates).each(function (i,c) {
            var subpages = g.filterPageByCategoryId(pages, c.ID);
            $scope.catepages.push({category:c,pages:subpages});
        });


        if (categoryId != 0 && pageId != 0) {
            $.when(rest.adminList(etor),rest.adminList(etorPattern),rest.adminList(etorJoin)).done(function (result,patterns,joins) {
                $(result).each(function (i, o) {
                    if (o.pageId == pageId) { $scope.result.push(o); };               
                });


                $(joins).each(function (i,o) {
                    var cps = _.filter(patterns, function (n) { return n.categoryId == o.joinCategoryId; });
                    var cate = _.find(cates, function (n) { return n.ID==o.joinCategoryId  });
                    $scope.patterns.push({ c:cate,p:cps });
                });

                var catep = _.find(cates, function (n) { return n.ID == categoryId });
                var cpp = _.filter(patterns, function (n) { return n.categoryId == categoryId; });
                $scope.patterns.push({ c: catep, p: cpp });



               // $scope.patterns = patterns;
                $("#rowcount").val($scope.result);
                $scope.$apply();
                g.jqueryInit('', 0);

            });
        }
        $scope.$apply();
    });

    $scope.adapter = function () {

        var insertList = [];
        var updateList = [];
        var delIds = [];

        var check = true;
        var reqCheck = true;
        $("[tag='edit']").each(function (i) {
            if ($(this).attr("vad") && $(this).attr("vad") != '' && $(this).attr("vad") != 'null' && $(this).val() != '' && !$(this).parent('div').parent('td').parent('tr').hasClass('hide')) {
                var regx = new RegExp(decodeURIComponent($(this).attr("vad")));
                if (!regx.test($.trim($(this).val()))) {
                    $(this).addClass("fieldInvalid");
                    openAlert($(this).parent('div').find('span').text() + " 格式不对");
                    check = false;
                    return false;
                }
            }
        });

        $("[req='true']").each(function () {
            if ($(this).val() == '' && !$(this).parent('div').parent('td').parent('tr').hasClass('hide')) {
                reqCheck = false;
                openAlert("必填项未填!" + $(this).attr('name'));
                //    window.external.MessageBox("必填项未填!");
                return false;
            }
        });



        if (check && reqCheck) {
            var RArray = [];
            $(".childTable").each(function (i, t) {
                $rows = $(t).find("tr");
                $rows.each(function (j, tr) {
                    if (j > 1) {
                        var rowFlag = false;
                        var erow = {
                            ID: 0,
                            categoryId: categoryId,
                            patternId: 0,
                            pageId: pageId,
                            eorder:0
                        };
                        var tid = $(this).find('[name="ID"]').val();
                        if (tid != '' && parseInt(tid) > 0) {
                            erow = g.filterListById($scope.result, parseInt(tid))[0];
                        }
                        $(tr).find("[tag='edit'][v='e']").each(function (i) {
                            rowFlag = true;
                            if (erow.hasOwnProperty($(this).attr('name'))) {
                                var v = $(this).val();
                                if ($(this).is(':checkbox'))
                                    v = $(this).is(":checked");
                                erow[$(this).attr('name')] = v;
                            }
                        });

                        if (rowFlag) {
                            if (tid != '' && parseInt(tid) > 0) {
                                updateList.push(erow);
                            } else {
                                insertList.push(erow);
                            }
                        }

                    }
                });
            });


            var d2 = JSON.stringify(RArray);

            var delv = $('#rowdel').val();
            var delist = [];
            if (delv != undefined && delv != '') {
                delv = delv.toString().substring(1);
                var args = delv.split(',');
                $(args).each(function (i, o) {
                    delist.push(parseInt(o));
                });
            }

            var etor = {
                key: 'element',
                insertList: JSON.stringify(insertList),
                updateList: JSON.stringify(updateList),
                delIds: delist
            };

            if (!checkdupe()) {
                openAlert('元素名称重复');
            }
            else {
                console.log(etor);

                if (insertList.length + updateList.length + delist.length == 0) {
                    openAlert('无变化！');

                }
                else {
                    $.when(rest.adminAdapter(etor)).done(function (result) {
                        console.log(result);
                        openAlert('已更新');
                        // console.log(result);
                    });
                }
            }
        }
    };

    var checkdupe = function () {

        var checklist = [];      
        var chk = true;
        $rows = $('.childTable').find("tr");
        $rows.each(function (j, tr) {
            if (j > 1) {
                var c = $(tr).find("[name='patternId']").val();         
                checklist.push(c);
            }
        });
        var flag= [];
        $(checklist).each(function (i, o) {
            if (!flag[o]) {
                flag[o] = true;
            }
            else {
                chk = false;
            }
        });
         
        return chk;
    };


    $scope.addChild = function () {

        var s = 'table_admin';
        var $table = $("[tag='" + s + "']");
        var $row = $table.find("tr:nth-child(2)").clone();
        $row.removeClass("hide");
        $table.append($row);
        $row.find('select').attr('v', 'e');
        $("#rowCount").val(parseInt($("#rowCount").val()) + 1);
        $('.date-pick').datePicker({ startDate: '1996-01-01' });

    };
});


CooWorkApp.controller('adminevent', function ($rootScope, $scope, $location, $sce, $routeParams, cooConfig, g, rest, ngDialog) {
    var openAlert = function (msg) {
        $scope.message = msg;
        $scope.cDlgId = ngDialog.open({
            template: 'tmpl/alert.html',
            className: 'ngdialog-theme-default-dialog',
            controller: 'dialogController',
            overlay: false,
            scope: $scope
        });
    };


    $scope.result = [];
    $scope.cates = [];
    $scope.pages = [];
    $scope.catepages = [];

    var categoryId = $routeParams.categoryId;
    var pageId = $routeParams.pageId;
    if (categoryId == undefined) categoryId = 0;
    if (pageId == undefined) pageId = 0;
    $scope.categoryId = categoryId;
    $scope.pageId = pageId;
    $scope.eventTypes = cooConfig.eventTypes;

    var etor = {
        key: "event",
        categoryId: categoryId
    };

    var etorCate = {
        key: "category"
    };

    var etorPage = {
        key: "page"
    };



    $.when(rest.adminList(etorCate), rest.adminList(etorPage)).done(function (cates, pages) {

        $scope.cates = cates;
        $scope.category = g.filterListById(cates, categoryId)[0];
        $scope.pages = pages;
        $scope.page = g.filterListById(pages, pageId)[0];

        $(cates).each(function (i, c) {
            var subpages = g.filterPageByCategoryId(pages, c.ID);
            $scope.catepages.push({ category: c, pages: subpages });
        });


        if (categoryId != 0 && pageId != 0) {
            $.when(rest.adminList(etor)).done(function (result) {
                $(result).each(function (i, o) {
                    if (o.pageId == pageId) { $scope.result.push(o); };
                });              
                $("#rowcount").val($scope.result);
                $scope.$apply();
                g.jqueryInit('', 0);

            });
        }
        $scope.$apply();
    });





    $scope.adapter = function () {

        var insertList = [];
        var updateList = [];
        var delIds = [];

        var check = true;
        var reqCheck = true;
        $("[tag='edit']").each(function (i) {
            if ($(this).attr("vad") && $(this).attr("vad") != '' && $(this).attr("vad") != 'null' && $(this).val() != '' && !$(this).parent('div').parent('td').parent('tr').hasClass('hide')) {
                var regx = new RegExp(decodeURIComponent($(this).attr("vad")));
                if (!regx.test($.trim($(this).val()))) {
                    $(this).addClass("fieldInvalid");
                    openAlert($(this).parent('div').find('span').text() + " 格式不对");
                    check = false;
                    return false;
                }
            }
        });

        $("[req='true']").each(function () {
            if ($(this).val() == '' && !$(this).parent('div').parent('td').parent('tr').hasClass('hide')) {
                reqCheck = false;
                openAlert("必填项未填!" + $(this).attr('name'));
                //    window.external.MessageBox("必填项未填!");
                return false;
            }
        });



        if (check && reqCheck) {
            var RArray = [];
            $(".childTable").each(function (i, t) {
                $rows = $(t).find("tr");
                $rows.each(function (j, tr) {
                    if (j > 1) {
                        var rowFlag = false;
                        var erow = {
                            ID: 0,                            
                            pageId: pageId,
                            eventType: 0,
                            eventSource:''                             
                        };
                        var tid = $(this).find('[name="ID"]').val();
                        if (tid != '' && parseInt(tid) > 0) {
                            erow = g.filterListById($scope.result, parseInt(tid))[0];
                        }
                        $(tr).find("[tag='edit'][v='e']").each(function (i) {
                            rowFlag = true;
                            if (erow.hasOwnProperty($(this).attr('name'))) {
                                var v = $(this).val();
                                if ($(this).is(':checkbox'))
                                    v = $(this).is(":checked");                          
                                erow[$(this).attr('name')] = v;
                            }
                        });

                        if (rowFlag) {
                            if (tid != '' && parseInt(tid) > 0) {
                                updateList.push(erow);
                            } else {
                                insertList.push(erow);
                            }
                        }

                    }
                });
            });


            var d2 = JSON.stringify(RArray);

            var delv = $('#rowdel').val();
            var delist = [];
            if (delv != undefined && delv != '') {
                delv = delv.toString().substring(1);
                var args = delv.split(',');
                $(args).each(function (i, o) {
                    delist.push(parseInt(o));
                });
            }

            var etor = {
                key: 'event',
                insertList: JSON.stringify(insertList),
                updateList: JSON.stringify(updateList),
                delIds: delist
            };

            if (!checkdupe()) {
                openAlert('事件类型重复');
            }
            else {
                console.log(etor);

                if (insertList.length + updateList.length + delist.length == 0) {
                    openAlert('无变化！');

                }
                else {
                    $.when(rest.adminAdapter(etor)).done(function (result) {
                        console.log(result);
                        openAlert('已更新');
                        // console.log(result);
                    });
                }
            }
        }
    };

    var checkdupe = function () {

        var checklist = [];
        var chk = true;
        $rows = $('.childTable').find("tr");
        $rows.each(function (j, tr) {
            if (j > 1) {
                var c = $(tr).find("[name='eventType']").val();
                checklist.push(c);
            }
        });
        var flag = [];
        $(checklist).each(function (i, o) {
            if (!flag[o]) {
                flag[o] = true;
            }
            else {
                chk = false;
            }
        });

        return chk;
    };


    $scope.addChild = function () {

        var s = 'table_admin';
        var $table = $("[tag='" + s + "']");
        var $row = $table.find("tr:nth-child(2)").clone();
        $row.removeClass("hide");
        $table.append($row);
        $row.find('select').attr('v', 'e');
        $("#rowCount").val(parseInt($("#rowCount").val()) + 1);
        $('.date-pick').datePicker({ startDate: '1996-01-01' });

    };
});


CooWorkApp.controller('adminstatus', function ($rootScope, $scope, $location, $sce, $routeParams, cooConfig, g, rest, ngDialog) {
    var openAlert = function (msg) {
        $scope.message = msg;
        $scope.cDlgId = ngDialog.open({
            template: 'tmpl/alert.html',
            className: 'ngdialog-theme-default-dialog',
            controller: 'dialogController',
            overlay: false,
            scope: $scope
        });
    };


    $scope.result = [];
    $scope.cates = [];
    $scope.patterns = [];
    $scope.catepatterns = [];
    $scope.roles = [];
 
    var categoryId = $routeParams.categoryId;
    var patternId = $routeParams.patternId;
    var parentId = $routeParams.parentId;
    if (categoryId == undefined) categoryId = 0;
    if (patternId == undefined) patternId = 0;
    $scope.categoryId = categoryId;
    $scope.patternId = patternId;
    $scope.parentId = parentId;
    $scope.parentStatus = [];

    $scope.userPatterns = [];


    var etor = {
        key: "rawStatus",
        categoryId: categoryId
    };

    var etorCate = {
        key: "category"
    }; 

    var etorPattern = {
        key: "pattern"
        
    };

    var etorRole =
        {
            key: "roles"
        };


    var filterByPatternId = function (status,patternId) {
        return status.filter(function (v) {
            return v.patternId == patternId;
        });
    };  


    $.when(rest.adminList(etorCate), rest.adminList(etorPattern)).done(function (cates, patterns) {

        $scope.cates = cates;
        $scope.category = g.filterListById(cates, categoryId)[0];
        $scope.patterns = patterns;
        $scope.pattern = g.filterListById(patterns, patternId)[0];

        $($scope.patterns).each(function (i,o) {
            if (o.pTypeId ==12 || o.pTypeId==19)
            {
                $scope.userPatterns.push(o.ID);
            }
        });

        $(cates).each(function (i, c) {
            var subpatterns = g.filterPattenByCategoryIdSelect(patterns, c.ID);
            $scope.catepatterns.push({ category: c, patterns: subpatterns });
        });


        if (categoryId != 0 && patternId != 0) {
            $.when(rest.adminList(etor), rest.adminList(etorRole)).done(function (result, roles) {
                var selectP = []; flagp = []; selectS = [];
                $(result).each(function (i, o) {                  
                    if (o.patternId == patternId) { $scope.result.push(o); }
                    else
                    {
                    //    var subPattern = g.filterListById($scope.patterns, o.patternId)[0];
                        if (!flagp[o.patternId] && jQuery.inArray(o.patternId, $scope.userPatterns) == -1)
                        {
                            flagp[o.patternId] = true;
                            selectP.push(o.patternId);
                        }
                        selectS.push(o);
                        //o.statusName = o.patternId + ':' + o.statusName;
                        //$scope.parentStatus.push(o);
                    }
                });
                $(selectP).each(function (i, o) {
                    var subs = filterByPatternId(selectS, o);
                    var p = g.filterListById($scope.patterns, o)[0];
                    $scope.parentStatus.push({ p: p, s: subs });

                });

                console.log(selectP);
                console.log(flagp);
                console.log($scope.parentStatus);


                $(roles).each(function (i, o) {
                    o.RoleName = o.RoleName.replace(/^\d+:/ig, '');           
                    $scope.roles.push(o);
                });

              
                $("#rowcount").val($scope.result);
                $scope.$apply();
                g.jqueryInit('', 0);

            });
        }
        $scope.$apply();
    });

    $scope.adapter = function () {

        var insertList = [];
        var updateList = [];
        var delIds = [];

        var check = true;
        var reqCheck = true;
        $("[tag='edit']").each(function (i) {
            if ($(this).attr("vad") && $(this).attr("vad") != '' && $(this).attr("vad") != 'null' && $(this).val() != '' && !$(this).parent('div').parent('td').parent('tr').hasClass('hide')) {
                var regx = new RegExp(decodeURIComponent($(this).attr("vad")));
                if (!regx.test($.trim($(this).val()))) {
                    $(this).addClass("fieldInvalid");
                    openAlert($(this).parent('div').find('span').text() + " 格式不对");
                    check = false;
                    return false;
                }
            }
        });

        $("[req='true']").each(function () {
            if ($(this).val() == '' && !$(this).closest('tr').hasClass('hide')) {
                reqCheck = false;
                openAlert("必填项未填!" + $(this).attr('name'));
                //    window.external.MessageBox("必填项未填!");
                return false;
            }
        });



        if (check && reqCheck) {
            var RArray = [];
            $(".childTable").each(function (i, t) {
                $rows = $(t).find("tr");
                $rows.each(function (j, tr) {
                    if (j > 1) {
                        var rowFlag = false;
                        var erow = {
                            ID: 0,
                            statusName: '',
                            categoryId: categoryId,
                            patternId: patternId ,
                            parentId: parentId,
                            statusOrder:0                        
                        };
                        var tid = $(this).find('[name="ID"]').val();
                        if (tid != '' && parseInt(tid) > 0) {
                            erow = g.filterListById($scope.result, parseInt(tid))[0];
                        }
                        $(tr).find("[tag='edit'][v='e']").each(function (i) {
                            rowFlag = true;
                            if (erow.hasOwnProperty($(this).attr('name'))) {
                                var v = $(this).val();
                                if ($(this).is(':checkbox'))
                                    v = $(this).is(":checked");
                                erow[$(this).attr('name')] = v;
                            }
                        });

                        if (rowFlag) {
                            if (tid != '' && parseInt(tid) > 0) {
                                updateList.push(erow);
                            } else {
                                insertList.push(erow);
                            }
                        }

                    }
                });
            });


            var d2 = JSON.stringify(RArray);

            var delv = $('#rowdel').val();
            var delist = [];
            if (delv != undefined && delv != '') {
                delv = delv.toString().substring(1);
                var args = delv.split(',');
                $(args).each(function (i, o) {
                    delist.push(parseInt(o));
                });
            }

            var etor = {
                key: 'status',
                insertList: JSON.stringify(insertList),
                updateList: JSON.stringify(updateList),
                delIds: delist
            };

            if (!checkdupe()) {
                openAlert('名称重复');
            }
            else {
                console.log(etor);

                if (insertList.length + updateList.length + delist.length == 0) {
                    openAlert('无变化！');

                }
                else {
                    $.when(rest.adminAdapter(etor)).done(function (result) {
                        console.log(result);
                        openAlert('已更新');
                        // console.log(result);
                    });
                }
            }
        }
    };

    var checkdupe = function () {

        var checklist = [];
        var chk = true;
        $rows = $('.childTable').find("tr");
        $rows.each(function (j, tr) {
            if (j > 1) {
                var c = $(tr).find("[name='statusName']").val();
                checklist.push(c);
            }
        });
        var flag = [];
        $(checklist).each(function (i, o) {
            if (!flag[o]) {
                flag[o] = true;
            }
            else {
                chk = false;
            }
        });

        return chk;
    };


    $scope.addChild = function () {

        var s = 'table_admin';
        var $table = $("[tag='" + s + "']");
        var $row = $table.find("tr:nth-child(2)").clone();
        $row.removeClass("hide");
        $table.append($row);
        $row.find('select').attr('v', 'e');
        $("#rowCount").val(parseInt($("#rowCount").val()) + 1);
        $('.date-pick').datePicker({ startDate: '1996-01-01' });

    };
});


CooWorkApp.controller('adminstatusmap', function ($rootScope, $scope, $location, $sce, $routeParams, cooConfig, g, rest, ngDialog) {
    var openAlert = function (msg) {
        $scope.message = msg;
        $scope.cDlgId = ngDialog.open({
            template: 'tmpl/alert.html',
            className: 'ngdialog-theme-default-dialog',
            controller: 'dialogController',
            overlay: false,
            scope: $scope
        });
    };


    $scope.result = [];
    $scope.cates = [];
    $scope.patterns = [];
    $scope.catepatterns = [];
  

    var categoryId = $routeParams.categoryId;
    var patternId = $routeParams.patternId;
    if (categoryId == undefined) categoryId = 0;
    if (patternId == undefined) patternId = 0;
    $scope.categoryId = categoryId;
    $scope.patternId = patternId;



    var etor = {
        key: "statusMap",
        categoryId: categoryId
    };

    var etorCate = {
        key: "category"
    };

    var etorPattern = {
        key: "pattern"

    };


    $.when(rest.adminList(etorCate), rest.adminList(etorPattern)).done(function (cates, patterns) {

        $scope.cates = cates;
        $scope.category = g.filterListById(cates, categoryId)[0];
        $scope.patterns = patterns;
        $scope.pattern = g.filterListById(patterns, patternId)[0];

        $(cates).each(function (i, c) {
            var subpatterns = g.filterPattenByCategoryIdSelect2(patterns, c.ID);
            $scope.catepatterns.push({ category: c, patterns: subpatterns });
        });


        if (categoryId != 0 && patternId != 0) {
            $.when(rest.adminList(etor)).done(function (result) {
            

                $(result).each(function (i, o) {
                    if (o.patternId == patternId) { $scope.result.push(o); }
             
                });

                $("#rowcount").val($scope.result.length);
                $scope.$apply();
                g.jqueryInit('', 0);

            });
        }
        $scope.$apply();
    });


    var statsIdFilter = function (list,id) {
        return list.filter(function (v) {
            return v.cstatusId == id;
        });
    };


    $scope.submit = function () {       
     
        var selectedPatternId = $('#s').val();
        var selectedPattern = g.filterListById($scope.patterns, selectedPatternId)[0];

        var etor =
            {
                key: 'status',
                categoryId:selectedPattern.categoryId
            };


        $.when(rest.adminList(etor)).done(function (result) {
            var k = 0;
            $(result).each(function (i,o) {
                if (o.patternId==selectedPatternId)
                {

                    var f = statsIdFilter($scope.result, o.ID);                 
                    if (f.length==0) {
                        $scope.addChild();
                        var j = 3 + (k++) + parseInt($('#rowcount').val());
                        $("[tag ='table_admin'] tr:nth-child(" + j + ") input[name='cstatusId']").val(o.ID);
                        $("[tag ='table_admin'] tr:nth-child(" + j + ") input[name='cstatusId']").attr('v', 'e');
                        $("[tag ='table_admin'] tr:nth-child(" + j + ") input[name='cstatusId']").parent('div').append(o.statusName);
                    }

                }
            });
            $('#rowcount').val(parseInt($('#rowcount').val()) + k);
            $scope.$apply();
        });

 

    };


    $scope.adapter = function () {

        var insertList = [];
        var updateList = [];
        var delIds = [];

        var check = true;
        var reqCheck = true;
        $("[tag='edit']").each(function (i) {
            if ($(this).attr("vad") && $(this).attr("vad") != '' && $(this).attr("vad") != 'null' && $(this).val() != '' && !$(this).parent('div').parent('td').parent('tr').hasClass('hide')) {
                var regx = new RegExp(decodeURIComponent($(this).attr("vad")));
                if (!regx.test($.trim($(this).val()))) {
                    $(this).addClass("fieldInvalid");
                    openAlert($(this).parent('div').find('span').text() + " 格式不对");
                    check = false;
                    return false;
                }
            }
        });

        $("[req='true']").each(function () {
            if ($(this).val() == '' && !$(this).closest('tr').hasClass('hide')) {
                reqCheck = false;
                openAlert("必填项未填!" + $(this).attr('name'));
                //    window.external.MessageBox("必填项未填!");
                return false;
            }
        });



        if (check && reqCheck) {
            var RArray = [];
            $(".childTable").each(function (i, t) {
                $rows = $(t).find("tr");
                $rows.each(function (j, tr) {
                    if (j > 1) {
                        var rowFlag = false;
                        var erow = {
                            ID: 0,                          
                            categoryId: categoryId,
                            patternId: patternId,
                            cstatusId: 0
                        };
                        var tid = $(this).find('[name="ID"]').val();
                        if (tid != '' && parseInt(tid) > 0) {
                            erow = g.filterListById($scope.result, parseInt(tid))[0];
                        }
                        $(tr).find("[tag='edit'][v='e']").each(function (i) {
                            rowFlag = true;
                            if (erow.hasOwnProperty($(this).attr('name'))) {
                                var v = $(this).val();
                                if ($(this).is(':checkbox'))
                                    v = $(this).is(":checked");
                                erow[$(this).attr('name')] = v;
                            }
                        });

                        if (rowFlag) {
                            if (tid != '' && parseInt(tid) > 0) {
                                updateList.push(erow);
                            } else {
                                insertList.push(erow);
                            }
                        }

                    }
                });
            });


            var d2 = JSON.stringify(RArray);

            var delv = $('#rowdel').val();
            var delist = [];
            if (delv != undefined && delv != '') {
                delv = delv.toString().substring(1);
                var args = delv.split(',');
                $(args).each(function (i, o) {
                    delist.push(parseInt(o));
                });
            }

            var etor = {
                key: 'statusMap',
                insertList: JSON.stringify(insertList),
                updateList: JSON.stringify(updateList),
                delIds: delist
            };

            if (!checkdupe()) {
                openAlert('重复');
            }
            else {
                console.log(etor);

                if (insertList.length + updateList.length + delist.length == 0) {
                    openAlert('无变化！');

                }
                else {
                    $.when(rest.adminAdapter(etor)).done(function (result) {
                        console.log(result);
                        openAlert('已更新');
                        // console.log(result);
                    });
                }
            }
        }
    };

    var checkdupe = function () {

        var checklist = [];
        var chk = true;
        $rows = $('.childTable').find("tr");
        $rows.each(function (j, tr) {
            if (j > 1) {
                var c = $(tr).find("[name='cstatusId']").val();
                checklist.push(c);
            }
        });
        var flag = [];
        $(checklist).each(function (i, o) {
            if (!flag[o]) {
                flag[o] = true;
            }
            else {
                chk = false;
            }
        });

        return chk;
    };


    $scope.addChild = function () {

        var s = 'table_admin';
        var $table = $("[tag='" + s + "']");
        var $row = $table.find("tr:nth-child(2)").clone();
        $row.removeClass("hide");
        $table.append($row);
        $row.find('select').attr('v', 'e');
        $("#rowCount").val(parseInt($("#rowCount").val()) + 1);
        $('.date-pick').datePicker({ startDate: '1996-01-01' });

    };
});



CooWorkApp.controller('admintag', function ($rootScope, $scope, $location, $sce, $routeParams, cooConfig, g, rest, ngDialog) {
    var openAlert = function (msg) {
        $scope.message = msg;
        $scope.cDlgId = ngDialog.open({
            template: 'tmpl/alert.html',
            className: 'ngdialog-theme-default-dialog',
            controller: 'dialogController',
            overlay: false,
            scope: $scope
        });
    };


    $scope.result = [];
    $scope.cates = [];
    $scope.tags = [];
    $scope.tags.push({ ID: 0, UIname: '请选择' });

    var categoryId = $routeParams.categoryId;
    if (categoryId == undefined) categoryId = 0;
    $scope.categoryId = categoryId;
   
    var etor = {
        key: "tag",
        categoryId: categoryId
    };

    var etorCate = {
        key: "category"
    }; 


    $.when(rest.adminList(etorCate)).done(function (cates) {

        $scope.cates = cates;
        $scope.category = g.filterListById(cates, categoryId)[0];

        if (categoryId != 0) {
            $.when(rest.adminList(etor)).done(function (result) {               

                $scope.result = result;
                $("#rowcount").val(result.length);
                $scope.$apply();
                g.jqueryInit('', 0);
            });
        }

        $scope.$apply();
    });

    $scope.adapter = function () {

        var insertList = [];
        var updateList = [];
        var delIds = [];

        var check = true;
        var reqCheck = true;
        $("[tag='edit']").each(function (i) {
            if ($(this).attr("vad") && $(this).attr("vad") != '' && $(this).attr("vad") != 'null' && $(this).val() != '' && !$(this).parent('div').parent('td').parent('tr').hasClass('hide')) {
                var regx = new RegExp(decodeURIComponent($(this).attr("vad")));
                if (!regx.test($.trim($(this).val()))) {
                    $(this).addClass("fieldInvalid");
                    openAlert($(this).parent('div').find('span').text() + " 格式不对");
                    check = false;
                    return false;
                }
            }
        });

        $("[req='true']").each(function () {
            if ($(this).val() == '' && !$(this).parent('div').parent('td').parent('tr').hasClass('hide')) {
                reqCheck = false;
                openAlert("必填项未填!" + $(this).attr('name'));
                //    window.external.MessageBox("必填项未填!");
                return false;
            }
        });



        if (check && reqCheck) {
            var RArray = [];
            $(".childTable").each(function (i, t) {
                $rows = $(t).find("tr");
                $rows.each(function (j, tr) {
                    if (j > 1) {
                        var rowFlag = false;
                        var erow = {
                            ID: 0,
                            categoryId: categoryId,
                            tagName:'',                          
                        };
                        var tid = $(this).find('[name="ID"]').val();
                        if (tid != '' && parseInt(tid) > 0) {
                            erow = g.filterListById($scope.result, parseInt(tid))[0];
                        }
                        $(tr).find("[tag='edit'][v='e']").each(function (i) {
                            rowFlag = true;
                            if (erow.hasOwnProperty($(this).attr('name'))) {
                                var v = $(this).val();
                                if ($(this).is(':checkbox'))
                                    v = $(this).is(":checked");
                                erow[$(this).attr('name')] = v;
                            }
                        });

                        if (rowFlag) {
                            if (tid != '' && parseInt(tid) > 0) {
                                updateList.push(erow);
                            } else {
                                insertList.push(erow);
                            }
                        }

                    }
                });
            });


            var d2 = JSON.stringify(RArray);

            var delv = $('#rowdel').val();
            var delist = [];
            if (delv != undefined && delv != '') {
                delv = delv.toString().substring(1);
                var args = delv.split(',');
                $(args).each(function (i, o) {
                    delist.push(parseInt(o));
                });
            }

            var etor = {
                key: 'tag',
                insertList: JSON.stringify(insertList),
                updateList: JSON.stringify(updateList),
                delIds: delist
            };

            if (!checkdupe()) {
                openAlert('标签名称重复');
            }
            else {
                console.log(etor);

                if (insertList.length + updateList.length + delist.length == 0) {
                    openAlert('无变化！');

                }
                else {
                    $.when(rest.adminAdapter(etor)).done(function (result) {
                        console.log(result);
                        openAlert('已更新');
                        // console.log(result);
                    });
                }
            }
        }
    };

    var checkdupe = function () {
        var checklist = [];
        var chk = true;
        $rows = $('.childTable').find("tr");
        $rows.each(function (j, tr) {
            if (j > 1) {
                var c = $(tr).find("[name='tagName']").val();
                checklist.push(c);
            }
        });
        var flag = [];
        $(checklist).each(function (i, o) {
            if (!flag[o]) {
                flag[o] = true;
            }
            else {
                chk = false;
            }
        });

        return chk;
    };


    $scope.addChild = function () {

        var s = 'table_admin';
        var $table = $("[tag='" + s + "']");
        var $row = $table.find("tr:nth-child(2)").clone();
        $row.removeClass("hide");
        $table.append($row);
        $row.find('select').attr('v', 'e');
        $("#rowCount").val(parseInt($("#rowCount").val()) + 1);
        $('.date-pick').datePicker({ startDate: '1996-01-01' });

    };
});


CooWorkApp.controller('adminrole', function ($rootScope, $scope, $location, $sce, cooConfig, g, rest, ngDialog) {
    var openAlert = function (msg) {
        $scope.message = msg;
        $scope.cDlgId = ngDialog.open({
            template: 'tmpl/alert.html',
            className: 'ngdialog-theme-default-dialog',
            controller: 'dialogController',
            overlay: false,
            scope: $scope
        });
    };


    var etor = {
        key: "roles"
    };

    $scope.result = [];


    $.when(rest.adminList(etor)).done(function (result) {

        console.log(result);

        $(result).each(function (i,o) {
            o.RoleName = o.RoleName.replace(/^\d+:/ig,'');
            $scope.result.push(o);
        });

        $("#rowcount").val(result.length);
        $scope.$apply();
        g.jqueryInit('', 0);
    });

    $scope.adapter = function () {

        var insertList = [];
        var updateList = [];
        var delIds = [];

        var check = true;
        var reqCheck = true;
        $("[tag='edit']").each(function (i) {
            if ($(this).attr("vad") && $(this).attr("vad") != '' && $(this).attr("vad") != 'null' && $(this).val() != '' && !$(this).parent('div').parent('td').parent('tr').hasClass('hide')) {
                var regx = new RegExp(decodeURIComponent($(this).attr("vad")));
                if (!regx.test($.trim($(this).val()))) {
                    $(this).addClass("fieldInvalid");
                    openAlert($(this).parent('div').find('span').text() + " 格式不对");
                    check = false;
                    return false;
                }
            }
        });

        $("[req='true']").each(function () {
            if ($(this).val() == '' && !$(this).parent('div').parent('td').parent('tr').hasClass('hide')) {
                reqCheck = false;
                openAlert("必填项未填!" + $(this).attr('name'));
                //    window.external.MessageBox("必填项未填!");
                return false;
            }
        });



        if (check && reqCheck) {
            var RArray = [];
            $(".childTable").each(function (i, t) {
                $rows = $(t).find("tr");
                $rows.each(function (j, tr) {
                    if (j > 1) {
                        var rowFlag = false;
                        var erow = {
                            RoleId: '00000000-0000-0000-0000-000000000000',
                            RoleName: '',
                            Description: '',
                        };
                        var tid = $.trim($(this).find('[name="RoleId"]').val());
                        if (tid != '') {
                            erow = g.roleFilterByRoleId($scope.result, tid)[0];
                        }
                        $(tr).find("[tag='edit'][v='e']").each(function (i) {
                            rowFlag = true;
                            if (erow.hasOwnProperty($(this).attr('name'))) {
                                var v = $(this).val();
                                if ($(this).is(':checkbox'))
                                    v = $(this).is(":checked");
                                erow[$(this).attr('name')] = v;
                            }
                        });

                        if (rowFlag) {
                            if (tid != '' && parseInt(tid) > 0) {
                                updateList.push(erow);
                            } else {
                                insertList.push(erow);
                            }
                        }

                    }
                });
            });


            var d2 = JSON.stringify(RArray);

            var delv = $('#rowdel').val();
            var delist = [];
            if (delv != undefined && delv != '') {
                delv = delv.toString().substring(1);
                var args = delv.split(',');
                $(args).each(function (i, o) {
                    delist.push(o);
                });
            }

            var etor = {
                key: 'roles',
                insertList: JSON.stringify(insertList),
                updateList: JSON.stringify(updateList),
                dels: delist
            };

            if (!checkdupe()) {
                openAlert('角色名称重复');
            }
            else {
                console.log(etor);

                if (insertList.length + updateList.length + delist.length == 0) {
                    openAlert('无变化！');

                }
                else {
                    $.when(rest.adminAdapterString(etor)).done(function (result) {
                        console.log(result);
                        openAlert('已更新');
                        // console.log(result);
                    });
                }
            }
        }
    };

    var checkdupe = function () {
        var checklist = [];
        var chk = true;
        $rows = $('.childTable').find("tr");
        $rows.each(function (j, tr) {
            if (j > 1) {
                var c = $(tr).find("[name='RoleName']").val();
                checklist.push(c);
            }
        });
        var flag = [];
        $(checklist).each(function (i, o) {
            if (!flag[o]) {
                flag[o] = true;
            }
            else {
                chk = false;
            }
        });

        return chk;
    };


    $scope.addChild = function () {

        var s = 'table_admin';
        var $table = $("[tag='" + s + "']");
        var $row = $table.find("tr:nth-child(2)").clone();
        $row.removeClass("hide");
        $table.append($row);
        $("#rowCount").val(parseInt($("#rowCount").val()) + 1);
        $('.date-pick').datePicker({ startDate: '1996-01-01' });

    };
});




CooWorkApp.controller('adminuser', function ($rootScope, $scope, $location, $sce, cooConfig, g, rest, ngDialog) {
    var openAlert = function (msg) {
        $scope.message = msg;
        $scope.cDlgId = ngDialog.open({
            template: 'tmpl/alert.html',
            className: 'ngdialog-theme-default-dialog',
            controller: 'dialogController',
            overlay: false,
            scope: $scope
        });
    };


    var etor = {
        key: "users"
    };

    var etorRole = {
        key:"roles"
    };

    $scope.result = [];
    $scope.roles = [];
    var sls = [];

    $.when(rest.adminList(etor),rest.adminList(etorRole)).done(function (result,roles) {         

        $(roles).each(function (i, o) {
            o.RoleName = o.RoleName.replace(/^\d+:/ig, ''); 
            $scope.roles.push(o);
        });

        $(result).each(function (i,o) {
            o.UserName = o.UserName.replace(/^\d+:/ig,'');
            o.Password = '***';
            $scope.result.push(o);
        });

        


        $("#rowcount").val(result.length);
        $scope.$apply();
        g.jqueryInit('', 0);

        $('.script').replaceWith('<div class=\"script\"><script > ' +
            '$(document).ready(function () {' +
           '$(\'.role\').each(function (i,element) {' +
             ' var ele =$(this);'+
               '$(this).multiselect({' +
                   'enableCaseInsensitiveFiltering: true,' +
                   'includeSelectAllOption: true,' +
                   ' onChange: function(option, checked) { ele.attr(\'v\',\'e\'); }' +
               '});' +
               'var val = $(this).attr(\'val\');' +
               'if (val!=undefined) {var vv = val.toString().toLowerCase().split(\',\'); ' +
                  '$(this).multiselect(\'select\', vv); }' +
           '}); });  </script></div>');

    });

    $scope.adapter = function () {

        var insertList = [];
        var updateList = [];
        var delIds = [];

        var check = true;
        var reqCheck = true;
        $("[tag='edit']").each(function (i) {
            if ($(this).attr("vad") && $(this).attr("vad") != '' && $(this).attr("vad") != 'null' && $(this).val() != '' && !$(this).parent('div').parent('td').parent('tr').hasClass('hide')) {
                var regx = new RegExp(decodeURIComponent($(this).attr("vad")));
                if (!regx.test($.trim($(this).val()))) {
                    $(this).addClass("fieldInvalid");
                    openAlert($(this).parent('div').find('span').text() + " 格式不对");
                    check = false;
                    return false;
                }
            }
        });

        $("[req='true']").each(function () {
            if ($(this).val() == '' && !$(this).parent('div').parent('td').parent('tr').hasClass('hide')) {
                reqCheck = false;
                openAlert("必填项未填!" + $(this).attr('name'));
                //    window.external.MessageBox("必填项未填!");
                return false;
            }
        });



        if (check && reqCheck) {
            var RArray = [];
            $(".childTable").each(function (i, t) {
                $rows = $(t).find("tr");
                $rows.each(function (j, tr) {
                    if (j > 1) {
                        var rowFlag = false;
                        var erow = {
                            UserId: '00000000-0000-0000-0000-000000000000',
                            UserName: '',
                            xingming: '',
                            Password: '',
                            IsApproved: false,
                            roles: '',
                            roleNames:'',
                            departmentId: null
                        };
                        var tid = $.trim($(this).find('[name="UserId"]').val());    
                        if (tid != '') {
                            erow = g.userFilterByUserId($scope.result, tid)[0];
                        }
                        $(tr).find("[tag='edit'][v='e']").each(function (i) {
                            rowFlag = true;
                            var ename = $(this).attr('name');
                            var val= $.trim($(this).val());
                            switch(ename)
                            {
                                case 'UserId':
                                    erow.UserId = val;
                                    break;
                                case 'UserName':
                                    erow.UserName = val;
                                    break;
                                case 'Password':
                                    erow.Password = val;
                                    break;
                                case 'RoleIds':
                                    var tempV = $(this).val();
                                    if (tempV != undefined && tempV.length > 0) {
                                        var tempStr = tempV.join(',');
                                        erow.roles = tempStr;

                                        var names = g.roleFilterByRoleIds($scope.roles, tempStr);
                                        erow.roleNames = $.map(names, function (obj) {
                                            return obj.RoleName
                                        }).join(',');
                                    }
                                  
                                    break;
                                case 'XingMing':
                                    erow.xingming = val;
                                    break;
                                case 'departmentId':
                                    erow.departmentId = val;
                                    break;
                                case '':
                                    erow.IsApproved = $(this).is(":checked");
                                    break;


                            }
                       
                        });

                        if (rowFlag) {
                            if (tid != '') {
                                updateList.push(erow);
                            } else {
                                insertList.push(erow);
                            }
                        }

                    }
                });
            });


            var d2 = JSON.stringify(RArray);

            var delv = $('#rowdel').val();
            var delist = [];
            if (delv != undefined && delv != '') {
                delv = delv.toString().substring(1);
                var args = delv.split(',');
                $(args).each(function (i, o) {
                    delist.push(o);
                });
            }

            var etor = {
                key: 'users',
                insertList: JSON.stringify(insertList),
                updateList: JSON.stringify(updateList),
                dels: delist
            };

            if (!checkdupe()) {
                openAlert('角色名称重复');
            }
            else {
                console.log(etor);

                if (insertList.length + updateList.length + delist.length == 0) {
                    openAlert('无变化！');

                }
                else {
                    $.when(rest.adminAdapterString(etor)).done(function (result) {
                        console.log(result);
                        openAlert('已更新');
                        // console.log(result);
                    });
                }
            }
        }
    };

    var checkdupe = function () {
        var checklist = [];
        var chk = true;
        $rows = $('.childTable').find("tr");
        $rows.each(function (j, tr) {
            if (j > 1) {
                var c = $(tr).find("[name='UserName']").val();
                checklist.push(c);
            }
        });
        var flag = [];
        $(checklist).each(function (i, o) {
            if (!flag[o]) {
                flag[o] = true;
            }
            else {
                chk = false;
            }
        });

        return chk;
    };


    $scope.addChild = function () {

        var s = 'table_admin';
        var $table = $("[tag='" + s + "']");
        var $row = $table.find("tr:nth-child(2)").clone();
        $row.removeClass("hide");
        $table.append($row);

        $row.find('[multiple="multiple"]').multiselect({
            enableCaseInsensitiveFiltering: true,
            includeSelectAllOption: true
        });
        $row.find('[multiple="multiple"]').attr('v', 'e');

        $("#rowCount").val(parseInt($("#rowCount").val()) + 1);
        $('.date-pick').datePicker({ startDate: '1996-01-01' });

    };
});



CooWorkApp.controller('admintemplate', function ($rootScope, $scope, $location, $sce, $routeParams, cooConfig, g, rest, ngDialog) {
    var openAlert = function (msg) {
        $scope.message = msg;
        $scope.cDlgId = ngDialog.open({
            template: 'tmpl/alert.html',
            className: 'ngdialog-theme-default-dialog',
            controller: 'dialogController',
            overlay: false,
            scope: $scope
        });
    };



    var fs = require("fs");
    var path = require("path");
    $scope.result = [];

    var etor = {
        key: "template"        
    };

   

    var fileFilter = function (f) {
        return $scope.result.filter(function (v) {
            return v.filename.toLowerCase() == f.toLowerCase();
        });
    };


    $.when(rest.adminList(etor)).done(function (result) {

        var p = "custom/" + cooConfig.configObj.companyId + "/";
        fs.readdir(p, function (err, files) {
            if (err) {
                throw err;
            }            

            $scope.result = result;

            $(files).each(function (i, f) {
                var tf = { filename: f, checkSum: '', ContentSize: 0 };
                if (fileFilter(f).length==0)   $scope.result.push(tf);
            });




            $("#rowcount").val($scope.result.length);
            $scope.$apply();
            g.jqueryInit('', 0);       
        });


     
    });

    $scope.adapter = function () {

        var insertList = [];
        var updateList = [];
        var delIds = [];

        var check = true;
        var reqCheck = true;
        $("[tag='edit']").each(function (i) {
            if ($(this).attr("vad") && $(this).attr("vad") != '' && $(this).attr("vad") != 'null' && $(this).val() != '' && !$(this).parent('div').parent('td').parent('tr').hasClass('hide')) {
                var regx = new RegExp(decodeURIComponent($(this).attr("vad")));
                if (!regx.test($.trim($(this).val()))) {
                    $(this).addClass("fieldInvalid");
                    openAlert($(this).parent('div').find('span').text() + " 格式不对");
                    check = false;
                    return false;
                }
            }
        });

        $("[req='true']").each(function () {
            if ($(this).val() == '' && !$(this).parent('div').parent('td').parent('tr').hasClass('hide')) {
                reqCheck = false;
                openAlert("必填项未填!" + $(this).attr('name'));
                //    window.external.MessageBox("必填项未填!");
                return false;
            }
        });



        if (check && reqCheck) {
            var RArray = [];
            $(".childTable").each(function (i, t) {
                $rows = $(t).find("tr");
                $rows.each(function (j, tr) {
                    if (j > 0) {
                        var rowFlag = false;
                        var erow = {
                            ID: 0,
                            filename: '',
                            checkSum: '',
                            ContentSize:''
                        };
                        var tid = $(this).find('[name="ID"]').val();
                        if (tid != '' && parseInt(tid) > 0) {
                            erow = g.filterListById($scope.result, parseInt(tid))[0];
                        }


                        $(tr).find('input:checked').each(function (i) {
                            rowFlag = true;                            
                            erow.ID = tid==''?0:parseInt(tid);
                            erow.filename = $(tr).find('[name="filename"]').html();                       
                        });

                      

                        if (rowFlag) {
                            if (tid != '' && parseInt(tid) > 0) {
                                updateList.push(erow);
                            } else {
                                insertList.push(erow);
                            }
                        }

                    }
                });
            });


            var d2 = JSON.stringify(RArray);

            var delv = $('#rowdel').val();
            var delist = [];
            if (delv != undefined && delv != '') {
                delv = delv.toString().substring(1);
                var args = delv.split(',');
                $(args).each(function (i, o) {
                    delist.push(parseInt(o));
                });
            }

            var etor = {
                key: 'template',
                insertList: JSON.stringify(insertList),
                updateList: JSON.stringify(updateList),
                delIds: delist
            };

            if (!checkdupe()) {
                openAlert('文件名称重复');
            }
            else {
                console.log(etor);

                if (insertList.length + updateList.length + delist.length == 0) {
                    openAlert('无变化！');

                }
                else {
                    $.when(rest.adminAdapter(etor)).done(function (result) {
                        console.log(result);

                        $(insertList).each(function (i,o) {
                            g.updateTemplate(o.ID,o.filename);
                        });
                        $(updateList).each(function (i, o) {
                            g.updateTemplate(o.ID, o.filename);
                        });
                        $('#rowdel').val('');
                        openAlert('已更新');
                        // console.log(result);
                    });
                }
            }
        }
    };

    var checkdupe = function () {
        var checklist = [];
        var chk = true;
        $rows = $('.childTable').find("tr");
        $rows.each(function (j, tr) {
            if (j > 1) {
                var c = $(tr).find("[name='filename']").html();
                checklist.push(c);
            }
        });
        var flag = [];
        $(checklist).each(function (i, o) {
            if (!flag[o]) {
                flag[o] = true;
            }
            else {
                chk = false;
            }
        });

        return chk;
    };


    $scope.addChild = function () {

        var s = 'table_admin';
        var $table = $("[tag='" + s + "']");
        var $row = $table.find("tr:nth-child(2)").clone();
        $row.removeClass("hide");
        $table.append($row);
        $row.find('select').attr('v', 'e');
        $("#rowCount").val(parseInt($("#rowCount").val()) + 1);
        $('.date-pick').datePicker({ startDate: '1996-01-01' });

    };
});




CooWorkApp.controller('adminjoin', function ($rootScope, $scope, $location, $sce, $routeParams, cooConfig, g, rest, ngDialog) {
    var openAlert = function (msg) {
        $scope.message = msg;
        $scope.cDlgId = ngDialog.open({
            template: 'tmpl/alert.html',
            className: 'ngdialog-theme-default-dialog',
            controller: 'dialogController',
            overlay: false,
            scope: $scope
        });
    };


    $scope.result = [];
    $scope.cates = [];
    $scope.patterns = [];
    $scope.patterns2 = [];

    var categoryId = $routeParams.categoryId;
    if (categoryId == undefined) categoryId = 0;
    $scope.categoryId = categoryId;

    var etor = {
        key: "join",
        categoryId: categoryId
    };

    var etorCate = {
        key: "category"
    };

    var etorPattern = {
        key:"pattern"
    };


   


    $.when(rest.adminList(etorCate)).done(function (cates) {

        $scope.cates = cates;
        $scope.category = g.filterListById(cates, categoryId)[0];

        if (categoryId != 0) {
            $.when(rest.adminList(etor)).done(function (result) {            

         

                $(cates).each(function (i, o) {
                    if (o.ID != categoryId) {
                        var subpats = g.filterPatternByCategoryIdPType(cooConfig.allpattern, o.ID, 5);
                        var subpats2 = g.filterPatternByCategoryIdPType(cooConfig.allpattern, o.ID, 16);
                        if (subpats2.length > 0) subpats.push(subpats2[0]);
                      //  console.log(subpats);
                        $scope.patterns.push({ c: o, p: subpats });
                    };
                });

          //      console.log($scope.patterns);
               

               
                $scope.result = result;
                $("#rowcount").val(result.length);
                $scope.$apply();
                g.jqueryInit('', 0);
            });
        }

        $scope.$apply();
    });

    $scope.adapter = function () {

        var insertList = [];
        var updateList = [];
        var delIds = [];

        var check = true;
        var reqCheck = true;
        $("[tag='edit']").each(function (i) {
            if ($(this).attr("vad") && $(this).attr("vad") != '' && $(this).attr("vad") != 'null' && $(this).val() != '' && !$(this).parent('div').parent('td').parent('tr').hasClass('hide')) {
                var regx = new RegExp(decodeURIComponent($(this).attr("vad")));
                if (!regx.test($.trim($(this).val()))) {
                    $(this).addClass("fieldInvalid");
                    openAlert($(this).parent('div').find('span').text() + " 格式不对");
                    check = false;
                    return false;
                }
            }
        });

        $("[req='true']").each(function () {
            if ($(this).val() == '' && !$(this).parent('div').parent('td').parent('tr').hasClass('hide')) {
                reqCheck = false;
                openAlert("必填项未填!" + $(this).attr('name'));
                //    window.external.MessageBox("必填项未填!");
                return false;
            }
        });



        if (check && reqCheck) {
            var RArray = [];
            $(".childTable").each(function (i, t) {
                $rows = $(t).find("tr");
                $rows.each(function (j, tr) {
                    if (j > 1) {
                        var rowFlag = false;
                        var erow = {
                            ID: 0,
                            categoryId:categoryId,
                            nRelation: 0,
                            joinCategoryId: 0,
                            joinPatternId:0                          
                        };
                        var tid = $(this).find('[name="ID"]').val();
                        if (tid != '' && parseInt(tid) > 0) {
                            erow = g.filterListById($scope.result, parseInt(tid))[0];
                        }
                        $(tr).find("[tag='edit'][v='e']").each(function (i) {
                            rowFlag = true;
                            if (erow.hasOwnProperty($(this).attr('name'))) {
                                var v = $(this).val();
                                if ($(this).is(':checkbox'))
                                    v = $(this).is(":checked");
                                erow[$(this).attr('name')] = v;
                            }
                        });

                        if (rowFlag) {
                            if (tid != '' && parseInt(tid) > 0) {
                                updateList.push(erow);
                            } else {
                                insertList.push(erow);
                            }
                        }

                    }
                });
            });


            var d2 = JSON.stringify(RArray);

            var delv = $('#rowdel').val();
            var delist = [];
            if (delv != undefined && delv != '') {
                delv = delv.toString().substring(1);
                var args = delv.split(',');
                $(args).each(function (i, o) {
                    delist.push(parseInt(o));
                });
            }

            var etor = {
                key: 'join',
                insertList: JSON.stringify(insertList),
                updateList: JSON.stringify(updateList),
                delIds: delist
            };

            if (!checkdupe()) {
                openAlert('关联有重复');
            }
            else {
                console.log(etor);

                if (insertList.length + updateList.length + delist.length == 0) {
                    openAlert('无变化！');

                }
                else {
                    $.when(rest.adminAdapter(etor)).done(function (result) {
                        console.log(result);
                        openAlert('已更新');
                        // console.log(result);
                    });
                }
            }
        }
    };

    var checkdupe = function () {
        var checklist = [];
        var chk = true;
        $rows = $('.childTable').find("tr");
        $rows.each(function (j, tr) {
            if (j > 1) {
                var c1 = $(tr).find("[name='categoryId']").val();
                var c2 = $(tr).find("[name='joinCategoryId']").val();
                checklist.push(JSON.stringify({ c1: c1, c2: c2 }));
            }
        });
        var flag = [];
        $(checklist).each(function (i, o) {
            if (!flag[o]) {
                flag[o] = true;
            }
            else {
                chk = false;
            }
        });

        return chk;
    };


    $scope.addChild = function () {

        var s = 'table_admin';
        var $table = $("[tag='" + s + "']");
        var $row = $table.find("tr:nth-child(2)").clone();
        $row.removeClass("hide");
        $table.append($row);
        $row.find('select').attr('v', 'e');
        $("#rowCount").val(parseInt($("#rowCount").val()) + 1);
        $('.date-pick').datePicker({ startDate: '1996-01-01' });

    };
});




CooWorkApp.controller('adminworkflow', function ($rootScope, $scope, $location, $sce, $routeParams, cooConfig, g,_, rest, ngDialog) {
    var openAlert = function (msg) {
        $scope.message = msg;
        $scope.cDlgId = ngDialog.open({
            template: 'tmpl/alert.html',
            className: 'ngdialog-theme-default-dialog',
            controller: 'dialogController',
            overlay: false,
            scope: $scope
        });
    };


    $scope.result = [];
    $scope.cates = [];
    $scope.roles = [];
    $scope.status = [];

    var categoryId = $routeParams.categoryId;
    if (categoryId == undefined) categoryId = 0;
    $scope.categoryId = categoryId;

    var etor = {
        key: "workFlow"
    };
    //,    categoryId: categoryId
    var etorCate = {
        key: "category"
    };

    var etorStatus = {
        key: "rawStatus",
        categoryId:categoryId
        
    };

    var etorPattern = {
        key: "pattern",
        categoryId: categoryId
    };

    var etorRoles =
        {
            key: "roles"
        };


    $.when(rest.adminList(etorCate)).done(function (cates) {

        $scope.cates = cates;
        $scope.category = g.filterListById(cates, categoryId)[0];

        if (categoryId != 0) {
            $.when(rest.adminList(etor),rest.adminList(etorPattern),rest.adminList(etorStatus),rest.adminList(etorRoles)).done(function (result,patterns,status,roles) {

                
                var p13 = _.filter(patterns, function (n) { return n.pTypeId == 13; });
                if (p13.length > 0)
                {
                    $scope.status = _.filter(status, function (s) { return s.categoryId == categoryId && s.patternId==p13[0].ID });
                }
                $(roles).each(function (i, o) {
                    o.RoleName = o.RoleName.replace(/^\d+:/ig, '');
                    $scope.roles.push(o);
                });



                //$(cates).each(function (i, o) {
                //    if (o.ID != categoryId) {
                //        var subpats = g.filterPatternByCategoryIdPType(cooConfig.allpattern, o.ID, 5);
                //        var subpats2 = g.filterPatternByCategoryIdPType(cooConfig.allpattern, o.ID, 16);
                //        if (subpats2.length > 0) subpats.push(subpats2[0]);
                //        //  console.log(subpats);
                //        $scope.patterns.push({ c: o, p: subpats });
                //    };
                //});

             
                $scope.result = _.filter(result, function (r) { return r.categoryId == categoryId });        
                $("#rowcount").val(result.length);
                $scope.$apply();
                g.jqueryInit('', 0);
            });
        }

        $scope.$apply();
    });

    $scope.adapter = function () {

        var insertList = [];
        var updateList = [];
        var delIds = [];

        var check = true;
        var reqCheck = true;
        $("[tag='edit']").each(function (i) {
            if ($(this).attr("vad") && $(this).attr("vad") != '' && $(this).attr("vad") != 'null' && $(this).val() != '' && !$(this).parent('div').parent('td').parent('tr').hasClass('hide')) {
                var regx = new RegExp(decodeURIComponent($(this).attr("vad")));
                if (!regx.test($.trim($(this).val()))) {
                    $(this).addClass("fieldInvalid");
                    openAlert($(this).parent('div').find('span').text() + " 格式不对");
                    check = false;
                    return false;
                }
            }
        });

        $("[req='true']").each(function () {
            if ($(this).val() == '' && !$(this).parent('div').parent('td').parent('tr').hasClass('hide')) {
                reqCheck = false;
                openAlert("必填项未填!" + $(this).attr('name'));
                //    window.external.MessageBox("必填项未填!");
                return false;
            }
        });



        if (check && reqCheck) {
            var RArray = [];
            $(".childTable").each(function (i, t) {
                $rows = $(t).find("tr");
                $rows.each(function (j, tr) {
                    if (j > 1) {
                        var rowFlag = false;
                        var erow = {
                            ID: 0,
                            categoryId: categoryId,
                            tagId1: 0,
                            tagId2: 0,
                            roleId: '00000000-0000-0000-0000-000000000000'
                        };
                        var tid = $(this).find('[name="ID"]').val();
                        if (tid != '' && parseInt(tid) > 0) {
                            erow = g.filterListById($scope.result, parseInt(tid))[0];
                        }
                        $(tr).find("[tag='edit'][v='e']").each(function (i) {
                            rowFlag = true;
                            if (erow.hasOwnProperty($(this).attr('name'))) {
                                var v = $(this).val();
                                if ($(this).is(':checkbox'))
                                    v = $(this).is(":checked");
                                erow[$(this).attr('name')] = v;
                            }
                        });

                        if (rowFlag) {
                            if (tid != '' && parseInt(tid) > 0) {
                                updateList.push(erow);
                            } else {
                                insertList.push(erow);
                            }
                        }

                    }
                });
            });


            var d2 = JSON.stringify(RArray);

            var delv = $('#rowdel').val();
            var delist = [];
            if (delv != undefined && delv != '') {
                delv = delv.toString().substring(1);
                var args = delv.split(',');
                $(args).each(function (i, o) {
                    delist.push(parseInt(o));
                });
            }

            var etor = {
                key: 'workFlow',
                insertList: JSON.stringify(insertList),
                updateList: JSON.stringify(updateList),
                delIds: delist
            };

            if (!checkdupe()) {
                openAlert('关联有重复');
            }
            else {
                console.log(etor);

                if (insertList.length + updateList.length + delist.length == 0) {
                    openAlert('无变化！');

                }
                else {
                    $.when(rest.adminAdapter(etor)).done(function (result) {
                        console.log(result);
                        openAlert('已更新');
                        // console.log(result);
                    });
                }
            }
        }
    };

    var checkdupe = function () {
        var checklist = [];
        var chk = true;
        $rows = $('.childTable').find("tr");
        $rows.each(function (j, tr) {
            if (j > 1) {
                var c1 = $(tr).find("[name='tagId1']").val();
                var c2 = $(tr).find("[name='tagId2']").val();
                var c3 = $(tr).find("[name='roleId']").val();
                checklist.push(JSON.stringify({ c1: c1, c2: c2 ,c3:c3}));
            }
        });
        var flag = [];
        $(checklist).each(function (i, o) {
            if (!flag[o]) {
                flag[o] = true;
            }
            else {
                chk = false;
            }
        });

        return chk;
    };


    $scope.addChild = function () {

        var s = 'table_admin';
        var $table = $("[tag='" + s + "']");
        var $row = $table.find("tr:nth-child(2)").clone();
        $row.removeClass("hide");
        $table.append($row);
        $row.find('select').attr('v', 'e');
        $("#rowCount").val(parseInt($("#rowCount").val()) + 1);
        $('.date-pick').datePicker({ startDate: '1996-01-01' });

    };
});
