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



var feeRateObject={
    mainFeeRateSpread:null,
    mainFeeRateSheet:null,
    mainFeeRateData:null,
    mainFeeRateSetting:{
        header: [
            {headerName: "专业名称", headerWidth: 250, dataCode: "name", dataType: "String"},
            {headerName: "值%", headerWidth: 80, dataCode: "rate", dataType: "Number",hAlign: "right",decimalField:"feeRate"},
            {headerName: "备注", headerWidth: 150, dataCode: "memo", dataType: "String", showHint: true}
        ],
        view: {
            lockColumns: [0]
        }
    },
    mainViews:null,
    datas:null,
    datasBackup:null,
    canEdit:false,
    activateFeeRate:null,
    needCascadeSet:false,
    selectionLoad:false,
    changeInfo:null,
    feeRateSpreads:null,
    editingCell:null,
    feeRateSelection:null,
    sheetSetting: {
        header: [
            {headerName: "专业名称", headerWidth: 200, dataCode: "name", dataType: "String"},
            {headerName: "值%", headerWidth: 120, dataCode: "rate", dataType: "Number",hAlign: "right",decimalField:"feeRate"},
            {headerName: "备注", dataCode: "memo", dataType: "String", showHint: true}
        ],
        view: {
            comboBox: [],
            lockColumns: [0, 1, 2]
        }
    },
    columns: [
        {
            id: 'name',
            caption: '专业名称',
            dataField: 'name',
            width: 450,
            allowEditing: false
        },
        {
            id: 'rate',
            caption: '值%',
            dataField: 'rate',
            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;
            }
            params.success();
            if(!$('#cascadeSet').prop('checked')||params.hasOwnProperty('viewIndex')){
                projectObj.project.FeeRate.updateFeeRateByEdit(params,feeRateObject.activateFeeRate);
            }
        }
    },
    createSheet:function(){
        var feeRateFile = projectObj.project.FeeRate.getActivateFeeRate();
        feeRateObject.feeRateSpreads=sheetCommonObj.buildSheet($('#fee_rate_sheet')[0], feeRateObject.sheetSetting,feeRateFile.rates.length);
        sheetCommonObj.spreadDefaultStyle(feeRateObject.feeRateSpreads);
        feeRateObject.feeRateSheet = feeRateObject.feeRateSpreads.getSheet(0);
        feeRateObject.feeRateSheet.selectionUnit(1)//0 cell,1 row,2 col;
        feeRateObject.feeRateSheet.options.isProtected = true;
        feeRateObject.feeRateSheet.name('fee_rate');
        feeRateObject.feeRateSheet.bind(GC.Spread.Sheets.Events.CellClick,feeRateObject.onCellClick);
        feeRateObject.feeRateSheet.bind(GC.Spread.Sheets.Events.CellDoubleClick,feeRateObject.onCellDoubleClick);
    },
    showFeeRateTree:function (sheet,setting,data) {

        let ch = GC.Spread.Sheets.SheetArea.viewport;
        let parentMap=_.groupBy(data, 'ParentID');
        let visibleMap = {};
        sheet.suspendPaint();
        sheet.suspendEvent();
        sheet.setRowCount(data.length);
        for (let col = 0; col < setting.header.length; col++) {
            let hAlign = "left", vAlign = "center";
            if (setting.header[col].hAlign) {
                hAlign = setting.header[col].hAlign;
            } else if (setting.header[col].dataType !== "String"){
                hAlign = "right";
            }
            vAlign = setting.header[col].vAlign?setting.header[col].vAlign:vAlign;
            sheetCommonObj.setAreaAlign(sheet.getRange(-1, col, -1, 1), hAlign, vAlign);
            if (setting.header[col].formatter) {
                sheet.setFormatter(-1, col, setting.header[col].formatter, GC.Spread.Sheets.SheetArea.viewport);
            }
            if (setting.header[col].showHint) {
                sheet.getRange(-1, col, -1, 1).cellType(TREE_SHEET_HELPER.getTipCellType(setting));
            }
            for (let row = 0; row < data.length; row++) {
                let val = data[row][setting.header[col].dataCode];
                if(val&&setting.header[col].dataType === "Number"){
                    if(setting.header[col].hasOwnProperty('decimalField')){
                        let decimal = getDecimal(setting.header[col].decimalField);
                        val =scMathUtil.roundToString(val,decimal);
                        sheet.setFormatter(-1, col,getFormatter(decimal), GC.Spread.Sheets.SheetArea.viewport);
                    }else {
                        val =scMathUtil.roundToString(val,2);
                    }
                }
                sheet.setValue(row, col, val, ch);
                if(col==0){
                    let treeType = sheetCommonObj.getTreeNodeCellType(data,row,parentMap);
                    sheet.getCell(row, 0).cellType(treeType);
                    visibleMap[data[row].ID] = treeType.collapsed;
                    feeRateObject.setRowVisible(data,row,visibleMap,sheet);
                } else if (col === 1 && this.rateShouldMark(data[row], val)) {
                    sheet.getCell(row, col).foreColor('red');
                }
            }
        }
        sheet.resumeEvent();
        sheet.resumePaint();
    },
    rateShouldMark: function (rateItem, val) {
        if (!rateItem) {
            return false;
        }
        if (rateItem.rate === null) {
            return false;
        }
        if (rateItem.sum) {
            return false;
        }
        if (rateItem.subFeeRate) {
            const selectedSubRate = rateItem.subFeeRate.recodes && rateItem.subFeeRate.recodes[0] ?
                rateItem.subFeeRate.recodes[0].optionList.find(item => item.selected)
                : null;
            if (!selectedSubRate) {
               return false;
            }
            const valInMap = rateItem.subFeeRate.valueMaps.find(item => item.ID === selectedSubRate.name);
            return !!(valInMap && valInMap.value !== +val);
        } else {
            return commonUtil.isDef(rateItem.originalRate) && rateItem.originalRate !== +val;
        }
    },
    setRowVisible:function (data,row,visibleMap,sheet) {
        sheet.getRange(row , -1, 1, -1).visible(getVisible(data[row].ParentID));//显示或隐藏
        function getVisible(ParentID) {
            if(visibleMap[ParentID]) return false //如果父节点是缩起的，那就隐藏本身。
            if(visibleMap[ParentID] == false){//如果父节点不是缩起的，要再往父节点找看
                let pnode = _.find(data,{'ID':ParentID});
                if(pnode) return getVisible(pnode.ParentID);//如果有父节点，递归调用
                return true;//没有，返回显示
            }
        }
    },
    getFeeRateLevel:function (rate,data) {
        if(rate.ParentID){
         let prate =  _.find(data,{'ID':rate.ParentID});
         return  this.getFeeRateLevel(prate,data) + 1;
        }else {
            return 0
        }
    },
    initFeeRateEditDiv:function(optionValue){//“0” 手工输入; “1” 选择费率
        let radioValue = optionValue,feeRateValue;
        if(!gljUtil.isDef(optionValue)){
            let fID = 0;
            if ($("#calc_program_manage").is(":visible")){
                fID = calcProgramManage.getSelectionInfo().calcItem.feeRateID;
                feeRateValue = calcProgramManage.getSelectionInfo().calcItem.feeRate;
            } else if ($("#zaojiashu").is(":visible")){
                fID = projectObj.project.mainTree.selected.data.feeRateID;
                feeRateValue = projectObj.project.mainTree.selected.data.feeRate;
            }
            radioValue = fID?"1":"0";
            $("#customFeeRate").val(feeRateValue);
        }
        $("input[name='editFeeRateOptions'][value='"+radioValue+"']").attr("checked",true);
        if(radioValue == "0"){
            $("#selfDiv").show();
            $("#fee_rate_sheet").hide();
        }else {
            $("#selfDiv").hide();
            $("#fee_rate_sheet").show();
        }
    },
    locate: function(){   // CSL,2018.07.18
        let sheet = feeRateObject.feeRateSpreads.getSheet(0);
        let fID = 0;
        if ($("#calc_program_manage").is(":visible"))
           fID = calcProgramManage.getSelectionInfo().calcItem.feeRateID;
        else if ($("#zaojiashu").is(":visible"))
           fID = projectObj.project.mainTree.selected.data.feeRateID;
        let rates = projectObj.project.FeeRate.getActivateFeeRate().rates;
        let rowIdx = 0, pID = 0;
        if (fID){
            fID = parseInt(fID);
            rowIdx = _.findIndex(rates,{ID:fID});
            if(rowIdx != -1) pID = rates[rowIdx].ParentID;
        }
        // 费率现有可能有多层节点，所以要递归展开父节点
        if(pID) expandParent(pID,rates,sheet);
        sheet.setSelection(rowIdx, -1, 1, -1);
        sheet.showRow(rowIdx, GC.Spread.Sheets.VerticalPosition.center);
        feeRateObject.onCellClick({type: 'CellClick'}, {row:rowIdx});
        
        function expandParent(ID,datas,sheet) {//递归展开父节点
             let cellType = setCollapsed(ID);
             cellType.refreshChildrenVisible(sheet);
            function setCollapsed(parentID){
                let index = _.findIndex(datas,{'ID':parentID});
                let type = sheet.getCellType(index,0);
                type.collapsed = false;
                if(datas[index].ParentID){
                    setCollapsed(datas[index].ParentID)
                }
                return type
            }

        }
    },
    getFeeRateEditCellType:function () {
        var ns = GC.Spread.Sheets;
        function FeeRateEditCellType() {
            var init=false;
        }
        FeeRateEditCellType.prototype = new ns.CellTypes.Text();
        //2018-12-12 按新需求隐藏费率选择按钮
      /*  FeeRateEditCellType.prototype.paint = function (ctx, value, x, y, w, h, style, options) {
             GC.Spread.Sheets.CellTypes.Text.prototype.paint.apply(this, arguments);
            if(feeRateObject.editingCell && !projectReadOnly){
                if(feeRateObject.editingCell.row==options.row&&feeRateObject.editingCell.col==options.col){
                    var image = document.getElementById('f_btn'),imageMagin = 3;
                    var imageHeight = h-2*imageMagin;
                    var imageWidth = w*2/7;
                    var imageX = x + w - imageWidth- imageMagin, imageY = y + h / 2 - imageHeight / 2;
                    ctx.save();
                    ctx.drawImage(image, imageX, imageY,imageWidth,imageHeight);
                    ctx.beginPath();
                    ctx.arc(imageX+imageWidth/2,imageY+imageHeight/2,1,0,360,false);
                    ctx.arc(imageX+imageWidth/2-4,imageY+imageHeight/2,1,0,360,false);
                    ctx.arc(imageX+imageWidth/2+4,imageY+imageHeight/2,1,0,360,false);
                    ctx.fillStyle="black";//填充颜色,默认是黑色
                    ctx.fill();//画实心圆
                    ctx.closePath();
                    ctx.restore();
                }
            }
        };
        FeeRateEditCellType.prototype.getHitInfo = function (x, y, cellStyle, cellRect, context) {
            return {
                x: x,
                y: y,
                row: context.row,
                col: context.col,
                cellStyle: cellStyle,
                cellRect: cellRect,
                sheetArea: context.sheetArea
            };
        };
        FeeRateEditCellType.prototype.processMouseDown = function (hitinfo) {
            let me=feeRateObject;
            if(me.editingCell && hitinfo.row==me.editingCell.row){
                var offset=hitinfo.cellRect.x+hitinfo.cellRect.width-6;
                var imageMagin=3;
                var imageHeight = hitinfo.cellRect.height-2*imageMagin;
                var imageWidth = hitinfo.cellRect.width*2/7;
                if(hitinfo.x<offset&&hitinfo.x>offset-imageWidth){
                    if(!projectReadOnly && me.ifFeeRateEdit(hitinfo.row,hitinfo.sheet.name())){
                        $('#calcBaseFeeRateConf').attr('toggle', 'feeRate');
                        changeCalcBaseFeeRate('feeRate');
                        $('#tabFeeRate').tab('show');
                        me.showSelectModal(hitinfo);
                    }
                }else {//鼠标点击其它地方，消失
                    hideButton(hitinfo);
                }
            }
        };
        FeeRateEditCellType.prototype.processMouseEnter = function (hitinfo){
            let me=feeRateObject;
            me.pmLeave = false;
            if(me.editingCell==null){
                var showSelectBtn = true;
                if(hitinfo.sheet.name()!='calc_detail'){
                    showSelectBtn=me.ifFeeRateEdit(hitinfo.row,hitinfo.sheet.name());
                }
                if(showSelectBtn){
                    me.editingCell={
                        row:hitinfo.row,
                        col:hitinfo.col
                    };
                    hitinfo.sheet.invalidateLayout();
                    hitinfo.sheet.repaint();
                }
            }
        };
        FeeRateEditCellType.prototype.processMouseLeave = function (hitinfo) {
            hideButton(hitinfo);
        };

        function hideButton(hitinfo) {
            if(!feeRateObject.pmLeave){
                feeRateObject.editingCell=null;
                hitinfo.sheet.invalidateLayout();
                hitinfo.sheet.repaint();
                feeRateObject.pmLeave = true;
            }
        }*/
        return new FeeRateEditCellType();
    },
    showSelectModal:function (hitinfo) {
        //锁定的清单不显示
        let project = projectObj.project;
        if(project.isBillsLocked() && project.withinBillsLocked(project.mainTree.selected)){
            return;
        }
        //$("#fee_rate_tree").modal({show:true});
        $("#calcBaseFeeRate").modal({show:true});
        $('#edit_from').val(hitinfo.sheet.name());
    },
    getChildrenCount:function (id,data) {
        var me=this;
        var sum=0;
        var children=_.filter(data,{'ParentID':id});
        if(children&&children.length==0){
            return 0;
        }
        for(var i=0;i<children.length;i++){
            sum+=me.getChildrenCount(children[i].ID,data);
        }
        return children.length+sum;
    },
    ifFeeRateEdit:function (row,name) {
        if( name == 'mainSheet'){
            var selected = projectObj.project.mainTree.items[row];
            return selected&&MainTreeCol.readOnly.forFeeRate(selected)?false:true;
        }
        return true;
    },
    createSpreadView:function () {
        if (this.mainViews) {
            this.mainViews.destroy();
            this.mainViews = null;
        }
        if(subRateObject.views){
            subRateObject.views.destroy();
            subRateObject.views = null;
        }
        this.activateFeeRate = projectObj.project.FeeRate.getActivateFeeRate();
        this.datas = this.activateFeeRate.rates;
        var rateColSetting = _.find(this.columns,{"id":"rate"});
        rateColSetting?rateColSetting.format=getFormatter(getDecimal("feeRate")):"";
        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();
    },
    initFeeRateSpread:function (rowCount) {
        //初始化费用项表格
        this.mainFeeRateSpread = sheetCommonObj.buildSheet($('#divFee')[0], this.mainFeeRateSetting,rowCount);
        sheetCommonObj.spreadDefaultStyle(this.mainFeeRateSpread);
        this.mainFeeRateSpread.options.scrollbarMaxAlign = true;
        this.mainFeeRateSheet = this.mainFeeRateSpread.getSheet(0);
        if(!projectReadOnly){
            sheetCommonObj.lockCells(this.mainFeeRateSheet , this.mainFeeRateSetting);
        }
        this.mainFeeRateSheet.bind(GC.Spread.Sheets.Events.ValueChanged, this.onMainFeeRateSheetValueChange);
        //this.mainFeeRateSheet.bind(GC.Spread.Sheets.Events.SelectionChanged, this.onMainFeeRateSelectChanged);
        this.mainFeeRateSheet.bind(GC.Spread.Sheets.Events.RangeChanged, this.onMainFeeRateRangeChanged);
        this.mainFeeRateSheet.bind(GC.Spread.Sheets.Events.EditStarting, function (e,args) {
            let me =feeRateObject;
            if($.bootstrapLoading.isLoading())  args.cancel = true;
            if(!me.mainFeeRateEditChecking(args.row,args.col)){
                args.cancel = true;
            }
        });
        this.mainFeeRateSheet.name('mainFeeRateSheet');
        disableRightMenu("divFee",this.mainFeeRateSpread,this.rightClickCallback);
        //打开他人分享的项目、只读
        if(projectReadOnly){
            disableSpread(this.mainFeeRateSpread);
        }
    },
    rightClickCallback:function (row) {
        let me = feeRateObject;
        me.onMainFeeRateSelect(row);
    },
    showMainFeeRateData:function () {
        let me = this;
        let selected = me.mainFeeRateSheet.getSelections()[0];
        me.activateFeeRate = projectObj.project.FeeRate.getActivateFeeRate();
        me.mainFeeRateData = projectObj.project.FeeRate.getActivateFeeRate().rates;
        me.mainFeeRateSheet.setRowCount(0);
        me.mainFeeRateSheet.setRowCount(me.mainFeeRateData.length);
        me.showFeeRateTree(me.mainFeeRateSheet,me.mainFeeRateSetting,me.mainFeeRateData);
        me.mainFeeRateSheet.setSelection(selected.row,selected.col,selected.rowCount,selected.colCount);
    },
    reFreshRateViews:function() {
        feeRateObject.loadPageContent();
        this.showMainFeeRateData();
        if(subRateObject.subRateSpread){//如果子费率没有初始化过的话，不需要显示。
            subRateObject.initSubRateSpread(this.mainFeeRateData[0]);
        }
    },
    mainFeeRateEditChecking:function (row,col) {//false 不能编辑，true 可以编辑
        let me =feeRateObject;
        let recode = me.mainFeeRateData[row];
        let dataCode = me.mainFeeRateSetting.header[col].dataCode;
        if(dataCode=="rate"&&(recode.sum != true && me.getChildrenCount(recode.ID,me.mainFeeRateData)>0)){//除了标记要汇总的节点，其它的有子节点时不能编辑费率列
            return false;
        }
        return true;
    },

    onMainFeeRateSheetValueChange:function (e,info) {
        feeRateObject.updateFeerateWhenCellsChange([info]);
    },
    onMainFeeRateRangeChanged:function (e,info) {
        let me = feeRateObject;
        let changeCells = [];
        for(let c of info.changedCells){
            let tem = {
                row:c.row,
                col:c.col,
                newValue:info.sheet.getCell(c.row,c.col).value()
            };
            changeCells.push(tem);
        }
        me.updateFeerateWhenCellsChange(changeCells);
    },
    sumParentRate:function (rateID,value,updateDatas) {
        let feeRate = projectObj.project.FeeRate;
        let rate = feeRate.getFeeRateByID(rateID);
        let parent = feeRate.getFeeRateByID(rate.ParentID);
        if(parent && parent.sum == true){
            let suRates = feeRate.getChildrenByID(parent.ID);
            let total = 0;
            for(let r of suRates) {
                let tem = r.rate ? r.rate:0;
                tem = scMathUtil.roundForObj(tem,getDecimal("feeRate"));
                if (rateID == r.ID){
                    tem = value;
                }else {
                    let u = _.find(updateDatas,{"rateID":r.ID})//看是不是更新的过程中包含了汇总的数据
                    if(u && gljUtil.isDef(u.doc.rate)) tem = u.doc.rate;
                }
                total = scMathUtil.roundForObj(tem + total,getDecimal('process'))
            }
            total = scMathUtil.roundForObj(total,getDecimal("feeRate"));
            let tp =  _.find(updateDatas,{"rateID":parent.ID});//如果父节点也在更新列表中
            if(tp){
                tp.doc.rate = total
            }else {
                updateDatas.push({rateID:parent.ID,doc:{rate:total}});
            }
        }

    },
    updateFeerateWhenCellsChange:function (cells) {// col,row,newValue
        let me = feeRateObject,updateDatas = [],feeRate = projectObj.project.FeeRate;//[{rateID:rateID,doc:doc}]
        let refreshA = [];//记录刷新条数的数组
        for(let c of cells){
            let temData = {};
            let recode  = me.mainFeeRateData[c.row];
            let fieldID = me.mainFeeRateSetting.header[c.col].dataCode;
            let value = c.newValue;
            let oldValue = recode[fieldID];
            if(!me.mainFeeRateEditChecking(c.row, c.col)){
                me.mainFeeRateSheet.setValue(c.row, c.col, oldValue);
                continue;
            }else if(fieldID == 'rate'&&value !== null && value!==0){
                let checkResult = scMathUtil.isNumOrFormula(value);
                if(checkResult!=null && !isNaN(checkResult)){
                    value = scMathUtil.roundForObj(checkResult,getDecimal("feeRate"));
                }else {
                    alert('当前输入的数据类型不正确，请重新输入。');
                    me.mainFeeRateSheet.setValue(c.row, c.col, oldValue);
                    continue;
                }
            }
            if(recode[fieldID] == value){//没有改变
                continue;
            }
            temData[fieldID] = value ;
            updateDatas.push({rateID:recode.ID,doc:temData});
            if(fieldID == 'rate') feeRateObject.sumParentRate(recode.ID,value,updateDatas);
        }
        if(updateDatas.length > 0){
            $.bootstrapLoading.start();
            feeRate.updateFeeRatesByIDs(updateDatas,async function () {
                let feerateInfo = [];
                for(let u of updateDatas){
                    let row = _.findIndex(me.mainFeeRateData,{'ID':u.rateID});
                    let rateItem = me.mainFeeRateData[row];
                    for(let key in u.doc){
                        let col = _.findIndex(me.mainFeeRateSetting.header,{'dataCode':key});
                        me.mainFeeRateSheet.setValue(row, col, u.doc[key]);
                        if(key == 'rate'){
                            const foreColor = feeRateObject.rateShouldMark(rateItem, u.doc[key]) ? 'red' : 'black';
                            me.mainFeeRateSheet.getCell(row, col).foreColor(foreColor);
                            feerateInfo.push({rateID:u.rateID,value:u.doc[key]});
                        }
                    }
                }
                feerateInfo.length > 0 ?await feeRate.onFeeRatesChange(feerateInfo):'';
                $.bootstrapLoading.end();
            })
        }
    },
    onMainFeeRateSelectChanged:function (e, info) {
        let me = feeRateObject;
        let row = info.newSelections[0].row;
        me.onMainFeeRateSelect(row);
    },
    onMainFeeRateSelect:function (row) {
        let me = this;
        if(row!=-1){
            subRateObject.initSubRateSpread(me.mainFeeRateData[row]);
        }
    },
    setRateFromSub:function (subRate,value,subList,editText,feeRateCoe) {//editText  下拉框选择的值，对于如“19.00”这样下拉选择项，value会变成19，所以在valueMap里找的时候要用editText去查找
         let me = feeRateObject,feeRate =  projectObj.project.FeeRate;
         let rates = feeRate.getActivateFeeRate().rates;
         let updateDatas = [];
         //对于有子节点的记录和可输入的记录，只支持一个参数(因为还要内插法取费率值)，如果要支持两个以上的参数，valueMap要再改下~~~~
         for(let r of rates){
             if(gljUtil.isDef(r.subFeeRate)){
                 let valueArray=[];//用来存参数的值
                 let temP =null;//这个用来存储需要内插法记算的时候,同时，树节点的子节点改变也计在这里， 这样，改变temP的值，会体现在保存subRecode
                 let match = false;
                 let temR = _.cloneDeep(r);//临时存储
                 for(let p of temR.subFeeRate.recodes){
                     if(p.name == subRate.name){
                         temP = p;
                         match = true;
                     }
                     let setValue = false;
                     for(let o of p.optionList){
                         if(match == true) {//匹配上了，改对应的selected 为 true
                             if(o.name == value){
                                 o.selected = true;
                                 valueArray.push(editText);//这里要用字符串去匹配而不是转换成数值的value
                                 setValue = true;
                             }else {
                                 o.selected = false;
                             }
                         }else {//没有匹配上的，直接取值就可以（这个是为多参数时用的，但是目前来看，不支持多参数，比较麻烦）
                             if(o.selected == true)  valueArray.push(o.name);
                         }
                     }
                     if(match==true && setValue ==false) valueArray.push(value);//如果匹配上了，但是setValue为false,说明没有满足和选项，要用内插法或超出倍数算值
                 }
                 if(match == true){//说明要改rate的值，先从valueMap中去查
                     if(subList && temP.subList && temP.subList.length > 0){
                         temP.subList = subList;// 设置树节点的子节点的值
                     }
                     let doc = {"subFeeRate":temR.subFeeRate};
                     let valueKey = valueArray.join('-');
                     let valueMaps = r.subFeeRate.valueMaps;
                     if(me.feeRateSpecialHandle){//不同编办特殊处理
                         let sf = me.feeRateSpecialHandle(subRate,value);
                         if(!_.isEmpty(sf)){
                             valueKey = sf.valueKey;
                             temP.value = sf.value;
                         }
                     }
                     let rate = _.find(valueMaps,{"ID":valueKey});
                     if(isDef(rate)) {//找到了，直接改费率值
                         doc.rate = rate.value;
                     } else {//没找到，用内插法或步长算值
                         let ltRate = null;//
                         let gtRate = null;
                         temP.value = scMathUtil.roundForObj(value,getDecimal("feeRate")) ;
                         for(let v of valueMaps){
                            if(parseFloat(v.ID)<parseFloat(value)){
                                ltRate = v;
                            }else if( gtRate==null && parseFloat(v.ID)>parseFloat(value)){
                                gtRate = v;
                            }
                         }
                         if(gljUtil.isDef(ltRate)&&gljUtil.isDef(gtRate)){//已经找到前后的值了
                             let step = scMathUtil.roundForObj(gtRate.value - ltRate.value,getDecimal("process"));
                             let total =  parseFloat(gtRate.ID) - parseFloat(ltRate.ID)
                             doc.rate =getRateByStep(ltRate.value,total,parseFloat(value) - parseFloat(ltRate.ID),step);
                         }else if(gljUtil.isDef(ltRate)&&gtRate == null){//说明是超出了选项的最大值
                             let share = parseFloat(value) - parseFloat(ltRate.ID);//超出了多少
                             doc.rate = getRateByStep(ltRate.value,temP.step,share,temP.amount)
                         }else if(gljUtil.isDef(gtRate)&&ltRate==null){//说明是只有一个选项，且这个选项比输入的值大
                             let step =  parseFloat(gtRate.value)- 0;
                             doc.rate = getRateByStep(0,gtRate.value,value,step)
                         }
                     }
                     if(isDef(doc.rate)){
                         if(feeRateCoe) doc.rate = scMathUtil.roundForObj(doc.rate * feeRateCoe,getDecimal("feeRate"));    //如果是从乘系数过来的，乘以系数。
                         updateDatas.push({rateID:r.ID,doc:doc});
                         me.sumParentRate(r.ID,doc.rate,updateDatas);
                     }
                 }
             }
         }
        if(updateDatas.length > 0){
            $.bootstrapLoading.start();
            feeRate.updateFeeRatesByIDs(updateDatas,async function () {
                let feerateInfo = [];
                for(let u of updateDatas){
                    feerateInfo.push({rateID:u.rateID,value:u.doc["rate"]});
                }
                subRateObject.showSubRateData();
                me.showMainFeeRateData();
                if(feerateInfo.length > 0){
                    await feeRate.onFeeRatesChange(feerateInfo);
                }else {
                    $.bootstrapLoading.end();
                }
            })
        }
        function getRateByStep(ltValue,total,share,step) { //min值 ，计算值的总区间， 区间中占比，步长--后端重选标准也要用到
            let p = scMathUtil.roundForObj(share/total,getDecimal("process"));
            let a = scMathUtil.roundForObj(step * p,getDecimal("process")) ;
            return scMathUtil.roundForObj(ltValue + a,getDecimal("feeRate"))
        }



    },


    cascadeSetRates:function(selectedItem,sourceRow,mapID,selectMap){
        let items=[];
        items.push({rateIndex:sourceRow,rate:selectedItem});
        _.forEach(this.mainFeeRateData,function (recode,Index) {
            if(Index!=sourceRow&&recode.subFeeRate){
                let valueMaps = recode.subFeeRate.valueMaps;
                let valueMap = _.find(valueMaps,{ID:mapID});
                if(valueMap){//选项完全一样的情况
                    if(valueMap.value==recode.rate){
                        return;
                    }else {
                        recode.rate = valueMap.value;
                        _.forEach(selectMap,function (value,key) {
                            let tempRecode =  recode.subFeeRate.recodes[key];
                            let optionList = tempRecode.optionList;
                            for(let o of optionList){
                                o.value===value? o.selected = true:o.selected = false;
                            }
                        });
                        items.push({rateIndex:Index,rate:recode});
                    }
                }else {//某条选项一样的情况
                    let needUpdate = false;
                    let selectList = mapID.split('-');
                    let newList=[];
                    _.forEach(recode.subFeeRate.recodes,function (r) {
                        let oList = r.optionList, oldSelectIndex=0, 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){
                      let newValue =   _.find(valueMaps,{ID:newList.join("-")})//取出费率值并更新
                        if(newValue){
                          if(recode.rate != newValue.value){
                              recode.rate = newValue.value;
                              items.push({rateIndex:Index,rate:recode});
                          }
                        }
                    }
                }
            }
        });
        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){
        $.bootstrapLoading.start();
        var callback=function () {
            feeRateObject.reFreshRateViews();
            $.bootstrapLoading.end();
        };
        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();
            }
        };
        projectObj.project.FeeRate.checkFeeRateName(newVal,callback);
    },
    feeRateFileSaveAs:function (newName) {
        if(!newName||newName==""){
           // $('#saveAsConfirm').attr("disabled","disabled");
            $('#nameError').text("请输入文件名称。").show();
            return;
        }
        let 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);
       /* let valideName = $('#valid_name').val();
        if(valideName==''||valideName!==newName){

        }else {
            feeRateObject.submitSaveAs(newName);
        }*/
    },
    submitSaveAs:function (newName) {
        let me = this;
        let FeeRate = projectObj.project.FeeRate;
        FeeRate.feeRateFileSaveAs(newName,function (result) {
            me.activateFeeRate = result;
            me.loadPageContent();
            $('#copy-lv').modal('hide');
            let data ={
                projectID:projectObj.project.ID(),
                oldRoom:socketObject.roomInfo.feeRate,
                newRoom: FeeRate.getActivateFeeRateFileID(),
                userID:userID,
                name:'feeRate'
            };
            socket.emit('changeNewRoom',data);
            socketObject.roomInfo.feeRate = FeeRate.getActivateFeeRateFileID();
            $.bootstrapLoading.end();
        });

    },
    getChangeInfo:function () {
        var me = this;
        var callback=function (data) {
            me.changeInfo=data;
            me.loadChangePageContent(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);
        })
        $('#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(){
        $.bootstrapLoading.start();
        var newVal = $("#currentOptions").val();
        if(!$("#currentOptions").val()){
            if($.bootstrapLoading.isLoading()){
                $.bootstrapLoading.end();
            }
            alert('费率文件不可为空');
            return;
        }
        if($("#currentOptions").val()==this.activateFeeRate.ID){
            return;
        }
        var name =$("#currentOptions").find("option:selected").text();
        var newFeeRateFile = {
            id:newVal,
            name:name
        }
        var callback=function () {
            feeRateObject.reFreshRateViews();
            projectObj.project.FeeRate.onFeeRateFileChange();
            $.bootstrapLoading.end();
        }
        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 callback=function (data) {
            if(data){
                //$('#renameConfirm').attr("disabled","disabled");
                $('#renameError').text("本建设项目中已存在同名费率文件。").show();
                $('#rename-lv').modal('show');
                $("#newFeeRateID").val(feeRateFileID);
                $("#newFeeRateName").val(name);
            }else {
                //$('#renameConfirm').removeAttr("disabled");
                $('#renameError').hide();
                feeRateObject.changeFeeRateFileConfirm(feeRateFileID,name);
            }
        };
        projectObj.project.FeeRate.checkFeeRateName(name,callback);

       /* 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){
        $.bootstrapLoading.start();
        var callback=function () {
            feeRateObject.reFreshRateViews();
            projectObj.project.FeeRate.onFeeRateFileChange();
            $.bootstrapLoading.end();
        }
        projectObj.project.FeeRate.changeFeeRateFileFromOthers(feeRateFileID,name,callback);
    },
    setFeeRateCellCol:function (sheet,col) {
        sheet.getRange(-1, col, -1, 1).cellType(this.getFeeRateEditCellType());
    },
    onCellClick:function (sender,args) {
       var data =projectObj.project.FeeRate.getActivateFeeRate().rates;
       feeRateObject.feeRateSelection=data[args.row];
    },
    onCellDoubleClick:function (sender,args) {
        var data =projectObj.project.FeeRate.getActivateFeeRate().rates;
        feeRateObject.feeRateSelection=data[args.row];
        feeRateObject.submitFeeRateBySelect();
    },
    checkSelectedFeeRate:function () {
        var validate = false;
        var data =projectObj.project.FeeRate.getActivateFeeRate().rates;
        if(feeRateObject.feeRateSelection!=null){
            var children=_.filter(data,{'ParentID':feeRateObject.feeRateSelection.ID});
            validate=children&&children.length==0;
        }
        return validate;
    },
    submitFeeRateFromBill:function () {
       var rate = feeRateObject.feeRateSelection;
       var selected = projectObj.project.mainTree.selected;
       if(selected.data.feeRateID === parseInt(rate.ID)) return $("#calcBaseFeeRate").modal('hide');
        $.bootstrapLoading.start();
        projectObj.project.FeeRate.submitFeeRateFromBill(rate,selected.data,function (data) {
            selected.updateData.feeRateID= parseInt(rate.ID);
            selected.updateData.feeRate=scMathUtil.roundToString(rate.rate,getDecimal("feeRate"));
            selected.changed = true;
            projectObj.project.calcProgram.calcAndSave(selected);
            $("#calcBaseFeeRate").modal('hide');
            $.bootstrapLoading.end();
        });
    },
    submitFeeRateFromCalc:function () {
        var rate = feeRateObject.feeRateSelection;
        var calInfo = calcProgramManage.getSelectionInfo();
        calInfo.calcItem.feeRateID=rate.ID;
        calInfo.calcItem.feeRate=null;
        var data={'projectID': projectObj.project.ID(),'templatesID': calInfo.template.ID,'calcItem': calInfo.calcItem};
        $.bootstrapLoading.start();
        calcProgramManage.saveCalcItem(data,function (result) {
            calInfo.calcItem.feeRate=rate.rate;
            projectObj.project.calcProgram.compileAllTemps();
            projectObj.project.calcProgram.calcAllNodesAndSave();
            calcProgramManage.refreshDetailSheet();
            $("#calcBaseFeeRate").modal('hide');
            $.bootstrapLoading.end();
        });
        console.log(calInfo);
    },
    submitFeeRateBySelect:function () {
        var validate = this.checkSelectedFeeRate();
        if(validate){
            if($('#edit_from').val()=='calc_detail'){
                this.submitFeeRateFromCalc();
            }else {
                this.submitFeeRateFromBill();
            }
        }else {
            //$("#fee_rate_tree").modal('hide');
        }
    }
}

function getPopoverContent() {
    var feeRateFile = projectObj.project.FeeRate.getActivateFeeRate();
    var usageProjects = feeRateFile.usageProjects;
    let names = _.map(usageProjects,'name');
    let popover_content = names.join('<br>');
    return "费率的变化，将自动影响以下单位工程造价：<br>"+ popover_content;
}

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

    $('#tab_fee_rate').on('shown.bs.tab', function (e) {
        sessionStorage.setItem('mainTab', '#tab_fee_rate');
        let me = feeRateObject;
        $(e.relatedTarget.hash).removeClass('active');
        if(me.mainFeeRateSpread == null)  me.initFeeRateSpread(0);
        subRateObject.initSubRateSpread();
        me.showMainFeeRateData();
        me.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();
        feeRateObject.changeFeeRateStandard(newVal);
        //这里改成不判断了，只是点击确定了就重选
        //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);
    });


    $('#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();
        var callback=function (data) {
            if(data){
                $('#renameError').text("已存在同名费率文件。").show();
                $("#newFeeRateID").val(feeRateFileID);
                $("#newFeeRateName").val(name);
            }else {
                $('#renameError').hide();
                $('#rename-lv').modal('hide');
                feeRateObject.changeFeeRateFileConfirm(feeRateFileID,name);
            }
        };
        projectObj.project.FeeRate.checkFeeRateName(name,callback);
    })


    $('#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});
    })

    $('#calcBaseFeeRate').on('shown.bs.modal', function (e) {
        let toggle = $('#calcBaseFeeRateConf').attr('toggle');
        if(feeRateObject.feeRateSpreads==null){
            feeRateObject.createSheet();
        }
        feeRateObject.initFeeRateEditDiv();
        feeRateObject.feeRateSelection=null;
        feeRateObject.showFeeRateTree(feeRateObject.feeRateSheet,feeRateObject.sheetSetting,projectObj.project.FeeRate.getActivateFeeRate().rates);
        feeRateObject.locate();
        feeRateObject.feeRateSpreads.refresh();
    });
    $('#tabFeeRate').on('shown.bs.tab', function () {
        if(feeRateObject.feeRateSpreads){
            feeRateObject.feeRateSpreads.refresh();
        }
    });
    $('#calcBaseFeeRate').on('hidden.bs.modal', function (e) {
        if(feeRateObject.feeRateSpreads){
            feeRateObject.feeRateSpreads.destroy();
            feeRateObject.feeRateSpreads=null;
            $('#edit_from').val('');
            $('#edit_row').val('');
        }
    });
    //fee_selected_conf
    $('#calcBaseFeeRateConf').bind('click',function (){
        let toggle = $(this).attr('toggle');
        if(!toggle || toggle !== 'feeRate'){
            return;
        }
        feeRateObject.submitFeeRateBySelect();
    });
    $("input[name='editFeeRateOptions']").each(function(){
        $(this).click(function(){
            let optins = $(this).val();
            if(optins == "0"){
                $("#selfDiv").show();
                $("#fee_rate_sheet").hide();
            }else {
                $("#selfDiv").hide();
                $("#fee_rate_sheet").show(function () {
                    feeRateObject.feeRateSpreads.refresh();
                });
            }
        });
    });
})
function changeFRadioClick() {
    var radioV= $("input[name='chaneg-lv-Radio']:checked").val();
    if(radioV==='0'){
        $("#fromProject").show();
        $("#fromOther").hide();
    }else {
        $("#fromProject").hide();
        $("#fromOther").show();
    }
}
