CooWorkApp.controller('complexeditController', 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 = $scope.categoryId;
    var pageId = $scope.editPageId;
    var itemId = $scope.itemId;



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

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

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


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

        p20 = g.pageFilter(20, pageId);
        $scope.subPageId = p20[0].ID;
        $scope.subElements = g.patternFilterByPage(p20[0].ID);
     
        $($scope.subElements).each(function (i,j) {
            if (j.pTypeId == 16) $scope.subIndexPatternId = j.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.editConfigElements.push({ item: o, select: true });
            }
            else {
                $scope.editConfigElements.push({ item: o, select: false });
            }
        });
        //config





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

            $scope.indexId = result.data['__c' + pattern[0].ID];
            ////result.data ,.join,.related
            $(a).each(function (i, o) {
                source = g.makeSource(o);
                $scope.elements.push({ p: o, v: result.data['__c' + o.ID], s: source });
            });
          



            var ppp = g.joinFilterByAB(subCategoryId, subJoinCategoryId);
            var joinPatternIndex = g.patternFilterByIndexId(subJoinCategoryId)[0].ID;
            var joinPatternId = ppp[0].joinPatternId;


            //console.log(result.related[subCategoryId]);

            $('#rowcount').val(result.related[subCategoryId].length);
            $(result.related[subCategoryId]).each(function (i, item) {

                addChild('table_' + p20[0].ID);
                var j = 3 + i;
                $("[tag ='table_" + p20[0].ID + "'] tr:nth-child(" + j + ") input[name='view__j" + joinPatternId + "']").val(item["__c" + joinPatternId]);
                $("[tag ='table_" + p20[0].ID + "'] tr:nth-child(" + j + ") input[name='__j" + joinPatternId + "']").val(item['__c' + joinPatternIndex]);
                $($scope.subElements).each(function (m, n) {                   
                    $("[tag ='table_" + p20[0].ID + "'] tr:nth-child(" + j + ") input[name='__c" + n.ID + "']").val(item['__c' + n.ID]);

                    if (n.pTypeId==16)
                    {
                        $("[tag ='table_" + p20[0].ID + "'] tr:nth-child(" + j + ") input[name='__c" + n.ID + "']").attr('v', 'e');
                    }

                });
            });



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

            g.dfnScript('');

        });











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

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

                        $.when(locdbServices.fetchAllUserElements()).done(function (result) {
                            cooConfig.alluserelement = result;
                            console.log('redirect');
                            $scope.closeDialog();
                        });
                    }
                });
            }
        };

    });


    $scope.closeDialog = function () {

        ngDialog.closeAll();
    };



    $scope.addChild = function () {

        var s = 'table_' + p20[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_' + p20[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(p20[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;

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

        $scope.selectDlg = dlg.id;

    };


    $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.close($scope.selectDlg);
    };





    $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_" + p20[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_' + p20[0].ID);
                        var j = 3 + i+ parseInt($('#rowcount').val());
                        $("[tag ='table_" + p20[0].ID + "'] tr:nth-child(" + j + ") input[name='view__j" + joinPatternId + "']").val(item["__c" + joinPatternId]);
                        $("[tag ='table_" + p20[0].ID + "'] tr:nth-child(" + j + ") input[name='__j" + joinPatternId + "']").val(item['__c' + joinPatternIndex]);
                        $("[tag ='table_" + p20[0].ID + "'] tr:nth-child(" + j + ") input[name='__j" + joinPatternId + "']").attr('v', 'e');

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

                    var rows = parseInt($('#rowcount').val());
                    $('#rowcount').val(rows + result.data.length);

                });
            }
        }
    };





    $scope.dosm2 = function () {
        $('#saomadiv2').show();
    };

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

    $scope.saomasubmit2 = function () {
        var val = $("#idlist2").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);
        $("#saomadiv2").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");


                if ($(this).attr('multiple') == 'multiple') {
                    var tempE = $("#" + $(this).attr("id")).val();

                    if (tempE != undefined && tempE.length > 0) {
                        tempV = tempE.join(',');
                    }
                }



                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("[tag='edit'][v='e']").each(function (i) {
                            var o = { _Key: $(this).attr('name'), _Value: $.trim($(this).val()) };
                            erow.push(o);
                        });
                        if (erow.length > 0) {
                            
                            RArray.push({
                                key: '__p'+$scope.subPageId,
                                value: erow
                            });
                        }
                    }
                });
            });

            var mainData = [];
            mainData.push({ key: '__p' + pageId, value: RetArray });


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

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



            var iid = $scope.indexId;

            var etor = {
                jsonStr: d1,
                relatedSTR: d2,
                pageId: pageId,
                itemId: iid,
                delSTR: JSON.stringify(delist)
            };


            console.log(etor);

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

        
                $scope.pageNumber($scope.startIndex);
                $scope.closeDialog();
                $scope.$apply();

            });

        }
    };

});





CooWorkApp.controller('complexviewController', 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 = $scope.categoryId;
    var pageId = $scope.viewPageId;
    var itemId = $scope.itemId;



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

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

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


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

        p22 = g.pageFilter(22, pageId);
        $scope.subPageId = p22[0].ID;
        $scope.subElements = g.patternFilterByPage(p22[0].ID);

        $($scope.subElements).each(function (i, j) {
            if (j.pTypeId == 16) $scope.subIndexPatternId = j.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.editConfigElements.push({ item: o, select: true });
            }
            else {
                $scope.editConfigElements.push({ item: o, select: false });
            }
        });
        //config





        $.when(rest.detail(pageId, itemId)).done(function (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 });                
            });




        //    var ppp = g.joinFilterByAB(subCategoryId, subJoinCategoryId);
        //    var joinPatternIndex = g.patternFilterByIndexId(subJoinCategoryId)[0].ID;
    
       //     console.log(result.related[subCategoryId]);

            $scope.subData = [];

            $(result.related[subCategoryId]).each(function (j, val) {

                var row = [];
                for (var k = 0; k < $scope.subElements.length; k++) {

                    var v = g.prepareVal(val, $scope.subElements[k]);

                    var ctor = { ID: $scope.subElements[k].ID, pTypeId: $scope.subElements[k].pTypeId, val: v };

                    row.push(ctor);
                  
                };

                $scope.subData.push(row);

            });



           



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


            g.dfnScript('');

        });











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

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

                        $.when(locdbServices.fetchAllUserElements()).done(function (result) {
                            cooConfig.alluserelement = result;
                            console.log('redirect');
                            $scope.closeDialog();
                        });
                    }
                });
            }
        };

    });


    $scope.closeDialog = function () {

        ngDialog.closeAll();
    };



    $scope.addChild = function () {

        var s = 'table_' + p22[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_' + p22[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 () {

        if (p22==undefined || p22.length == 0) return;

        var pmain = g.patternFilterByPage(p22[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

     



 
     


    

});

