/**
 * Created by Zhong on 2018/3/7.
 */
let indicativeInfoObj = {
    feeType: {common: 'common', labour: 'labour', material: 'material', machine: 'machine', mainMaterial: 'mainMaterial', equipment: 'equipment',
        labourDiff: 'labourDiff', materialDiff: 'materialDiff', machineDiff: 'machineDiff', manage: 'manage', profit: 'profit'},
    workBook: null,
    setting:{
        header: [
            {name: '名称', dataCode: 'name', width: 200, vAlign: 'center', hAlign: 'left'},
            {name: '金额', dataCode: 'price', width: 120, vAlign: 'center', hAlign: 'right'},
            {name: '占造价比例(%)', dataCode: 'rate', width: 100, vAlign: 'center', hAlign: 'right'},
            {name: '单方造价', dataCode: 'perCentiare', width: 80, vAlign: 'center', hAlign: 'right'}
        ],
        options: {
            allowContextMenu: false,
            tabStripVisible:  false,
            allowCopyPasteExcelStyle : false,
            allowExtendPasteRange: false,
            allowUserDragDrop : false,
            allowUserDragFill: false,
            scrollbarMaxAlign : true
        }
    },

    renderSheetFuc: function (sheet, fuc) {
        sheet.suspendPaint();
        sheet.suspendEvent();
        fuc();
        sheet.resumePaint();
        sheet.resumeEvent();
    },

    setOptions: function (workbook, opts) {
        for(let opt in opts){
            workbook.options[opt] = opts[opt];
        }
    },

    buildHeader: function (sheet, headers) {
        let me = projFeatureView;
        let fuc = function () {
            sheet.setColumnCount(headers.length);
            sheet.setRowHeight(0, 40, GC.Spread.Sheets.SheetArea.colHeader);
            for(let i = 0, len = headers.length; i < len; i++){
                sheet.setValue(0, i, headers[i].name, GC.Spread.Sheets.SheetArea.colHeader);
                sheet.setColumnWidth(i, headers[i].width, GC.Spread.Sheets.SheetArea.colHeader);
            }
        };
        me.renderSheetFuc(sheet, fuc);
    },

    buildSheet: function () {
        if(!this.workBook){
            this.workBook = new GC.Spread.Sheets.Workbook($('#indicativeInfoSpread')[0], {sheetCount: 1});
            sheetCommonObj.spreadDefaultStyle(this.workBook);
            this.setOptions(this.workBook, this.setting.options);
            this.workBook.getSheet(0).options.isProtected = true;
            this.buildHeader(this.workBook.getActiveSheet(), this.setting.header);
        }
    },
    showData(datas){
        let sheet = this.workBook.getActiveSheet();
        let cols = this.setting.header;
        let fuc = function () {
            sheet.setRowCount(datas.length);
            for(let col = 0, cLen = cols.length; col < cLen; col++){
                //设置小数位数
                if(cols[col]['dataCode'] !== 'name'){
                    sheet.setFormatter(-1, col, MainTreeCol.getNumberFormatter(decimalObj.bills.totalPrice, true));
                }
                sheet.getRange(-1, col, -1, 1, GC.Spread.Sheets.SheetArea.viewport).hAlign(GC.Spread.Sheets.HorizontalAlign[cols[col]['hAlign']]);
                sheet.getRange(-1, col, -1, 1, GC.Spread.Sheets.SheetArea.viewport).vAlign(GC.Spread.Sheets.VerticalAlign[cols[col]['vAlign']]);
                for(let row = 0, rLen = datas.length; row < rLen; row++){
                    sheet.setValue(row, col, datas[row][cols[col]['dataCode']]);
                }
            }
        };
        this.renderSheetFuc(sheet, fuc);
    },
    //是清单
    isBills: function (node) {
        return node && node.sourceType === projectObj.project.Bills.getSourceType();
    },
    //是分部节点
    isFB:function (node) {
        return this.isBills(node) && node.data.type === billType.FB;
    },
    //是大项费用
    isDXFY: function (node) {
        return this.isBills(node) && node.data.type === billType.DXFY;
    },
    //是分部分项工程
    isFBFX: function (node) {
        return this.isDXFY(node) && node.data.flagsIndex && node.data.flagsIndex.fixed && node.data.flagsIndex.fixed.flag === fixedFlag.SUB_ENGINERRING;
    },
    //是措施项目
    isCSXM: function (node) {
        return this.isDXFY(node) && node.data.flagsIndex && node.data.flagsIndex.fixed && node.data.flagsIndex.fixed.flag === fixedFlag.MEASURE;
    },
    //是工程造价
    isEngieeringCost: function (node) {
        return this.isDXFY(node) && node.data.flagsIndex && node.data.flagsIndex.fixed && node.data.flagsIndex.fixed.flag === fixedFlag.ENGINEERINGCOST;
    },
    //存在某个费用
    fee: function (node, feeType) {
        return node && node.data.feesIndex && node.data.feesIndex[feeType] ? node.data.feesIndex[feeType].totalFee : 0;
    },
    //根据固定行ID获取固定行清单节点
    getFixedBill: function (flag) {
        for(let node of projectObj.project.mainTree.items){
            if(node && node.data.flagsIndex && node.data.flagsIndex.fixed && node.data.flagsIndex.fixed.flag === flag){
                return node;
            }
        }
        return null;
    },
    getDXFY: function (node) {
        if(!node) return null;
        let dxfy = Object.create(null);
        let engCostFee = this.fee(this.getFixedBill(fixedFlag.ENGINEERINGCOST), this.feeType.common);
        let commonFee = this.fee(node, this.feeType.common);
        let buildingArea = projFeatureView.getFeature('buildingArea');
        let areaNum = !buildingArea || buildingArea == '' || isNaN(buildingArea) ? 0 : buildingArea;
        dxfy.name = node.data.name;
        dxfy.price = commonFee ? parseFloat(commonFee).toDecimal(decimalObj.bills.totalPrice) : 0;
        dxfy.rate = engCostFee == 0 || this.isEngieeringCost(node) ? '' : parseFloat(dxfy.price/engCostFee*100).toDecimal(2);
        dxfy.perCentiare = areaNum == 0 ? '' : parseFloat(dxfy.price/areaNum).toDecimal(decimalObj.bills.totalPrice);
        return dxfy;
    },
    getIndicativeInfo: function () {
        let rst = [];
        for(let node of projectObj.project.mainTree.items){
            if(this.isDXFY(node)){
                let dxfy = this.getDXFY(node);
                if(!dxfy) continue;
                if(this.isFBFX(node)){
                    rst.push(dxfy);
                    rst.push({name: '其中:', price: '', rate: '', perCentiare: ''});
                    rst.push({name: '       人工费', price: parseFloat(this.fee(node, this.feeType.labour)).toDecimal(decimalObj.bills.totalPrice), rate: '', perCentiare: ''});
                    rst.push({name: '       材料费', price: parseFloat(this.fee(node, this.feeType.material)).toDecimal(decimalObj.bills.totalPrice), rate: '', perCentiare: ''});
                    rst.push({name: '       机械费', price: parseFloat(this.fee(node, this.feeType.machine)).toDecimal(decimalObj.bills.totalPrice), rate: '', perCentiare: ''});
                    rst.push({name: '       主材费', price: parseFloat(this.fee(node, this.feeType.mainMaterial)).toDecimal(decimalObj.bills.totalPrice), rate: '', perCentiare: ''});
                    rst.push({name: '       设备费', price: parseFloat(this.fee(node, this.feeType.equipment)).toDecimal(decimalObj.bills.totalPrice), rate: '', perCentiare: ''});
                    let labourDiff = this.fee(node, this.feeType.labourDiff),
                        materialDiff = this.fee(node, this.feeType.materialDiff),
                        machineDiff = this.fee(node, this.feeType.machineDiff),
                        rcjDiff = labourDiff + materialDiff + machineDiff;
                    rst.push({name: '       人材机价差', price: parseFloat(rcjDiff).toDecimal(decimalObj.bills.totalPrice), rate: '', perCentiare: ''});
                    rst.push({name: '       企业管理费', price: parseFloat(this.fee(node, this.feeType.manage)).toDecimal(decimalObj.bills.totalPrice), rate: '', perCentiare: ''});
                    rst.push({name: '       利润', price: parseFloat(this.fee(node, this.feeType.profit)).toDecimal(decimalObj.bills.totalPrice), rate: '', perCentiare: ''});
                }
                else if(this.isCSXM(node)){
                    rst.push(dxfy);
                    rst.push({name: '其中:', price: '', rate: '', perCentiare: ''});
                    let safeConst = this.getDXFY(this.getFixedBill(fixedFlag.SAFETY_CONSTRUCTION));
                    if(safeConst){
                        safeConst.name = `      ${safeConst.name}`;
                        rst.push(safeConst);
                    }
                }
                else{
                    rst.push(dxfy);
                }
            }
        }
        return rst;
    }
};

$(document).ready(function () {
    $('#tab_poj-settings-indicativeInfo').on('shown.bs.tab', function(){
        if(indicativeInfoObj.workBook){
            indicativeInfoObj.workBook.destroy();
            indicativeInfoObj.workBook = null;
        }
        indicativeInfoObj.buildSheet();
        indicativeInfoObj.showData(indicativeInfoObj.getIndicativeInfo());
    });
    $('#poj-set').on('shown.bs.modal', function () {
        indicativeInfoObj.buildSheet();
        indicativeInfoObj.showData(indicativeInfoObj.getIndicativeInfo());
    });

    $('#poj-set').on('hidden.bs.modal', function () {
       if(indicativeInfoObj.workBook){
           indicativeInfoObj.workBook.destroy();
           indicativeInfoObj.workBook = null;
       }
    });

    $('#tab_poj-settings-indicativeInfo').on('shown.bs.tab', function () {
        indicativeInfoObj.workBook.refresh();
    });
});