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

var subRateObject={
    views:null,
    datas:null,
    timeStamp:null,
    valueMap:null,
    canEdit:true,
    subRateSpread:null,
    subRateSheet:null,
    subRateSetting:{
        header: [
            {headerName: "参数名称", headerWidth: 160, dataCode: "name", dataType: "String"},
            {headerName: "参数值", headerWidth: 150, dataCode: "optionValue", dataType: "String",getText:'forOption'}
        ],
        view: {
            lockColumns: [0]
        },
        getText:{
            forOption:function (item,val) {
                if(item.isSub == true) return item.value;//可编辑子节点
                let o = _.find(item.optionList,{'selected':true});
                if(gljUtil.isDef(o)){
                    return o.name;
                }else {
                    if(item.editable==true) return item.value;
                }
            }
        }
    },
    options :{
        allowSorting: false,
        showRowHeader: true,
        colMinWidth: 80,
        rowHeight: 33,
        allowEditing: this.canEdit,
        editMode: 'inline',
        editUnit: 'cell',
        selectionUnit:(this.canEdit == true) ? "cell" : "row"
    },
    initSubRateSpread:function (item) {
        if(this.subRateSpread == null){
            this.subRateSpread = SheetDataHelper.createNewSpread($("#subRate")[0]);
            sheetCommonObj.spreadDefaultStyle(this.subRateSpread);
            this.subRateSheet = this.subRateSpread.getSheet(0);
            sheetCommonObj.initSheet(this.subRateSheet, this.subRateSetting, 30);
            this.subRateSheet.bind(GC.Spread.Sheets.Events.SelectionChanged, this.onSubRateSelectChanged);
            this.subRateSheet.bind(GC.Spread.Sheets.Events.EditStarting,this.onSubRateEditStarting);
            this.subRateSheet.bind(GC.Spread.Sheets.Events.ValueChanged, this.onSubRateValueChange);
            //this.subRateSheet.bind(GC.Spread.Sheets.Events.ValueChanged, me.onSheetValueChange);
            this.subRateSheet.name('subRateSheet');
        }
        //subRateObject.valueMap=projectObj.project.FeeRate.getValueMap(item);
        subRateObject.showSubRateData();
        if(projectReadOnly){
            if(this.subRateSetting.view.lockColumns){
                this.subRateSetting.view.lockColumns = null;
            }
            sheetCommonObj.disableSpread(this.subRateSpread);
            disableRightMenu("subRate",this.subRateSpread);
        }else {
            this.initRightClick("subRate",this.subRateSpread)
        }
    },
    showSubRateData:function () {
        let preSelections = this.subRateSheet.getSelections();
        this.datas = projectObj.project.FeeRate.getAllSubRates();
        this.subRateSheet.setRowCount(0);
        sheetCommonObj.showData(this.subRateSheet, this.subRateSetting, this.datas);
        this.subRateSheet.setRowCount(this.datas.length);
        let parentMap=_.groupBy(this.datas, 'ParentID');
        let visibleMap = {};
        this.subRateSheet.suspendPaint();
        this.subRateSheet.suspendEvent();
        for(let row =0; row < this.datas.length;row++){
            this.setComboOptionCell(row,1,this.datas[row],this.subRateSheet,this.datas[row].name);
            this.setTreeNodeCellType(this.datas,row,parentMap,visibleMap,this.subRateSheet);
        }
        this.subRateSheet.resumeEvent();
        this.subRateSheet.resumePaint();
        if(preSelections){//定位光标到之前的位置
            this.subRateSheet.setSelection(preSelections[0].row,preSelections[0].col,preSelections[0].rowCount,preSelections[0].colCount);
        }
    },
    onSubRateSelectChanged:function (e,info) {
        info.sheet.repaint();
    },
    getAreaTips:function(name){
        let field = name === "冬季施工"?"temperatureArea":"rainfallArea";
        let location = feeRateObject.getLocation();
        let area = feeRateAreaMap[location];
        return area && area[field]? area[field]:null;
    },
    setTreeNodeCellType:function (datas,row,parentMap,visibleMap,sheet) {
        delete parentMap.undefined;//去掉无用节点
        let treeNode = null;
        if(datas[row].name == "冬季施工" || datas[row].name == "雨季施工"){
            treeNode = sheetCommonObj.getTreeNodeCellType(datas,row,parentMap,null,null,this.getAreaTips(datas[row].name));
        }else{
            treeNode = sheetCommonObj.getTreeNodeCellType(datas,row,parentMap);
        }
        treeNode.treeNodeType = false;
        if((datas[row].subList &&　datas[row].subList.length >0)||datas[row].isSub == true　){
            treeNode.treeNodeType = true;
            visibleMap[datas[row].ID] = treeNode.collapsed;
        }
        sheet.setCellType(row, 0, treeNode, GC.Spread.Sheets.SheetArea.viewport);
        if(visibleMap[datas[row].ParentID]) sheet.getRange(row , -1, 1, -1).visible(!visibleMap[datas[row].ParentID]);//显示或隐藏
    },
    setComboOptionCell:function(row,col,subRate,sheet,name){
        let options=[];
        if(subRate.isSub == true) return;//是树节点的子节点;
        for(let op of subRate.optionList){
           options.push(op.name);
        }
        let dynamicCombo =null;
        if(name == "冬季施工" || name == "雨季施工"){
            let tips = this.getAreaTips(name)
            dynamicCombo = sheetCommonObj.getTipsCombo(true, tips, {})
        }else{
            dynamicCombo = sheetCommonObj.getDynamicCombo();//new GC.Spread.Sheets.CellTypes.ComboBox();
        }
         
        dynamicCombo.items(options);
        if(subRate.editable == true) dynamicCombo.editable(true);
        sheet.setCellType(row, col, dynamicCombo, GC.Spread.Sheets.SheetArea.viewport);
    },
    addComboboxOption:function (datas) {
        _.forEach(datas,function (item) {
            var selectvalue = 0;
            _.forEach(item.optionList,function (o) {
                var option =  $("<option>").val(o.value).text(o.name);
                $('#'+item.ID).append(option);
                if(o.selected){
                    selectvalue = o.value;
                }
            })
            $('#'+item.ID).val(selectvalue);
        })
    },
    onSubRateEditStarting :function(e,info){
        if($.bootstrapLoading.isLoading())  info.cancel = true;
    },

    onSubRateValueChange:function (e,info,feeRateCoe) {
        let me = subRateObject, subList=null;
        let value = info.newValue;
        let subRate = me.datas[info.row];
        if(subRate.editable == true || subRate.isSub == true){//是可编辑的，要检查数据类型
            let checkResult = scMathUtil.isNumOrFormula(value);
            if(checkResult!=null && !isNaN(checkResult)){
                value = scMathUtil.roundForObj(checkResult,getDecimal("feeRate"));
            }else {
                alert('当前输入的数据类型不正确，请重新输入。');
                return me.showSubRateData();
            }
        }
        if(subRate.isSub == true){//是树节点的子节点,计算父节点的值
            let parentRate = _.find(me.datas,{"ID":subRate.ParentID});//找到父节点
            if(parentRate){
                let sum = 0;
                subList = _.cloneDeep(parentRate.subList);
                for(let s of subList){//按比例计算
                    if(s.ID == subRate.ID) s.value = value;//当前项要用新输入的值
                    let v_a = scMathUtil.roundForObj(s.value * s.amount,getDecimal("process"))
                    sum = scMathUtil.roundForObj(sum + v_a,getDecimal("feeRate"));
                }
                value = sum;
                subRate = parentRate;//把subRate 指向parentRate
            }
        } else if(subRate.subList && subRate.subList.length > 0){//输入树节结的父结点，子结点都等于父节点的值
            subList = _.cloneDeep(subRate.subList);
            for(let t of subList){
                t.value = value
            }
        }
        if(me.timeStamp = null){
            me.timeStamp =  +new Date()
            feeRateObject.setRateFromSub(subRate,value,subList,info.newValue,feeRateCoe);
        }else {
            let now = +new Date();
            if(now - me.timeStamp < 500){
                setTimeout(function () {
                    feeRateObject.setRateFromSub(subRate,value,subList,info.newValue,feeRateCoe);
                },500)
            }else {
                feeRateObject.setRateFromSub(subRate,value,subList,info.newValue,feeRateCoe);
            }
            me.timeStamp = now;
        }
    },

    destorySpreadView:function () {
        if(this.views){
            this.views.destroy();
            this.views = null;
        }
        subRateObject.datas=null;
        subRateObject.valueMap=null;
    },
    initRightClick:function (id,spread) {
        let me = this;
        $.contextMenu({
            selector: '#'+id,
            build: function ($trigger, e) {
                me.rightClickTarget = SheetDataHelper.safeRightClickSelection($trigger, e, spread);
                return me.rightClickTarget.hitTestType === GC.Spread.Sheets.SheetArea.viewport ||
                    me.rightClickTarget.hitTestType === GC.Spread.Sheets.SheetArea.rowHeader;
            },
            items: {
                "widthCoe":{
                    name: "乘系数",
                    icon: 'fa-sign-in',
                    visible:function () {
                        return true;//2019-11-17 改成不需要右键插入功能    id == "freightSheet";
                    },
                    disabled: function (){
                        let subRate = subRateObject.datas[me.rightClickTarget.row];
                        if(subRate && subRate.isSub) return true;
                        return me.rightClickTarget.row === undefined;
                    },
                    callback:function () {
                        $("#width_coe_value").val(1);
                        $("#widthCoeDiv").modal("show");
                    }

                }
            }
        });
    }
};

$(function(){
    $("#widthCoeDivConfirm").click(function () {
        let feeRateCoe = $("#width_coe_value").val();
        if(!number_util.isNum(feeRateCoe)){
            alert("乘系数类型不对，请重新输入!");
            return ;
        }
        feeRateCoe = scMathUtil.roundForObj(feeRateCoe,getDecimal("feeRate"));
        let sub = subRateObject.subRateSheet.getSelections()[0];
        let value =subRateObject.subRateSheet.getCell(sub.row,1).value();
        let info = {col:1,row:sub.row,newValue:value,oldValue:value};
        subRateObject.onSubRateValueChange({},info,feeRateCoe);
        $("#widthCoeDiv").modal("hide");
    })
});
