/**
 * Created by Zhong on 2017/11/15.
 */
/*
* 清单工程量精度
* */
let billsQuanDecimal = {
    datas: [],
    //根据单位获取精度, 需要用清单工程量精度的调用此接口
    decimal: function (unit) {
        for(let i = 0, len = this.datas.length; i < len; i++){
            if(unit === this.datas[i].unit){
                return this.datas[i].decimal;
            }
        }
        return this.datas[0].decimal;
    }
};

//点了确定才更新数据
let billsDecimalView = {
    default: {min: 0, max: 4, decimal: 3},//以防后面修改,小数数位的取值范围, default.decimal为新增时默认的小数位
    angleDecimal: {unit: '其他未列单位', decimal: 2},//防止出现工程没有初始默认的清单工程量精度模板（正常不会出现）
    cache: [],//temp
    workBook: null,
    setting:{
        header: [
            {name: '计量单位', dataCode: 'unit', width: 120, vAlign: 'center', hAlign: 'left'},
            {name: '小数位数', dataCode: 'decimal', width: 80, vAlign: 'center', hAlign: 'center'}
        ],
        options: {
            allowContextMenu: false,
            tabStripVisible:  false,
            allowCopyPasteExcelStyle : 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];
        }
    },

    getComboItems: function (min, max) {
        let rst = [];
        while (min <= max){
            rst.push(min);
            min ++;
        }
        return rst;
    },
    
    setComboBox: function (sheet, items) {
        let combo = sheetCommonObj.getDynamicCombo();
        combo.items(items);
        combo.editable(true);
        sheet.getRange(-1, 1, -1, 1).cellType(combo);
    },

    buildHeader: function (sheet, headers) {
        let me = billsDecimalView;
        let fuc = function () {
            sheet.setColumnCount(headers.length);
            sheet.setRowHeight(0, 40, GC.Spread.Sheets.SheetArea.colHeader);
            me.setComboBox(sheet, me.getComboItems(me.default.min, me.default.max));
            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($('#billsQuanDecimal')[0], {sheetCount: 1});
            sheetCommonObj.spreadDefaultStyle(this.workBook);
            this.setOptions(this.workBook, this.setting.options);
            this.buildHeader(this.workBook.getActiveSheet(), this.setting.header);
            this.bindEvent(this.workBook);
            this.onContextmenuOpr();
        }
    },

    bindEvent: function (workBook) {
        const _events = GC.Spread.Sheets.Events;
        let sheet = workBook.getActiveSheet();
        let me = billsDecimalView;
        sheet.bind(_events.EnterCell, me.onEnterCell);
        sheet.bind(_events.EditStarting, me.onEditStarting);
        sheet.bind(_events.EditEnded, me.onEditEnded);
        sheet.bind(_events.ClipboardPasting, me.onClipboardPasting);
        sheet.bind(_events.ClipboardPasted, me.onClipboardPasted);
    },

    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++){
                sheet.getRange(-1, col, -1, 1).hAlign(GC.Spread.Sheets.HorizontalAlign[cols[col]['hAlign']]);
                sheet.getRange(-1, col, -1, 1).hAlign(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);
    },

    onEnterCell: function (sender, args) {
        args.sheet.repaint();
    },

    onEditStarting: function (sender, args) {
        if(args.col === 0 && args.row === 0){//其他未列单位不可编辑
            args.cancel = true;
        }
    },

    onEditEnded: function (sender, args) {
        console.log('enter');
        let me = billsDecimalView;
        console.log(args);
        let v =  args.editingText !== undefined && args.editingText !== null ? args.editingText.toString().trim() : '';
        console.log(v);
        if(v.length === 0){
            return;
        }
        if(args.col === 0){
            if(v !== me.cache[args.row].unit && me.hasUnit(me.cache, v)){
                alert('已存在此计量单位');
                args.sheet.setValue(args.row, args.col, me.isDef(me.cache[args.row]) ? me.cache[args.row].unit : '');
            }
            else {
                me.cache[args.row].unit = v;
                if(!me.isValidDecimal(me.cache[args.row].decimal)){
                    me.cache[args.row].decimal = me.default.decimal;
                    args.sheet.setValue(args.row, 1, me.default.decimal);
                }
            }
        }
        else if(args.col === 1){
            if(!me.isValidDecimal(v)){
                alert('小数位数只能是'+ me.default.min + '-' + me.default.max + '的整数');
                args.sheet.setValue(args.row, args.col, me.isDef(me.cache[args.row]) ? me.cache[args.row].decimal : '');
            }
            else {
                me.cache[args.row].decimal = v;
            }
        }
        console.log(me.cache[args.row]);
    },

    onClipboardPasting: function (sender, args) {
        if(args.cellRange.row === 0 && args.cellRange.col === 0){
            args.cancel = true;
            alert('不可更改其他未列计量单位');
        }
    },

    onClipboardPasted: function (sender, args) {
        let me = billsDecimalView;
        let items = sheetCommonObj.analyzePasteData(me.setting, args);
        for(let i = 0, len = items.length; i < len; i++){
            let row = args.cellRange.row + i;
            if(me.isDef(me.cache[row])){
                if(me.isDef(items[i].unit) && !me.hasUnit(me.cache, items[i].unit)){
                    me.cache[row].unit = items[i].unit;
                }
                if(me.isValidDecimal(items[i].decimal)){
                    me.cache[row].decimal = items[i].decimal;
                }
            }
        }
        me.showData(me.cache);
    },

    onContextmenuOpr: function () {//右键菜单
        let me = billsDecimalView;
        $.contextMenu({
            selector: '#billsQuanDecimal',
            build: function($triggerElement, e){
                //控制允许右键菜单在哪个位置出现
                let target = SheetDataHelper.safeRightClickSelection($triggerElement, e, me.workBook);
                let sheet = me.workBook.getSheet(0);
                if(target.hitTestType === 3 && typeof target.row !== 'undefined'){//在表格内
                    let delDis = false;
                    let insertDis = false;
                    //控制按钮是否可用
                    sheet.setActiveCell(target.row, target.col);
                    if(target.row === 0){//不可删除其他未列单位行
                        delDis = true;
                    }
                    if(!me.isDef(me.cache) || target.row >= me.cache.length){//有数据才能删除
                        delDis = true;
                    }
                    return {
                        callback: function(){},
                        items: {
                            "insert": {name: "添加", disabled: insertDis, icon: "fa-sign-in", callback: function (key, opt) {
                                //插入空行
                                me.addRow(me.cache, sheet, target.row);
                            }},
                            "delete": {name: "删除", disabled: delDis, icon: "fa-remove", callback: function (key, opt) {
                               me.deleteRow(me.cache, sheet, target.row);
                            }}
                        }
                    };
                }
                else{
                    return false;
                }
            }
        });
    },
    //新增一空白行
    addRow: function (all, sheet, row) {
        let func = function () {
            let data = Object.create(null);
            data.unit = '';
            data.decimal = '';
            //新增空行
            if(row === 0){//保证其他未列单位在第一行
                row = 1;
            }
            //新增空白数据
            all.splice(row, 0, data);
            sheet.addRows(row, 1);
        };
        this.renderSheetFuc(sheet, func);
    },

    deleteRow: function (all, sheet, row) {
        let func = function () {
            all.splice(row, 1);
            sheet.deleteRows(row, 1);
        };
        this.renderSheetFuc(sheet, func);
    },

    isDef: function (v) {
        return v !== undefined && v !== null;
    },

    isData: function (v) {
        return this.isDef(v) && v.toString().trim().length > 0;
    },

    isValidDecimal: function (v) {
        return this.isData(v) && !isNaN(v) && parseInt(v) == v && parseInt(v) >= this.default.min && parseInt(v) <= this.default.max;
    },

    hasUnit: function (all, v) {
        for(let i = 0, len = all.length; i < len; i++){
            if(all[i].unit === v){
                return true;
            }
        }
        return false;
    },

    copyObj: function(obj){
        let newObj = {};
        for(let attr in obj){
            newObj[attr] = obj[attr];
        }
        return newObj;
    },

    initDatas: function (datas) {
        this.cache = [];
        for(let i = 0, len = datas.length; i < len; i++){
            this.cache.push(this.copyObj(datas[i]));
        }
    },

    rowHasData: function (sheet, row) {
        let v = sheet.getValue(row, 0);
        if(v && v.toString().trim().length > 0) {
            return true;
        }
        return false;
    },

    toUpdate: function (orgV, newV) {//org: billsDecimal.datas, newV: toBillsDecimalDatas(cache)
        for(let i = 0, len = orgV.length; i < len; i++){
            if(!this.isDef(newV[i])){
                return true;
            }
            else {
                if(orgV[i].unit !== newV[i].unit || orgV[i].decimal !== newV[i].decimal){
                    return true;
                }
            }
        }
        return false;
    },

    //将tempDatas提取出新的请单工程量精度数据
    toBillsDecimalDatas: function (datas) {
        let rst = [];
        for(let i = 0, len = datas.length; i < len; i++){
            if(this.isData(datas[i].unit) && this.isValidDecimal(datas[i].decimal)){
                datas[i].decimal = parseInt(datas[i].decimal);
                rst.push(datas[i]);
            }
        }
        return rst;
    },
    
    a_update: function (datas) {
        let url = '/pm/api/updateProjects';
        let updateData = {
            updateType: 'update',
            updateData: {
                ID: parseInt(scUrlUtil.GetQueryString('project')),
                'property.billsQuantityDecimal': datas
            }
        };
        let postData = {
            user_id: userID,
            updateData: [updateData]
        };
        CommonAjax.post(url, postData, function () {
            billsQuanDecimal.datas = datas;
        });
    }
};

$(document).ready(function () {
    $('#poj-set').on('shown.bs.modal', function (e) {
        //init Spread
        if(billsDecimalView.isDef(billsQuanDecimal.datas)){
            //billsDecimalView.cache = billsDecimalView.cache.concat(billsQuanDecimal.datas);
            billsDecimalView.initDatas(billsQuanDecimal.datas);
        }
        if(billsDecimalView.cache.length === 0){
            billsDecimalView.cache.push(billsDecimalView.angleDecimal);
        }
        billsDecimalView.buildSheet();
        billsDecimalView.showData(billsDecimalView.cache);
        if(projectReadOnly){
            sheetCommonObj.disableSpread(billsDecimalView.workBook);
        }
    });

    $('#poj-set').on('hidden.bs.modal', function (e) {
        //destroy Spread
        if(billsDecimalView.workBook){
            billsDecimalView.workBook.destroy();
            billsDecimalView.workBook = null;
        }
        billsDecimalView.cache = [];
    });

    $('#tab_poj-settings-bqDecimal').on('shown.bs.tab', function () {
        sheetCommonObj.refreshWorkbookDelDefer(billsDecimalView.workBook, 100);
    });

 /*   $('#property_ok').bind('click', function () {
        let newBillsDecimalDatas = billsDecimalView.toBillsDecimalDatas(billsDecimalView.cache);
        if(billsDecimalView.toUpdate(billsQuanDecimal.datas, newBillsDecimalDatas)){
            billsDecimalView.a_update(newBillsDecimalDatas);
        }
    });*/
});
