/**
 * Created by chen on 2017/8/1.
 */



var feeRateObject={
    mainViews:null,
    datas:null,
    canEdit:false,
    activateFeeRate:null,
    needCascadeSet:false,
    selectionLoad:false,
    changeInfo:null,
    columns: [
        {
            id: 'name',
            caption: '专业名称',
            dataField: 'name',
            width: 450,
            allowEditing: false
        },
        {
            id: 'rate',
            caption: '值%',
            dataField: 'rate',
            format: '0.000',
            width: 120,
            minWidth: 50,
            allowEditing: true
        },
        {
            id: 'memo',
            caption: '备注',
            dataField: 'memo',
            minWidth: 120,
            allowEditing: true
        },
        {
            id: 'ID',
            caption: 'ID',
            dataField: 'ID',
            width: 80,
            visible: false,
            allowEditing: false
        },
        {
            id: 'subFeeRate',
            caption: '子费率',
            dataField: 'subFeeRate',
            width: 80,
            visible: false,
            allowEditing: false
        },
        {
            id: '_id',
            caption: '自动ID',
            dataField: '_id',
            width: 80,
            visible: false,
            allowEditing: false
        },
        {
            id: 'ParentID',
            caption: '父结点ID',
            dataField: 'ParentID',
            width: 80,
            visible: false,
            allowEditing: false
        }
    ],
    options :{
        allowSorting: false,
        showRowHeader: true,
        colMinWidth: 80,
        rowHeight: 30,
        allowEditing: true,
        editMode: 'inline',
        editUnit: 'cell',
        selectionUnit:  "row",
        hierarchy: {
            keyField: 'ID',
            parentField: 'ParentID',
            collapsed: false,
            column: 'name'
        }
    },
    dataSource : {
        loadRange: function(params) {
            params.success(feeRateObject.datas);
        },
        update: function(params) {
            if(!params.hasOwnProperty('sourceIndex')){
               var selected = feeRateObject.mainViews.getSelections()[0];
                params.sourceIndex = selected.sourceRow;
            }
            if(!$('#cascadeSet').prop('checked')||params.hasOwnProperty('viewIndex')){
                projectObj.project.FeeRate.updateFeeRateByEdit(params,feeRateObject.activateFeeRate);
            }
            params.success();
        }
    },
    createSpreadView:function () {
        if (this.mainViews) {
            this.mainViews.destroy();
            this.mainViews = null;
        }
        this.activateFeeRate = projectObj.project.FeeRate.getActivateFeeRate();
        this.datas = this.activateFeeRate.rates;
        this.mainViews = new GC.Spread.Views.DataView($('#divFee')[0],
            this.dataSource, this.columns, new GC.Spread.Views.Plugins.GridLayout(this.options));
        this.mainViews["rowClick"].addHandler(subRateObject.reFreshRateViews);
        this.mainViews .invalidate();
        document.querySelector('#divFee').focus();
    },
    reFreshRateViews:function() {
        if(this.mainViews){
            this.mainViews.refresh()
        }else {
            feeRateObject.createSpreadView();
            //setTimeout("feeRateObject.createSpreadView()",100);
        }
    },
    updateBySelect:function (rate,selectMap,mapID) {
       var selected = this.mainViews.getSelections()[0];
       var item = this.datas[selected.sourceRow];
        item.rate = rate;
        _.forEach(selectMap,function (value,key) {
            var recode =  item.subFeeRate.recodes[key];
            var optionList = recode.optionList;
            _.forEach(optionList,function (o) {
                if(o.value==value){
                    o.selected=true;
                }else {
                    o.selected = false;
                }
            })
        })
        if($('#cascadeSet').prop('checked')){
            this.cascadeSetRates(item,selected.sourceRow,mapID,selectMap)
        }else {
            this.mainViews.data.updateItem(selected.sourceRow,item);
        }
        projectObj.project.FeeRate.synchronizeFeeRate();

        //this.views.data.updateItem()
    },
    cascadeSetRates:function(selectedItem,sourceRow,mapID,selectMap){
        var items=[];
        items.push({rateIndex:sourceRow,rate:selectedItem});
        _.forEach(this.datas,function (recode,Index) {
            if(Index!=sourceRow&&recode.subFeeRate){
                var valueMaps = recode.subFeeRate.valueMaps;
                var valueMap = _.find(valueMaps,{ID:mapID});
                if(valueMap){//选项完全一样的情况
                    if(valueMap.value==recode.rate){
                        return;
                    }else {
                        recode.rate = valueMap.value;
                        _.forEach(selectMap,function (value,key) {
                            var tempRecode =  recode.subFeeRate.recodes[key];
                            var optionList = tempRecode.optionList;
                            _.forEach(optionList,function (o) {
                                if(o.value==value){
                                    o.selected=true;
                                }else {
                                    o.selected = false;
                                }
                            })
                        })
                        items.push({rateIndex:Index,rate:recode});
                    }
                }else {//某条选项一样的情况
                    var needUpdate = false;
                    var selectList = mapID.split('-');
                    var newList=[];
                    _.forEach(recode.subFeeRate.recodes,function (r) {
                        var oList = r.optionList;
                        var oldSelectIndex=0;
                        var hasChange=false;
                        _.forEach(oList,function (o,key) {
                            if(o.selected){
                                oldSelectIndex = key;
                            }
                            if(_.includes(selectList,o.value)){
                                needUpdate=true;
                                o.selected=true;
                                hasChange=true;
                                newList.push(o.value);
                            }else {
                                o.selected=false;
                            }
                        })
                        if(!hasChange){
                            oList[oldSelectIndex].selected=true;
                            newList.push(oList[oldSelectIndex].value)
                        }
                    })
                    if(needUpdate){
                      var newValue =   _.find(valueMaps,{ID:newList.join("-")})//取出费率值并更新
                        if(newValue){
                          if(recode.rate != newValue.value){
                              recode.rate = newValue.value
                              items.push({rateIndex:Index,rate:recode});
                          }
                        }
                    }
                }
            }
        })

        _.forEach(items,function (t) {
            feeRateObject.mainViews.data.updateItem(t.rateIndex,t.rate);
        })

        projectObj.project.FeeRate.batchUpdateFeeRate(items,feeRateObject.activateFeeRate);
    },
    loadPageContent:function(){
        var feeRateFile = projectObj.project.FeeRate.getActivateFeeRate();
        var usageProjects = feeRateFile.usageProjects;
        $('#feeRateFileName').text(feeRateFile.name);
        $('#feeRateLibName').text(feeRateFile.libName);
        $('#projectCount').text(usageProjects.length);
    },
    loadFeeRateSelection:function() {
        if(!this.selectionLoad){
            var selectedID=0;
            _.forEach(projectObj.project.FeeRate.datas,function (data) {
                var option =  $("<option>").val(data.ID).text(data.libName);
                $('#inlineFormCustomSelect').append(option);
                if(data.status=='activate'){
                    selectedID=data.ID;
                }
            })
            $('#inlineFormCustomSelect').val(selectedID);
        }
    },
    getFeeRateStandards:function (callback) {
        CommonAjax.post('/feeRates/getFeeRateStandards', {"projectID": projectObj.project.ID()}, function (data) {
            if (data) {
                callback(data);
            }
        });
    },
    changeFeeRateStandard:function(newVal){
        var callback=function () {
            feeRateObject.createSpreadView();
            feeRateObject.loadPageContent();
            projectObj.project.FeeRate.synchronizeFeeRate();
            subRateObject.destorySpreadView();
        };
        projectObj.project.FeeRate.changeFeeRateStandard(newVal,callback);
    },
    checkFeeRateName:function (newVal) {
        if(!newVal||newVal==""){
            $('#saveAsConfirm').attr("disabled","disabled");
            $('#nameError').text("请输入文件名称。").show();
            return;
        }
        var callback=function (data) {
            if(data){
                $('#saveAsConfirm').attr("disabled","disabled");
                $('#nameError').text("已存在同名费率文件。").show();
                $('#valid_name').val('');
            }else {
                $('#valid_name').val(newVal);
                $('#saveAsConfirm').removeAttr("disabled");
                $('#nameError').hide();
            }
            console.log(data);
        };
        projectObj.project.FeeRate.checkFeeRateName(newVal,callback);
    },
    feeRateFileSaveAs:function (newName) {
        if(!newName||newName==""){
            $('#saveAsConfirm').attr("disabled","disabled");
            $('#nameError').text("请输入文件名称。").show();
            return;
        }
        var valideName = $('#valid_name').val();
        if(valideName==''||valideName!==newName){
            var callback=function (data) {
                if(data){
                    $('#saveAsConfirm').attr("disabled","disabled");
                    $('#nameError').text("已存在同名费率文件。").show();
                    $('#valid_name').val('');
                }else {
                    feeRateObject.submitSaveAs(newName);
                }
            }
            projectObj.project.FeeRate.checkFeeRateName(newName,callback)
        }else {
            feeRateObject.submitSaveAs(newName);
        }
    },
    submitSaveAs:function (newName) {
        this.activateFeeRate =  projectObj.project.FeeRate.feeRateFileSaveAs(newName);
        feeRateObject.loadPageContent();
        $('#copy-lv').modal('hide');
    },
    getChangeInfo:function () {
        var me = this;
        var callback=function (data) {
            me.changeInfo=data;
            me.loadChangePageContent(data);
            console.log(data);
        };
        projectObj.project.FeeRate.getChangeInfo(callback);
    },
    loadChangePageContent:function (data) {
        $('#currentProject').text(data.currentProject.name);
        $('#currentOptions').empty();
        _.forEach(data.currentProject.currentOptions,function (s) {
            var option =  $("<option>").val(s.ID).text(s.name);
            $('#currentOptions').append(option);
        })
        $('#currentOptions').val(projectObj.project.FeeRate.getActivateFeeRateID());
        $('#otherProject').empty();
        _.forEach(data.others,function (p) {
            var option =  $("<option>").val(p.ID).text(p.name);
            $('#otherProject').append(option);
        });
        $('#otherFeeRateOption').empty();
        if(data.others.length>0){
            _.forEach(data.others[0].optionList,function (f) {
                var option =  $("<option>").val(f.ID).text(f.name);
                $('#otherFeeRateOption').append(option);
            });
        }
    },
    changeFeeRateFileFromCurrent:function(){
        var newVal = $("#currentOptions").val();
        if($("#currentOptions").val()==this.activateFeeRate.ID){
            return;
        }
        var name =$("#currentOptions").find("option:selected").text();
        var newFeeRateFile = {
            id:newVal,
            name:name
        }
        var callback=function () {
            feeRateObject.createSpreadView();
            feeRateObject.loadPageContent();
            projectObj.project.FeeRate.synchronizeFeeRate();
        }
        projectObj.project.FeeRate.changeFeeRateFileFromCurrent(newFeeRateFile,callback);
    },
    changeFeeRateFileFromOthers:function () {
        var feeRateFileID = $("#otherFeeRateOption").val();
        var name =$("#otherFeeRateOption").find("option:selected").text();
        if(null===feeRateFileID){
            alert("请选择一个费率文件！");
            return;
        }
        var currentOption = _.find(this.changeInfo.currentProject.currentOptions,{name:name})
        if(currentOption){
            $("#rename-lv").modal({show:true});
            $("#newFeeRateID").val(feeRateFileID);
            $("#newFeeRateName").val(name);
        }else {
            this.changeFeeRateFileConfirm(feeRateFileID,name);
        }
    },
    changeFeeRateFileConfirm:function(feeRateFileID,name){
        var callback=function () {
            feeRateObject.createSpreadView();
            feeRateObject.loadPageContent();
            projectObj.project.FeeRate.synchronizeFeeRate();
        }
        projectObj.project.FeeRate.changeFeeRateFileFromOthers(feeRateFileID,name,callback);
    }
}

function getPopoverContent() {
    var feeRateFile = projectObj.project.FeeRate.getActivateFeeRate();
    var usageProjects = feeRateFile.usageProjects;
    var popover_content = "";
    _.forEach(usageProjects,function (p,index) {
        if(index>0){
            popover_content+='<br>';
        }
        popover_content+=p.name;
    })
    return popover_content;
}

$('#pop-lv').popover({
        placement:"bottom",
        html:true,
        trigger:"hover | focus",
        content:getPopoverContent
    }
);

$('#tab_fee_rate').on('shown.bs.tab', function (e) {
    feeRateObject.reFreshRateViews();
    feeRateObject.loadPageContent();
});

$('#setNewFeeRate').bind('click', function () {
    var feeRateFile = projectObj.project.FeeRate.getActivateFeeRate();
    var usageProjects = feeRateFile.usageProjects;
    var listString ='';
    _.forEach(usageProjects,function (u) {
        listString+="<li>"+u.name+"</li>"
    })
    $("#usageProjectList").html(listString);
    $("#set-lv-feeRateName").text(feeRateFile.name);
    $("#set-use-feeRateName").text(feeRateFile.name);

    feeRateObject.getFeeRateStandards(function (data) {
        $('#standardSelect').empty();
        _.forEach(data,function (s) {
            var option =  $("<option>").val(s.ID).text(s.libName);
            $('#standardSelect').append(option);
        })
        $('#standardSelect').val(feeRateFile.libID);
    });
});
$('#changeConfirm').bind('click', function (){
    var newVal=$('#standardSelect').val();
    var feeRateFile = projectObj.project.FeeRate.getActivateFeeRate();
    if(newVal&&newVal!=feeRateFile.libID){
        feeRateObject.changeFeeRateStandard(newVal);
    }
});

$('#saveAs').bind('click', function (){
    var feeRateFile = projectObj.project.FeeRate.getActivateFeeRate();
    $('#copyFeeRateName').val(feeRateFile.name+'副本');
    $('#valid_name').val(feeRateFile.name+'副本');
    $('#nameError').hide();
});

$('#saveAsConfirm').bind('click',function () {
    feeRateObject.feeRateFileSaveAs($('#copyFeeRateName').val());
})


$('#copyFeeRateName').change(function () {
    feeRateObject.checkFeeRateName(this.value);
});

$('#newFeeRateName').change(function () {
    var newName = $(this).val();
    if(!newName||newName==""){
        $('#renameConfirm').attr("disabled","disabled");
        $('#renameError').text("请输入文件名称。").show();
        return;
    }
    var callback=function (data) {
        if(data){
            $('#renameConfirm').attr("disabled","disabled");
            $('#renameError').text("本建设项目中已存在同名费率文件。").show();
        }else {
            $('#renameConfirm').removeAttr("disabled");
            $('#renameError').hide();
        }
    };
    projectObj.project.FeeRate.checkFeeRateName(newName,callback);
});


function changeFRadioClick() {
    var radioV= $("input[name='chaneg-lv-Radio']:checked").val();
    if(radioV==='0'){
        $("#fromProject").show();
        $("#fromOther").hide();
    }else {
        $("#fromProject").hide();
        $("#fromOther").show();
    }
}
$('#changeFeeRateConfirm').bind('click',function (){
    var radioV= $("input[name='chaneg-lv-Radio']:checked").val();
    if(radioV==='0'){
        feeRateObject.changeFeeRateFileFromCurrent();
    }else {
        feeRateObject.changeFeeRateFileFromOthers();
    }
})

$('#changFeeRateFile').bind('click',function (){
    $("input[name='chaneg-lv-Radio']")[0].checked=true;
    $("#fromProject").show();
    $("#fromOther").hide();
    feeRateObject.getChangeInfo();
})

$('#otherProject').change(function(){
    var newVal = $(this).val();
    var projects = feeRateObject.changeInfo.others;
    var selected = _.find(projects,{ID:parseInt(newVal)});
    $('#otherFeeRateOption').empty();
    _.forEach(selected.optionList,function (f) {
        var option =  $("<option>").val(f.ID).text(f.name);
        $('#otherFeeRateOption').append(option);
    });
})

$('#renameConfirm').bind('click',function (){
    var feeRateFileID= $("#newFeeRateID").val();
    var name = $("#newFeeRateName").val();
    feeRateObject.changeFeeRateFileConfirm(feeRateFileID,name);
})


$('#inlineFormCustomSelect').change(function(){
    var updateTask = [];
    var selectID = $(this).val();
    var oldValue=0;
    _.forEach(projectObj.project.FeeRate.datas,function (feeRate) {
        if(feeRate.status=='activate'){
            oldValue=feeRate.ID;
        }
        if(feeRate.ID ==selectID){
            feeRate.status='activate';
        }else {
            feeRate.status='disable';
        }
        updateTask.push({query:{ID:feeRate.feeRateID},doc:{status:feeRate.status}});
    })
    projectObj.project.FeeRate.updateStatusBySelected(updateTask);
    feeRateObject.createSpreadView();
    subRateObject.destorySpreadView();
    socket.emit('changeActivateFeeRate',{oldRoom:oldValue,newRoom:selectID});
})

