CooWorkApp.controller('reportController', function ($rootScope,$scope, $location, $routeParams, $sce, locdbServices, userSetting,cooConfig, g, rest) {


    var querys = require('querystring');

    var reportPageId = $routeParams.pageId;

    var currentPage = g.pageFilterById(reportPageId)[0];
    $rootScope.title = currentPage.UIname + ' - 报表分析';


   var categoryId = $routeParams.categoryId;
   var p17 = g.pageFilter(17, reportPageId);
   var p18 = g.pageFilter(18, reportPageId);
   var lsc = [];
   $scope.rElements = [];
   $scope.vElements = [];
   $scope.vData = [];
   $scope.pageId = p18[0].ID;



   $scope.searchConfigElements = [];
   var osElements = g.patternFilterByPage(p17[0].ID);


   var twoD = function (queryString, result) {

       var qobj = querys.parse(queryString);
       var icount = qobj._sys_thtitle.match(/th>/ig).length;
       var caculateCount = (qobj._sys_calculate == undefined || qobj._sys_calculate == "") ? 0 : qobj._sys_calculate.split(',').length;
       var groupCount = (qobj._sys_group == "" || qobj._sys_group == undefined) ? 0 : qobj._sys_group.split(',').length;
       var data = [];

       if (groupCount == 0) return;
    //   console.log(icount);
       if (icount == 4) {
           $(result).each(function (i, item) {

               var edata = [item.v1, item.v0];
               data.push(edata);
           });
       }

       if (icount == 6 && caculateCount == 1) {

           $(result).each(function (i, item) {

               var edata = [item.v2, item.v1];
               data.push(edata);
           });
       }

       var plot1 = jQuery.jqplot('chart2', [data],
         {
             seriesDefaults: {
                 // Make this a pie chart.
                 renderer: jQuery.jqplot.PieRenderer,
                 rendererOptions: {
                     // Put data labels on the pie slices.
                     // By default, labels show the percentage of the slice.
                     showDataLabels: true
                 }
             },
             legend: { show: true, location: 'e' }
         }
       );

   };


   var threeD = function (queryString, result) {


       var rfilter = function (list, v1, v2) {
           return list.filter(function (v) {
               return v.v1 == v1 && v.v2 == v2;
           });

       };

       var rfilter23 = function (list, v2, v3) {
           return list.filter(function (v) {
               return v.v2 == v2 && v.v3 == v3;
           });
       }



       var qobj = querys.parse(queryString);
       var icount = qobj._sys_thtitle.match(/th>/ig).length;
       var caculateCount = (qobj._sys_calculate == undefined || qobj._sys_calculate == "") ? 0 : qobj._sys_calculate.split(',').length;
       var groupCount = (qobj._sys_group == "" || qobj._sys_group == undefined) ? 0 : qobj._sys_group.split(',').length;


       var ticks = [];
       var s3data = [];
       var slabel = [];

       // console.log(icount + caculateCount);

       if (icount == 6 && caculateCount == 0) {

           var flags = [], flagsv1 = [], output = [], l = result.length, i;

           for (i = 0; i < l; i++) {

               if (!flagsv1[result[i].v1]) {
                   ticks.push(result[i].v1);
                   flagsv1[result[i].v1] = true;
               }
               if (!flags[result[i].v2]) {
                   flags[result[i].v2] = true;
                   output.push(result[i].v2);
               }
           }

           ticks.sort(function (a, b) {
               if (a < b) return -1;
               if (a > b) return 1;
               return 0;
           });


           $(output).each(function (i, a) {

               var subData = [];
               $(ticks).each(function (j, b) {

                   var rec = rfilter(result, b, a);
                   if (rec.length > 0) {
                       subData.push(rec[0].v0);
                   }
                   else {
                       subData.push(0);
                   }
               });
               s3data.push(subData);
           });

           $(output).each(function (i, item) {

               var o = { label: item };
               slabel.push(o);
           });

       }
       else if (icount == 8 && caculateCount == 1) {
           var flags = [], flagsv1 = [], output = [], l = result.length, i;

           for (i = 0; i < l; i++) {

               if (!flagsv1[result[i].v2]) {
                   ticks.push(result[i].v2);
                   flagsv1[result[i].v2] = true;
               }
               if (!flags[result[i].v3]) {
                   flags[result[i].v3] = true;
                   output.push(result[i].v3);
               }
           }

           ticks.sort(function (a, b) {
               if (a < b) return -1;
               if (a > b) return 1;
               return 0;
           });



           $(output).each(function (i, a) {

               var subData = [];
               $(ticks).each(function (j, b) {

                   var rec = rfilter23(result, b, a);
                   if (rec.length > 0) {
                       subData.push(rec[0].v1);
                   }
                   else {
                       subData.push(0);
                   }
               });
               s3data.push(subData);
           });


           $(output).each(function (i, item) {

               var o = { label: item };
               slabel.push(o);
           });

       }

       var plot1 = $.jqplot('chart1', s3data, {
           // The "seriesDefaults" option is an options object that will
           // be applied to all series in the chart.
           seriesDefaults: {
               renderer: $.jqplot.BarRenderer,
               rendererOptions: { fillToZero: true },
               pointLabels: { show: true, location: 'e', edgeTolerance: -15 },
           },
           // Custom labels for the series are specified with the "label"
           // option on the series option.  Here a series option object
           // is specified for each series.
           series: slabel,
           // Show the legend and put it outside the grid, but inside the
           // plot container, shrinking the grid to accomodate the legend.
           // A value of "outside" would not shrink the grid and allow
           // the legend to overflow the container.
           legend: {
               show: true,
               placement: 'outsideGrid'
           },
           axes: {
               // Use a category axis on the x axis and use our custom ticks.
               xaxis: {
                   renderer: $.jqplot.CategoryAxisRenderer,
                   ticks: ticks
               },
               // Pad the y axis just a little so bars can get close to, but
               // not touch, the grid boundaries.  1.2 is the default padding.
               yaxis: {
                   pad: 1.05,
                   tickOptions: { formatString: '$%d' }
               }
           }
       });
   };
    //jqplot








    $.when(userSetting.getSettingElementByPage(p17[0].ID)).done(function (a) {

        $scope.rElements = a;
        $.each($scope.rElements, function (index, item) {
            if (item.validator != undefined)
                item.validator = encodeURIComponent(item.validator);
        });      


        //config
        var eleStr = ',';
        $($scope.rElements).each(function (i, item) {
            eleStr += item.ID + ',';
        }); 

 

        $(osElements).each(function (j, obj) {
            if (eleStr.indexOf(',' + obj.ID.toString() + ',') > -1) {
                $scope.searchConfigElements.push({ item: obj, select: true });
            }
            else {
                $scope.searchConfigElements.push({ item: obj, select: false });
            }
        });
        //config;



        $scope.$$phase || $scope.$apply();


        $scope.searchClear = function () {
            window.location.href = window.location.href + '/';

        };



        $scope.dosearch = function () {
            $scope.vData = [];
            lsc = [];
            $("[tag='edit']").each(function (i, tb) {
                var val = $.trim($(this).val());
                if ($(this).is(':checkbox'))
                    val = $(this).is(":checked");


                if (val) {
                    var sc = {
                        _Key: $(this).attr("id"),
                        _Value: val
                    };
                    lsc.push(sc);
                }
            });

            var etor =
                {
                    companyId:cooConfig.configObj.companyId,
                    cateId: categoryId,
                    pageId: reportPageId,
                    lscStr: JSON.stringify(lsc)
                };
 
            console.log(lsc);


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

                var rdate = /\d+-\d+(T|\s)\d+/i;
                $(result.data).each(function (i, o) {
                    if (rdate.test(o.v0)) o.v0 = g.dateFormat(o.v0);
                    if (rdate.test(o.v1)) o.v1 = g.dateFormat(o.v1);
                    if (rdate.test(o.v2)) o.v2 = g.dateFormat(o.v2);
                    if (rdate.test(o.v3)) o.v3 = g.dateFormat(o.v3);
                    if (rdate.test(o.v4)) o.v4 = g.dateFormat(o.v4);
                
                });


                $scope.vData = result.data;


                var qs = result.queryString.toString();
                var paging = qs;
                qs = qs.replace(/.+=/ig, '');
                qs = qs.replace(/<\/th><th>/ig, ',').replace(/<\/?th>/ig,'');                
          //      $scope.vElements = [];
                $scope.vElements = qs.split(',');
      
                var len=$scope.vElements.length;


                for (var k = 0; k < 5 - len ; k++)
                {
                    $scope.vElements.push('['+k+']');
                }

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


                $("#chart1").html("");
                $("#chart1").attr('style', '');
                $("#chart2").html("");
                $("#chart2").attr('style', '');

                var qobj = querys.parse(paging);
                if (qobj._sys_thtitle == undefined) return;
                var icount = qobj._sys_thtitle.match(/th>/ig).length;
                var caculateCount = (qobj._sys_calculate == undefined || qobj._sys_calculate == "") ? 0 : qobj._sys_calculate.split(',').length;




                if (icount == 4 || (icount == 6 && caculateCount == 1)) {

                    console.log("2d");

                    twoD(paging, result.data);
                }
                else if (icount == 8 || (icount == 6 && caculateCount == 0)) {

                    threeD(paging, result.data);
                }
                else {
                    $("#chart1").hide();
                    $("#chart2").hide();
                }

                $scope.$apply();
            });

        };



        $scope.searchConfig = function () {
            if (!$("#searchConfig").is(":visible")) {
                $("#searchConfig").show();
            } else {
                $("#searchConfig").hide();

                $.when(userSetting.pageConfig($scope.rElements, 'os', p17[0].ID)).done(function (f) {
                    if (f) {

                        $.when(locdbServices.fetchAllUserElements()).done(function (result) {
                            cooConfig.alluserelement = result;
                            console.log('redirect');
                            $location.path('/report/' + categoryId + '/page/' + reportPageId + '/');
                            $scope.$apply();
                        });
                    }
                });
            }
        };

    });
});



CooWorkApp.controller('complexcreateController', function ($scope, $location, $routeParams, $sce, locdbServices, userSetting, 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
        });
    };





    window.ondragover = function (e) { e.preventDefault(); return false };
    window.ondrop = function (e) { e.preventDefault(); return false };

    var categoryId = $routeParams.categoryId;
    $scope.categoryId = categoryId;
    var subCategoryId = 0;
    var subJoinCategoryId = 0;
    var p19;
    var pageId = $routeParams.pageId;
    var pattern = g.patternFilterByIndexId(categoryId);
    var intersect_result = []; //subcategory ,joincategory has same ename , copy value

    $scope.subCategoryId = 0;
    $scope.elements = [];
    $scope.subElements = [];
    $scope.options = [];
    $scope.indexId = 0;
    $scope.searchElements = [];
    $scope.subPageId = 0;
    var source = [];
    var prefix = '.createTable ';

    $scope.createConfigElements = [];
    var ocElements = g.patternFilterByPage(pageId);


    $.when(userSetting.getSettingElementByPage(pageId)).done(function (a) {

        p19 = g.pageFilter(19, pageId);
        $scope.subPageId = p19[0].ID;
        $scope.subElements = g.patternFilterByPage(p19[0].ID);
        //config
        var eleStr = ',';
        $(a).each(function (i, item) {
            eleStr += item.ID + ',';
        });

        $(ocElements).each(function (i, o) {
            if (eleStr.indexOf(',' + o.ID.toString() + ',') > -1) {
                $scope.createConfigElements.push({ item: o, select: true });
            }
            else {
                $scope.createConfigElements.push({ item: o, select: false });
            }
        });
        //config



        //result.data ,.join,.related
        $(a).each(function (i, o) {

         

            source = g.makeSource(o);
            $scope.elements.push({ p: o, s: source });
        });
        g.jqueryInit(prefix, $scope.indexId);




        $scope.createConfig = function () {
            if (!$("#createConfig").is(":visible")) {
                $("#createConfig").show();
            } else {
                $("#createConfig").hide();

                $.when(userSetting.pageConfig(a, 'oc', pageId)).done(function (f) {
                    if (f) {

                        $.when(locdbServices.fetchAllUserElements()).done(function (result) {
                            cooConfig.alluserelement = result;
                            console.log('redirect');
                            $location.path('/create/' + categoryId + '/page/' + pageId + '/');
                            $scope.$apply();
                        });
                    }
                });
            }
        };

    });


    $scope.addChild = function () {
 
            var s = 'table_' + p19[0].ID;
            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' });

    };


    var addChild = function () {
        var s = 'table_' + p19[0].ID;
        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' });
    };


    var setSubCategoryId = function () {
        var flags = [], output = [], l = $scope.subElements.length, i;

        for (i = 0; i < l; i++) {
            if (!flags[$scope.subElements[i].categoryId]) {
                output.push($scope.subElements[i].categoryId);
                flags[$scope.subElements[i].categoryId] = true;
            }
        };



        if (output.length == 1) {
            var vj = g.joinFilterByAB(categoryId, output[0]);

            if (vj.length > 0 && vj[0].nRelation == 2) {

                console.log("nR todo");
                subCategoryId = output[0];
                subJoinCategoryId = output[0];
            }
        }
        else {
            var subFlag = false;

            $(output).each(function (i, o) {
                var vj2 = g.joinFilterByAB(categoryId, o);

                if (vj2.length > 0 && vj2[0].nRelation == 2) {
                    subFlag = true;
                    subCategoryId = o;

                }
                if (vj2.length == 0) {
                    subJoinCategoryId = o;
                }
            });
        };

        $scope.subCategoryId = subCategoryId;
    };

    setSubCategoryId();
    //join setting

    var intersect = function () {

        var pmain = g.patternFilterByPage(p19[0].ID);
        var joinPatterns = g.patternFilterByCategory(subJoinCategoryId);

        //intersect
        pmain.sort(function (a, b) {
            if (a.eName < b.eName) return -1;
            if (a.eName > b.eName) return 1;
            return 0;
        });

        joinPatterns.sort(function (a, b) {
            if (a.eName < b.eName) return -1;
            if (a.eName > b.eName) return 1;
            return 0;
        });

        var ai = 0, bi = 0; 

        while (ai < pmain.length && bi < joinPatterns.length) {
            if (pmain[ai].eName < joinPatterns[bi].eName) { ai++; }
            else if (pmain[ai].eName > joinPatterns[bi].eName) { bi++; }
            else /* they're equal */
            {
                var mappingPattern =
                    {
                        m: pmain[ai].ID,
                        s: joinPatterns[bi].ID
                    };
                if (pmain[ai].ID != joinPatterns[bi].ID && pmain[ai].pTypeId != 16) {
                    intersect_result.push(mappingPattern);
                }
                ai++;
                bi++;
            }
        }   
    };

    intersect();
    //intersect



    $scope.openSearch = function () {       
        var listp = g.pageFilterByCategoryType(subJoinCategoryId , 10);
        if (listp.length > 0) {           
            var p11 = g.pageFilter(11, listp[0].ID);
            if (p11.length > 0) {
                $scope.searchElements = g.userPatternFilterByPage(p11[0].ID);
                if ($scope.searchElements.length == 0) $scope.searchElements = g.patternFilterByPage(p11[0].ID);
               // console.log($scope.searchElements);
            }
        }
    };


    $scope.openSelect = function (element) {


        $scope.element = element;

        ngDialog.open({
            template: 'tmpl/select.html',
            controller: 'selectController',       
            scope: $scope
        });
    };   


    $scope.rowSelect = function (index,name) {

        $('#view__j' + $scope.element.ID).val(name);
        $('#__j' + $scope.element.ID).val(index);
        $('#__j' + $scope.element.ID).attr('v', 'e');
        ngDialog.closeAll();
    };





    $scope.searchSubmit = function () {

        console.log(subJoinCategoryId);

        var listp = g.pageFilterByCategoryType(subJoinCategoryId, 10);
        if (listp.length > 0) {
            var p11 = g.pageFilter(11, listp[0].ID);
            if (p11.length > 0) {
                $scope.searchElements = g.userPatternFilterByPage(p11[0].ID);
                if ($scope.searchElements.length == 0) $scope.searchElements = g.patternFilterByPage(p11[0].ID);               
                var lsc = g.getSearchCondition('#search ',$scope.searchElements);    
                $("[tag ='table_" + p19[0].ID + "'] tr:nth-child(n+3)").remove();
        
                $.when(rest.search(subJoinCategoryId, listp[0].ID, lsc, 0, 300)).done(function (result) {              
                    var ppp = g.joinFilterByAB(subCategoryId, subJoinCategoryId);
                    var joinPatternIndex = g.patternFilterByIndexId(subJoinCategoryId)[0].ID;
                    var joinPatternId = ppp[0].joinPatternId;                     
                    $(result.data).each(function (i, item) {

                        addChild('table_' + p19[0].ID);
                        var j = 3 + i;
                        $("[tag ='table_" + p19[0].ID + "'] tr:nth-child(" + j + ") input[name='view__j" + joinPatternId + "']").val(item["__c" + joinPatternId]);
                        $("[tag ='table_" + p19[0].ID + "'] tr:nth-child(" + j + ") input[name='__j" + joinPatternId + "']").val(item['__c' + joinPatternIndex]);

                        $(intersect_result).each(function (i, r) {
                            $("[tag ='table_" + p19[0].ID + "'] tr:nth-child(" + j + ") input[name='__c" + r.m + "']").val(item['__c' + r.s]);
                        });

                    });
                });
            }
        }
    };





    $scope.dosm = function () {
        $('#saomadiv').show();
    };

    $scope.saomacancel = function () {
        $('#saomadiv').hide();
    };

    $scope.saomasubmit = function () {
        var val = $("#idlist").val();
        var r = /[0-9]+/g;
        var matches = [], found;
        while (found = r.exec(val)) {
            matches.push(found[0]);
        }

        var tt = matches.toString();
        if (tt == "") tt = "0";

        var indexPattern = g.patternFilterByIndexId(subJoinCategoryId);
        $('#__c' + indexPattern[0].ID).val(tt);
        $('#__c' + indexPattern[0].ID + '_o').val(5);  
        $("#saomadiv").hide();
    };
    



    $scope.doSubmit = function () {

        var check = true;
        var reqCheck = true;
        var uniCheck = true;
        $(".complexcreate [tag='edit']").each(function (i) {

            if ($(this).attr("vad") && $(this).attr("vad") != '' && $(this).attr("vad") != 'null' && $(this).val() != '') {
                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;
                }
            }
        });


        $(".complexcreate [req='true']").each(function () {
            if ($(this).val() == '') {
                reqCheck = false;
                openAlert("必填项未填!" + $(this).parent('div').find('span').text());
                //    window.external.MessageBox("必填项未填!");
                return false;
            }
        });




        $(".complexcreate [unq='true']").each(function (i) {

            if ($(this).val() != '') {
                var cid = $scope.indexId;

                var etor = {
                    val: $(this).val(),
                    name: $(this).attr('id'),
                    itemId: cid
                };

                $.when(rest.uniqueCheck(etor)).done(function (data) {
                    if (data != '') {
                        $('.complexcreate #' + etor.name).addClass("fieldInvalid");
                        openAlert("已存在," + data);
                        uniCheck = false;
                        return false;
                    }
                });
            }
        });




        if (check && reqCheck && uniCheck) {
            var RetArray = [];
            $(".complexcreate [v='e']").each(function (i) {

                var tempV = $.trim($(this).val());
                if ($(this).is("div"))
                    tempV = $.trim($(this).html());

                if ($(this).is(':checkbox'))
                    tempV = $(this).is(":checked");

                var o = { _Key: $(this).attr('id'), _Value: tempV };
                RetArray.push(o);
            });

            $(".complexcreate .jqtxt").each(function (i) {
                var tempj = $.trim($(this).val());

                var o = { _Key: $(this).attr('id'), _Value: tempj };

                RetArray.push(o);

            });

            $(".complexcreate [multiple='multiple']").each(function (i) {
                var tempV = $("#" + $(this).attr("id")).val();

                if (tempV != undefined && tempV.length > 0) {
                    var tempStr = tempV.join(',');
                    var o = { _Key: $(this).attr('id'), _Value: tempStr };
                    RetArray.push(o);
                }
            });



            var RArray = [];
            $(".childTable").each(function (i, t) {
                    $rows = $(t).find("tr");
                    $rows.each(function (j, tr) {
                        if (j > 1) {
                            var erow = [];
                            $(tr).find("input[tag='edit']").each(function (i) {
                                var o = { _Key: $(this).attr('name'), _Value: $.trim($(this).val()) };
                                erow.push(o);
                            });
                            if (erow.length > 0) {
                                var ccc = g.getCategoryById(subCategoryId);
                                RArray.push({
                                    key: ccc[0].eName,
                                    value: erow
                                });
                            }
                        }
                    });                
            });

            var d1 = JSON.stringify(RetArray);
            var d2 = JSON.stringify(RArray);


            var iid = $scope.indexId;

            var etor = {
                jsonStr: d1,
                relatedSTR: d2,
                pageId: pageId,
                itemId: iid
            };


            console.log(etor);

            $.when(rest.create(etor)).done(function (data) {

                ngDialog.open({
                    template: '<p style="width:100px;">ok</p>',
                    plain: true
                });
                $location.path('/complexcreate/'+categoryId+'/page/'+pageId+'/');
                $scope.$apply();
            });

        }
    };

});


 

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

    var fs = require('fs');

    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.startup = false;

    $rootScope.title = '绩效管理 北极光v1.03 - 首页';
   

    if (fs.existsSync('startup.txt')) {
        $scope.startup = true;
    };



    console.log(cooConfig.configObj.isLogin);
   
    if (cooConfig.configObj.isLogin) {    
        window.location.href = location.protocol + '//' + location.host + location.pathname + '#/center';          
    }

 


    $scope.showDiv = function () {
        
        $scope.startup = !$scope.startup;
        $scope.$apply();

    };


    $scope.submit2 = function () {

        var etor =
           {
               companyname: $.trim($("#companyName2").val()),
               username: $.trim($("#UserName2").val()),
               Password: $.trim($("#Password2").val()),
               email: $.trim($("#email").val()),
           };

     

        $.ajax({            
            url: cooConfig.configObj.url + 'account/create',
            type: "post",
            data: JSON.stringify(etor),
            dataType: "json",
            contentType: "application/json;charset=utf-8",
            success: function (data) {

                console.log(data);
                if (data.indexOf('成功')>0) {
                    $("#companyName").val(etor.companyname); 
                    $("#UserName").val(etor.username);
                    $("#Password").val(etor.Password);
                    $scope.submit();

                }           
            },
            error: function (jqXHR, exception) {
                openAlert(exception);
            }

        });
    };




    $scope.submit = function () {

   

        var pas = $.trim($("#Password").val());

        var result = "";
        for (var i = 0; i < pas.length; ++i) {
            result += String.fromCharCode(108 ^ pas.charCodeAt(i));
        }

        var etor =
        {
            companyName: $.trim($("#companyName").val()),
            UserName: $.trim($("#UserName").val()),
            Password: result
        };

        //console.log(etor);

        
       




        $.ajax({
            // url: 'http://localhost:1379/account/nodelogin',
            url: cooConfig.configObj.url + 'account/nodelogin',
            type: "post",
            data: JSON.stringify(etor),
            dataType: "json",
            contentType: "application/json;charset=utf-8",
            success: function (data) {

               

              //  console.log(data);

                if (data.companyId > 0) {

                    cooConfig.configObj.companyId = data.companyId;
                    cooConfig.configObj.key = data.key;
                    cooConfig.configObj.uploadKey = data.uploadKey;
                    cooConfig.configObj.isAdmin = data.isAdmin;
                    cooConfig.configObj.isLogin = true;
                    cooConfig.configObj.xingMing = data.XingMing;



                    var index = fs.readFileSync('index.html').toString();
                    if (index.indexOf('custom/' + cooConfig.configObj.companyId + '/customcontrollers.js') == -1)
                    {
                        var dir = 'custom/' + cooConfig.configObj.companyId;
                        if (!fs.existsSync(dir)) {
                            fs.mkdirSync(dir);
                        }
                        if (!fs.existsSync('custom/' + cooConfig.configObj.companyId + '/customcontrollers.js'))
                        {
                            fs.writeFile('custom/' + cooConfig.configObj.companyId + '/customcontrollers.js', "//custom controllers", function (err) {
                                if (err) {
                                    console.log(err);
                                }  
                            });
                        }
                        index = index.replace('<!--custom-->', '<!--custom--><script src="custom/' + cooConfig.configObj.companyId + '/customcontrollers.js" type="text/javascript" ></script>');
                        fs.writeFileSync('index.html', index);
                    }


                 

                    if ($('#autoLogin').is(':checked')) {

                        var config = fs.readFileSync('js/service/cooConfig.js').toString();
                        config = config.replace(/companyId:[^,]+/ig, 'companyId:' + data.companyId);
                        config = config.replace(/xingMing:[^,]+/ig, 'xingMing:"' + data.XingMing+'"');
                        config = config.replace(/key:[^,]+/ig, 'key:"' + data.key +'"');
                        config = config.replace(/uploadKey:[^,]+/ig, 'uploadKey:"' + data.uploadKey + '"');
                        config = config.replace(/isAdmin:[^,]+/ig, 'isAdmin:' + data.isAdmin);
                        config = config.replace(/fileServer:[^,]+/ig, 'fileServer:"' + data.fileServer+'"');
                        config = config.replace(/isAutoLogin:[a-z]+/ig, 'isAutoLogin:true');

                        fs.writeFileSync('js/service/cooConfig.js', config);
                    };



                    if (fs.existsSync('startup.txt')) {
                        $("#ajax").html("<img src='css/ajax1.gif' />");

                        var setupUrl = fs.readFileSync('startup.txt').toString();
                        $.when(rest.setup(setupUrl)).done(function (data) {
                            console.log(data);
                            $("#ajax").html("");
                            fs.rename('startup.txt', 'startup_bak.txt', function (err) {
                                if (err) console.log('ERROR: ' + err);
                            });
                            window.location.href = location.protocol + '//' + location.host + location.pathname + '#/center';
                            $scope.$apply();

                        });
                        //todo  first login
                    }
                    else
                    {
                        window.location.href = location.protocol + '//' + location.host + location.pathname + '#/center';
                        $scope.$apply();

                    }





            
                }
                else
                {
                    openAlert('用户名或密码不正确!');
                }
      

            },
            error: function (jqXHR, exception) {
                openAlert(exception);
            }

        });

    };











});