CooWorkApp.controller('editController', 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
        });
    };



    var fs = require('fs');

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

    var categoryId = $scope.categoryId;
    $scope.categoryId = categoryId;
    var pageId = $scope.editPageId;
    var currentPage = g.pageFilterById(pageId)[0];
    $scope.title = currentPage.UIname + ' - 编辑';


    var itemId = $scope.itemId;
    var pattern = g.patternFilterByIndexId(categoryId);
    
    $scope.elements = [];
    $scope.options = [];
    $scope.indexId = 0;
    var source = [];
    var prefix = '.createTable ';

    $scope.editConfigElements = [];
    var oeElements = g.patternFilterByPage(pageId);



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


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

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




        $.when(rest.detail(pageId, itemId)).done(function (result) {                        

          
            console.log(result);


            $scope.indexId = result.data['__c' + pattern[0].ID];
            var iid = result.data['__c' + pattern[0].ID];
            //result.data ,.join,.related
            $(a).each(function (i, o) {
                source = g.makeSource(o);
                var vv = result.data['__c' + o.ID];
                if (o.pTypeId == 10)
                {
                    
                    var imgReg =/\.(bmp|jpg|jpeg|png|gif)"?$/i;
                    $(vv).each(function (j, k) {
                        k['isImage'] = imgReg.test(k.Filename);
                    });

                  //  console.log(vv);
                }
                if (o.pTypeId == 6 )
                {
                    vv = g.dateFormat(vv);
                }
                $scope.elements.push({ p: o, v: vv, s: source });
            });

            $scope.editable = result.editable;

            $scope.$apply();
            g.jqueryInit(prefix, iid);
            if (!result.editable)
            {
                g.disable(prefix);
            }
        });



        $scope.fileSelect = function ($id) {
            $('#file_' + $id).trigger('click');

        };

        $scope.fileNameChanged = function (element) {
            $scope.$apply(function ($scope) {
                if (element.files.length > 0)
                    if (fs.existsSync(element.files[0].path)) {
                        var formData = {
                            key: cooConfig.configObj.uploadKey,
                            itemId: itemId,
                            cateId: categoryId,
                            my_file: fs.createReadStream(element.files[0].path)
                        };

                        var id = $(element).attr('id').replace(/\D/ig, '');
                        $.when(g.postFile(formData)).done(function (obj) {
                            $("#__img" + id + " ul").html("<li tag='" + obj.ID + "'><img src='" + obj.FilePath + "' width='100px' /><span>  </span><a href='javascript:void(0);' class='del' pat='" + id + "' att='" + obj.ID + "' cat='" + categoryId + "' >删除</a></li>")
                            $("#__c" + id).val(obj.ID);
                            $("#__c" + id).attr("v", "e");
                        });
                    }
            });
        }

        $scope.checkValid = function (p) {

            g.checkValid(prefix, p, $scope.indexId);

            //g.checkUQ(prefix, etor);

            //openAlert(v);
        };


        $scope.fileNameChanged2 = function (element) {
            $scope.$apply(function ($scope) {
                if (element.files.length > 0)
                    var id = $(element).attr('id').replace(/\D/ig, '');
                $(element.files).each(function (i, o) {

                    if (fs.existsSync(element.files[i].path)) {
                        var formData = {
                            key: cooConfig.configObj.uploadKey,
                            itemId: itemId,
                            cateId: categoryId,
                            my_file: fs.createReadStream(element.files[i].path)
                        };
                        $.when(g.postFile(formData)).done(function (obj) {

                            var objv = "<a href='" + obj.FilePath + "' >" + obj.Filename + "</a>";
                            var imgReg = /\.(bmp|jpg|jpeg|gif|png)$/ig;
                            if (imgReg.test(obj.FilePath)) {
                                objv = "<img src='" + obj.FilePath + "' width='100px' />";
                            }

                            $("#__img" + id + " ul").append("<li tag='" + obj.ID + "'>" + objv + "<br/><a href='javascript:void(0);' class='del' pat='" + id + "' att='" + obj.ID + "' cat='" + categoryId + "' >删除</a></li>")
                            var val = $("#__c" + id).val();
                            if (val != "") val += ",";
                            val += obj.ID;
                            $("#__c" + id).val(val);
                            $("#__c" + id).attr("v", "e");
                        });
                    }

                });
            });
        }



        $scope.openSelect = function (element) {

            $scope.element = element;

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

            $scope.currentDlg = dlg1.id;

        };


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

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





        $scope.doSubmit = function () {

               

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

                    if ($(this).attr("vad") && $(this).attr("vad") != '' && $(this).attr("vad") != 'null' && $(this).val() != '') {


                        var regStr = $(this).attr("vad");
                        if (regStr.indexOf('%') > -1) regStr = decodeURIComponent(regStr);
                        if (regStr.indexOf('%') > -1) regStr = decodeURIComponent(regStr);


                        var regx = new RegExp(regStr);
                        if (!regx.test($.trim($(this).val()))) {
                            $(this).addClass("fieldInvalid");
                            openAlert($(this).parent('div').find('span').text() + " 格式不对");
                            check = false;
                            return false;
                        }
                    }
                });


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




                $(".createTable [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 != '') {
                                $('.createTable #' + etor.name).addClass("fieldInvalid");
                                openAlert("已存在," + data);
                                uniCheck = false;
                                return false;
                            }
                        }); 
                    }
                });     

         


                if (check && reqCheck && uniCheck) {
                    var RetArray = [];
                    $(".createTable [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");

                   

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

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

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

                        RetArray.push(o);

                    });

                    $(".createTable [multiple='multiple'][v='e']").each(function (i) {
                        var tempV = $(".createTable #" + $(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 = [];
                    $(".createTable .childTable").each(function (i, t) {
                        $rows = $(t).find("tr");
                        $rows.each(function (i, tr) {
                            var erow = [];
                            $(tr).find("input[tag='redit']").each(function (i) {
                                var o = { _Key: $(this).attr('name'), _Value: $.trim($(this).val()) };
                                erow.push(o);
                            });
                            if (erow.length > 0) {
                                RArray.push({
                                    key: $(t).attr("id"),
                                    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.edit(etor)).done(function (data) {

                             g.resetUserInput(prefix);                         
                             $scope.pageNumber($scope.startIndex);
                             $scope.closeDialog();
                             $scope.$apply();
                    });
                     
                }

        };




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

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

                        $.when(locdbServices.fetchAllUserElements()).done(function (result) {
                            cooConfig.alluserelement = result;                           
                            $scope.closeDialog();
                            $scope.$apply();
                        });
                    }
                });
            }
        };

    });
});


CooWorkApp.controller('subCreateController', 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
        });
    };



    var fs = require('fs');

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

    var categoryId = $scope.categoryId;
    $scope.categoryId = categoryId;
    var pageId = $scope.createPageId;
    var currentPage = g.pageFilterById(pageId)[0];
    $scope.title = currentPage.UIname + '- ' + $scope.itemId + ' - 子项';


    var itemId = $scope.itemId;

    var pattern = g.patternFilterByIndexId(categoryId);

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

    $scope.editConfigElements = [];
    var oeElements = g.patternFilterByPage(pageId);



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


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

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



        $(a).each(function (i, o) {
            source = g.makeSource(o);
            $scope.elements.push({ p: o, s: source });
        });


        $scope.$$phase || $scope.$apply();
        g.jqueryInit(prefix, $scope.indexId);



        $scope.fileSelect = function ($id) {
            $('#file_' + $id).trigger('click');

        };

        $scope.fileNameChanged = function (element) {
            $scope.$apply(function ($scope) {
                if (element.files.length > 0)
                    if (fs.existsSync(element.files[0].path)) {
                        var formData = {
                            key: cooConfig.configObj.uploadKey,
                            itemId: itemId,
                            cateId: categoryId,
                            my_file: fs.createReadStream(element.files[0].path)
                        };

                        var id = $(element).attr('id').replace(/\D/ig, '');
                        $.when(g.postFile(formData)).done(function (obj) {
                            $("#__img" + id + " ul").html("<li tag='" + obj.ID + "'><img src='" + obj.FilePath + "' width='100px' /><span>  </span><a href='javascript:void(0);' class='del' pat='" + id + "' att='" + obj.ID + "' cat='" + categoryId + "' >删除</a></li>")
                            $("#__c" + id).val(obj.ID);
                            $("#__c" + id).attr("v", "e");
                        });
                    }
            });
        }


        $scope.fileNameChanged2 = function (element) {
            $scope.$apply(function ($scope) {
                if (element.files.length > 0)
                    var id = $(element).attr('id').replace(/\D/ig, '');
                $(element.files).each(function (i, o) {

                    if (fs.existsSync(element.files[i].path)) {
                        var formData = {
                            key: cooConfig.configObj.uploadKey,
                            itemId: itemId,
                            cateId: categoryId,
                            my_file: fs.createReadStream(element.files[i].path)
                        };
                        $.when(g.postFile(formData)).done(function (obj) {

                            var objv = "<a href='" + obj.FilePath + "' >" + obj.Filename + "</a>";
                            var imgReg = /\.(bmp|jpg|jpeg|gif|png)$/ig;
                            if (imgReg.test(obj.FilePath)) {
                                objv = "<img src='" + obj.FilePath + "' width='100px' />";
                            }

                            $("#__img" + id + " ul").append("<li tag='" + obj.ID + "'>" + objv + "<br/><a href='javascript:void(0);' class='del' pat='" + id + "' att='" + obj.ID + "' cat='" + categoryId + "' >删除</a></li>")
                            var val = $("#__c" + id).val();
                            if (val != "") val += ",";
                            val += obj.ID;
                            $("#__c" + id).val(val);
                            $("#__c" + id).attr("v", "e");
                        });
                    }

                });
            });
        }

        $scope.checkValid = function (p) {

            g.checkValid(prefix, p, $scope.indexId);

            //g.checkUQ(prefix, etor);

            //openAlert(v);
        };

        $scope.openSelect = function (element) {

            $scope.element = element;

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


            $scope.currentDlg = dlg1.id;

        };


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

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




        $scope.doSubmit = function () {

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

                if ($(this).attr("vad") && $(this).attr("vad") != '' && $(this).attr("vad") != 'null' && $(this).val() != '') {

                    var regStr = $(this).attr("vad");
                    if (regStr.indexOf('%') > -1) regStr = decodeURIComponent(regStr);
                    if (regStr.indexOf('%') > -1) regStr = decodeURIComponent(regStr);

                    var regx = new RegExp(regStr);
                    if (!regx.test($.trim($(this).val()))) {
                        $(this).addClass("fieldInvalid");
                        check = false;
                        msg = $(this).parent('div').find('span').text() + " 格式不对";
                        //   openAlert($(this).parent('div').find('span').text() + " 格式不对");                
                        return false;
                    }
                }
            });


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




            $(".createTable [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) {
                        var rd = /\d/ig;
                        if (data != '' && rd.test(data)) {
                            $('.createTable #' + etor.name).addClass("fieldInvalid");
                            uniCheck = false;
                            msg = "已存在," + data;
                            //openAlert("已存在," + data);


                        }
                    });
                }

            });






            if (check && reqCheck && uniCheck) {
                var RetArray = [];
                $(".createTable [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");

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

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

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

                    RetArray.push(o);

                });

                $(".createTable [multiple='multiple'][v='e']").each(function (i) {
                    var tempV = $(".createTable #" + $(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 = [];
                $(".createTable .childTable").each(function (i, t) {
                    $rows = $(t).find("tr");
                    $rows.each(function (i, tr) {
                        var erow = [];
                        $(tr).find("input[tag='redit']").each(function (i) {
                            var o = { _Key: $(this).attr('name'), _Value: $.trim($(this).val()) };
                            erow.push(o);
                        });
                        if (erow.length > 0) {
                            RArray.push({
                                key: $(t).attr("id"),
                                value: erow
                            });
                        }
                    });
                });

                if (itemId > 0)
                {
                    var pattern = _.filter(cooConfig.allpattern, function (p) { return p.categoryId == categoryId && p.pTypeId == 18; });                   
                    RetArray.push({ _Key: '__c'+pattern[0].ID, _Value: itemId });
                }


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


                

                var iid = $scope.indexId;

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

                //console.log(etor);

                //openAlert("ok!");



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

                 //   openAlert("ok!");
                 //   g.resetUserInput(prefix);
                    $scope.pageNumber($scope.startIndex);
                    $scope.closeDialog();
                    $scope.$apply();
                });

            }
            else {
                openAlert(msg);
            }

        };





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

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

                        $.when(locdbServices.fetchAllUserElements()).done(function (result) {
                            cooConfig.alluserelement = result;
                            $scope.closeDialog();
                            $scope.$apply();
                        });
                    }
                });
            }
        };

    });
});



CooWorkApp.controller('joinCreateController', 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
        });
    };



    var fs = require('fs');

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

    var backCategoryId = $scope.categoryId;




   
    var pageId = $scope.joinPageId;
    var currentPage = g.pageFilterById(pageId)[0];
    var currentCategory = g.getCategoryById(backCategoryId)[0];
    $scope.title = ' ' + currentCategory.categoryName + ':' + $scope.itemId + ' ' + '  - 关联项 - ' + currentPage.UIname;

    var categoryId = currentPage.categoryId;
    $scope.categoryId = categoryId;
    var jp = _.filter(cooConfig.alljoin, function (j) { return j.categoryId == categoryId && j.joinCategoryId == backCategoryId });

    var itemId = 0;
    var pattern = g.patternFilterByIndexId(categoryId);

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

    $scope.editConfigElements = [];
    var oeElements = g.patternFilterByPage(pageId);



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


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

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



        $(a).each(function (i, o) {
            source = g.makeSource(o);
            $scope.elements.push({ p: o, s: source });
        });

  

        $scope.$$phase || $scope.$apply();
        g.jqueryInit(prefix, $scope.indexId);
        

        $scope.fileSelect = function ($id) {
            $('#file_' + $id).trigger('click');

        };

        $scope.fileNameChanged = function (element) {
            $scope.$apply(function ($scope) {
                if (element.files.length > 0)
                    if (fs.existsSync(element.files[0].path)) {
                        var formData = {
                            key: cooConfig.configObj.uploadKey,
                            itemId: itemId,
                            cateId: categoryId,
                            my_file: fs.createReadStream(element.files[0].path)
                        };

                        var id = $(element).attr('id').replace(/\D/ig, '');
                        $.when(g.postFile(formData)).done(function (obj) {
                            $("#__img" + id + " ul").html("<li tag='" + obj.ID + "'><img src='" + obj.FilePath + "' width='100px' /><span>  </span><a href='javascript:void(0);' class='del' pat='" + id + "' att='" + obj.ID + "' cat='" + categoryId + "' >删除</a></li>")
                            $("#__c" + id).val(obj.ID);
                            $("#__c" + id).attr("v", "e");
                        });
                    }
            });
        }


        $scope.fileNameChanged2 = function (element) {
            $scope.$apply(function ($scope) {
                if (element.files.length > 0)
                    var id = $(element).attr('id').replace(/\D/ig, '');
                $(element.files).each(function (i, o) {

                    if (fs.existsSync(element.files[i].path)) {
                        var formData = {
                            key: cooConfig.configObj.uploadKey,
                            itemId: itemId,
                            cateId: categoryId,
                            my_file: fs.createReadStream(element.files[i].path)
                        };
                        $.when(g.postFile(formData)).done(function (obj) {

                            var objv = "<a href='" + obj.FilePath + "' >" + obj.Filename + "</a>";
                            var imgReg = /\.(bmp|jpg|jpeg|gif|png)$/ig;
                            if (imgReg.test(obj.FilePath)) {
                                objv = "<img src='" + obj.FilePath + "' width='100px' />";
                            }

                            $("#__img" + id + " ul").append("<li tag='" + obj.ID + "'>" + objv + "<br/><a href='javascript:void(0);' class='del' pat='" + id + "' att='" + obj.ID + "' cat='" + categoryId + "' >删除</a></li>")
                            var val = $("#__c" + id).val();
                            if (val != "") val += ",";
                            val += obj.ID;
                            $("#__c" + id).val(val);
                            $("#__c" + id).attr("v", "e");
                        });
                    }

                });
            });
        }

        $scope.checkValid = function (p) {

            g.checkValid(prefix, p, $scope.indexId);

            //g.checkUQ(prefix, etor);

            //openAlert(v);
        };

        $scope.openSelect = function (element) {

            $scope.element = element;

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


            $scope.currentDlg = dlg1.id;

        };


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

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




        $scope.doSubmit = function () {

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

                if ($(this).attr("vad") && $(this).attr("vad") != '' && $(this).attr("vad") != 'null' && $(this).val() != '') {
                    var regStr = $(this).attr("vad");
                    if (regStr.indexOf('%') > -1) regStr = decodeURIComponent(regStr);
                    if (regStr.indexOf('%') > -1) regStr = decodeURIComponent(regStr);

                    var regx = new RegExp(regStr);
                    if (!regx.test($.trim($(this).val()))) {
                        $(this).addClass("fieldInvalid");
                        check = false;
                        msg = $(this).parent('div').find('span').text() + " 格式不对";
                        //   openAlert($(this).parent('div').find('span').text() + " 格式不对");                
                        return false;
                    }
                }
            });


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




            $(".createTable [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) {
                        var rd = /\d/ig;
                        if (data != '' && rd.test(data)) {
                            $('.createTable #' + etor.name).addClass("fieldInvalid");
                            uniCheck = false;
                            msg = "已存在," + data;
                            //openAlert("已存在," + data);


                        }
                    });
                }

            });






            if (check && reqCheck && uniCheck) {
                var RetArray = [];
                $(".createTable [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");

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

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

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

                    RetArray.push(o);

                });

                $(".createTable [multiple='multiple'][v='e']").each(function (i) {
                    var tempV = $(".createTable #" + $(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 = [];
                $(".createTable .childTable").each(function (i, t) {
                    $rows = $(t).find("tr");
                    $rows.each(function (i, tr) {
                        var erow = [];
                        $(tr).find("input[tag='redit']").each(function (i) {
                            var o = { _Key: $(this).attr('name'), _Value: $.trim($(this).val()) };
                            erow.push(o);
                        });
                        if (erow.length > 0) {
                            RArray.push({
                                key: $(t).attr("id"),
                                value: erow
                            });
                        }
                    });
                });

                if ($scope.itemId > 0) {
                   
                    if (jp.length > 0) {
                        RetArray.push({ _Key: '__j' + jp[0].joinPatternId, _Value: $scope.itemId });
                    }
                }


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




                var iid = $scope.indexId;

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

                console.log(etor);

             //   openAlert("ok!");



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

                //    openAlert("ok!");
                    console.log($scope.categoryId);
                    $scope.categoryId = backCategoryId;
                    console.log($scope.categoryId);
                    $scope.pageNumber($scope.startIndex);
                    $scope.closeDialog();
                  //  g.resetUserInput(prefix);
                    $scope.$apply();
                });

            }
            else {
                openAlert(msg);
            }

        };





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

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

                        $.when(locdbServices.fetchAllUserElements()).done(function (result) {
                            cooConfig.alluserelement = result;
                            $scope.closeDialog();
                            $scope.$apply();
                        });
                    }
                });
            }
        };

    });
});







CooWorkApp.controller('createController', function ($rootScope,$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 fs = require('fs');

    var categoryId = $routeParams.categoryId;
    $scope.categoryId = categoryId;
    var pageId = $routeParams.pageId;
    var currentPage = g.pageFilterById(pageId)[0];
    $rootScope.title = currentPage.UIname + ' - 创建';

     
    var pattern = g.patternFilterByIndexId(categoryId);

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

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


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

        //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 });
        });        

    
        $scope.$$phase || $scope.$apply();
        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.checkValid = function (p) {
        g.checkValid('',p,$scope.indexId);
        //openAlert(v);
    };

    $scope.fileSelect = function ($id) { 
        $('#file_' + $id).trigger('click');
       
    };

    $scope.fileNameChanged = function (element) {
        $scope.$apply(function ($scope) {
            if (element.files.length > 0)
                if (fs.existsSync(element.files[0].path)) {
                    var formData = {                   
                        key: cooConfig.configObj.uploadKey,
                        itemId: 0,
                        cateId: categoryId,                       
                        my_file: fs.createReadStream(element.files[0].path)                                   
                    };

                    var id = $(element).attr('id').replace(/\D/ig,'');
                    $.when(g.postFile(formData)).done(function (obj) {
                    $("#__img" + id + " ul").html("<li tag='" + obj.ID + "'><img src='" + obj.FilePath + "' width='100px' /><span>  </span><a href='javascript:void(0);' class='del' pat='"+id+"' att='"+obj.ID+"' cat='"+categoryId+"' >删除</a></li>")
                    $("#__c" + id).val(obj.ID);
                    $("#__c" + id).attr("v", "e");
                    });                     
                }
        });
    }


    $scope.fileNameChanged2 = function (element) {
        $scope.$apply(function ($scope) {
            if (element.files.length > 0)
                var id = $(element).attr('id').replace(/\D/ig, '');
                $(element.files).each(function (i,o) {

                    if (fs.existsSync(element.files[i].path)) {
                        var formData = {
                            key: cooConfig.configObj.uploadKey,
                            itemId: 0,
                            cateId: categoryId,
                            my_file: fs.createReadStream(element.files[i].path)
                        };
                        $.when(g.postFile(formData)).done(function (obj) {

                            var objv = "<a href='" + obj.FilePath + "' >" + obj.Filename + "</a>";
                            var imgReg =/\.(bmp|jpg|jpeg|gif|png)$/ig;
                            if (imgReg.test(obj.FilePath))
                            {
                                objv = "<img src='" + obj.FilePath + "' width='100px' />";
                            }

                            $("#__img" + id + " ul").append("<li tag='" + obj.ID + "'>"+objv+"<br/><a href='javascript:void(0);' class='del' pat='" + id + "' att='" + obj.ID + "' cat='" + categoryId + "' >删除</a></li>")
                            var val = $("#__c" + id).val();
                            if (val != "") val += ",";
                            val += obj.ID;
                            $("#__c" + id).val(val);
                            $("#__c" + id).attr("v", "e");
                        });
                    }

                });              
        });
    }





    $scope.openSelect = function (element) {

        $scope.element = element;

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


        $scope.currentDlg = dlg1.id;

    };


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

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




    $scope.doSubmit = function () {

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

            if ($(this).attr("vad") && $(this).attr("vad") != '' && $(this).attr("vad") != 'null' && $(this).val() != '') {
                var regStr = $(this).attr("vad");
                if (regStr.indexOf('%') > -1) regStr = decodeURIComponent(regStr);
                if (regStr.indexOf('%') > -1) regStr = decodeURIComponent(regStr);

                var regx = new RegExp(regStr);
                if (!regx.test($.trim($(this).val()))) {
                    $(this).addClass("fieldInvalid");
                    check = false;
                    msg = $(this).parent('div').find('span').text() + " 格式不对";
                 //   openAlert($(this).parent('div').find('span').text() + " 格式不对");                
                    return false;
                }
            }
        });


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




        $(".createTable [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) {
                    var rd =/\d/ig;
                    if (data != '' && rd.test(data) ) {
                        $('.createTable #' + etor.name).addClass("fieldInvalid");                     
                        uniCheck = false;                         
                        msg = "已存在," + data;
                        //openAlert("已存在," + data);
                       
                     
                    }
                });              
            }
          
        });

  
    

    

        if (check && reqCheck && uniCheck) {
            var RetArray = [];
            $(".createTable [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);
            });

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

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

                RetArray.push(o);

            });

            $(".createTable [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 = [];
            $(".createTable .childTable").each(function (i, t) {
                $rows = $(t).find("tr");
                $rows.each(function (i, tr) {
                    var erow = [];
                    $(tr).find("input[tag='redit']").each(function (i) {
                        var o = { _Key: $(this).attr('name'), _Value: $.trim($(this).val()) };
                        erow.push(o);
                    });
                    if (erow.length > 0) {
                        RArray.push({
                            key: $(t).attr("id"),
                            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
            }; 



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

                openAlert("ok!");
               
                g.resetUserInput(prefix);       
                $scope.$apply();
            });

        }
        else
        {
            openAlert(msg);
        }

    };




});








CooWorkApp.controller('viewController', function ($scope, $location, $routeParams, $sce,_, locdbServices, userSetting, cooConfig, g, rest,ngDialog) {


    var categoryId = $scope.categoryId;
    var pageId = $scope.viewPageId;
    var itemId = $scope.itemId;
    var currentPage = g.pageFilterById(pageId)[0];
    $scope.title = currentPage.UIname + '  ';

    var pattern = g.patternFilterByIndexId(categoryId);

    $scope.elements = [];
    $scope.options = [];
    $scope.indexId = 0;
    var source = [];


    $scope.print = function () {

        var etor = { pageId: pageId, itemId: itemId };


        $.when(rest.print(etor)).done(function (a) {
            if (a != null && a != '')
            {
                window.open(a);
                //window.location.href = a;
              //  $scope.$apply();
                ngDialog.closeAll();
                //  window.open(a);
            }
            console.log(a);
        });
      //  console.log('ppp');
     //   window.print();

    };


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

        $.when(rest.detail(pageId, itemId)).done(function (result) {

           // console.log(result);

            $scope.indexId = result.data['__c' + pattern[0].ID];
            //result.data ,.join,.related
            $(a).each(function (i, o) {
                source = g.makeSource(o);               
                var val = result.data['__c' + o.ID];

              

                switch(o.pTypeId)
                {
                    case 2:
                    case 13:
                    case 20:                    
                        if (val!=undefined)
                        {                          
                            var vv = ',' + val.toString() + ',';   
                            var source = _.filter(cooConfig.allstatus, function (item) {
                               return  vv.indexOf(item.ID.toString()) != -1 && item.patternId == o.ID;
                            });                          
                            val = _.pluck(source, 'statusName').join(',');                        
                        }

                        break;
                    case 19:
                        if (val != undefined) {
                            source = g.userFilterByUserIds(val);
                            val = source;
                        }
                        break;
                    case 6:
                        val = g.dateFormat(val);
                        break;
                    case 7:
                        val = $sce.trustAsHtml(val);


                        break;
                    case 11:
                        if (val!=undefined && val.FilePath!=undefined)  val.FilePath = val.FilePath.replace('/100', '');
                        break;
                    case 10:
                        $(val).each(function (p,k) {
                            k.FilePath = k.FilePath.replace('/100', '');
                        });
                        break;
                    default:
                        break;
                }

                $scope.elements.push({ p: o, v: val , s: source });
            });

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

});






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


    var categoryId = $scope.categoryId;
    var pageId = $scope.exportPageId;
    var listPageId = $scope.listPageId;
    var lsc = $scope.lsc;

    var pattern = g.patternFilterByIndexId(categoryId);
   

    var currentPage = g.pageFilterById(pageId)[0];
    $scope.title = currentPage.UIname + ' - 导出';


    $scope.elements = [];
 
    var source = [];

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

     //   $scope.elements = g.patternFilterByPage(pageId);


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

     //   $('#export').multiselect({
     //       enableCaseInsensitiveFiltering: true,
     //       includeSelectAllOption: true
     //   });




        $scope.exportData = function () {

            var etor =
                {
                    lsc: lsc,
                    categoryId: categoryId,
                    pageId: listPageId,
                    iElementPage: pageId,
                    cols: "" + $("#__p" + pageId).val() + "",
                    raw:$('#raw').is(':checked')
                };     


            $.when(rest.export(etor)).done(function (url) {
        
                window.location.href = url;
                $scope.$apply();
                ngDialog.closeAll();
            });
        };
         
  //  });

});









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

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



    var fs = require('fs');
    var categoryId = $scope.categoryId;
    var pageId = $scope.importPageId;
    
    var currentPage = g.pageFilterById(pageId)[0];
    $scope.title = currentPage.UIname + ' - 导入';


    $scope.cElements = [];

    $scope.importConfigElements = [];
    var oiElements = g.patternFilterByPage(pageId);


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


        var eleStr = ',';
        $(a).each(function (i, o) {           
            $scope.cElements.push(o);
            eleStr += o.ID + ',';

        });


        //config   

        $(oiElements).each(function (i, o) {
            if (eleStr.indexOf(',' + o.ID.toString() + ',') > -1) {
                $scope.importConfigElements.push({ item: o, select: true });
            }
            else {
                $scope.importConfigElements.push({ item: o, select: false });
            }
        });
        //config
        $scope.$$phase || $scope.$apply();
        g.importInit();


        $scope.selectAll2 = function () {
            if ($("#selectAll2").prop("checked") != true) {
                $("#importb tr td").find('input[type=checkbox]').prop("checked", false);
            } else {
                $("#importb tr td").find('input[type=checkbox]').prop("checked", true);
            }
        };


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

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

                        $.when(locdbServices.fetchAllUserElements()).done(function (result) {
                            cooConfig.alluserelement = result;
                            $scope.closeDialog();
                            $scope.$apply();
                        });
                    }
                });
            }
        };



        $scope.fileSelect = function ($id) {
            $('#file_' + $id).trigger('click');

        };

        $scope.fileNameChanged = function (element) {
            $scope.$apply(function ($scope) {
                if (element.files.length > 0)
                    if (fs.existsSync(element.files[0].path)) {
                        var formData = {
                            key: cooConfig.configObj.uploadKey,
                            itemId: 0,
                            cateId: categoryId,
                            my_file: fs.createReadStream(element.files[0].path)
                        };

                        var id = $(element).attr('id').replace(/\D/ig, '');
                        $.when(g.postFile(formData)).done(function (obj) {
                          

                            var etor = {
                                cateId: categoryId,
                                pageId: pageId,
                                aid: obj.ID
                            };

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

                             
                                $("#importb tr:nth-child(n+2)").remove();

                                $(data).each(function (i, item) {
                                    var tr = '<tr>';
                                    tr += '<td> <input  type="checkbox"  name="mainCheckBox"></td>';
                                    $($scope.cElements).each(function (j, p) {

                                        var v = item['__c' + p.ID] == undefined ? "" : item['__c' + p.ID];

                                        tr += '<td ><div contenteditable="true" name="__c' + p.ID + '" >' + v + '</div></td>';

                                    });

                                    tr += '</tr>';
                                    $("#importb").append(tr);
                                });


                                $scope.$apply();
                            });





                        });
                    }
            });
        }



        $scope.submit = function () {

            openConfirm('确认提交？');


            //ngDialog.close(id);
            //if (flag) {
            //    var vals = getChecked();
            //    if (vals == "") return openAlert('未选中！');

            //    var etor = {
            //        ids: vals,
            //        categoryId: categoryId
            //    };

            //    $.when(rest.adminDel(etor)).done(function (f) {
            //        if (f) { renderList(); } else { openAlert('删除失败！'); };
            //    });
            //}
        }



        $scope.closeConfirm = function (id, flag) {

            ngDialog.close(id);
            if (flag) {

                var $table = $("#importb");
                var $tr1 = $table.find("tr:nth-child(1)");
                var $th = $tr1.find("th");


                var flag = true;
                $.each($th, function (i, node) {
                    var tag = $(node).attr("vad");
                    if (tag != "" && i != 0 && tag != "null") {
                        var k = i + 1;
                        var regx = new RegExp(decodeURIComponent(tag));
                        $table.find("tr td:nth-child(" + k + ")").each(function (j, node2) {
                            if ($.trim($(node2).text()) != "" && !regx.test($.trim($(node2).text()))) {
                                $(node2).css("background-color", "red");
                                flag = false;
                            }
                        });
                    }
                });
                if (!flag)
                    return false;



                var $tr = $table.find("tr");
                var data = [];
                $.each($tr, function (i, n) {

                    if (i != 0) {
                        var erow = [];
                        $(n).find("td").each(function (k, kn) {
                            if ($.trim($(kn).text()) != '' && $(kn).find("div").attr("name") != undefined && $(kn).find("div").attr("name") != '') {
                                var o = { _Key: $(kn).find("div").attr("name"), _Value: $.trim($(kn).text()) };
                                erow.push(o);
                            }
                        });
                        data.push(erow);
                    }
                });



                var etor = {
                    jsonStr: JSON.stringify(data),
                    pageId: pageId
                };


                if (data.length > 0) {

                    $.when(rest.bulkCreate(etor)).done(function () {
                        $("#importb tr:nth-child(n+2)").remove();
                        openAlert('已导入!');
                        $scope.pageNumber($scope.startIndex);
                        $scope.closeDialog();

                    });

                }
                else {
                    openAlert("无数据！");
                }

            };
        }

    });    
});





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

    var categoryId = $scope.categoryId;
    var itemId = $scope.itemId;

    $scope.datalogs = [];

    var etor = {
        categoryId: categoryId,
        itemId:itemId
    };

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

        $(result).each(function (i, o) {
            $scope.datalogs.push(o);
        });
        $scope.$apply();
         
    });

});




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

    var categoryId = $scope.categoryId;
    var itemId = $scope.itemId;

    $scope.workflowlogs = [];

    var etor = {
        categoryId: categoryId,
        itemId: itemId
    };

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

        $(result).each(function (i, o) {
            $scope.workflowlogs.push(o);
        });

        $scope.$apply();

    });

});