'use strict';

/**
 *
 *
 * @author Zhong
 * @date 2018/11/28
 * @version
 */
/*
* 定额下模板关联
* */

const RationTemplate = (function () {
    let curRation = null;
    function _isDef(v) {
        return typeof v !== 'undefined' && v !== null;
    }
    //当前定额下的定额模板关联数据
    let templateData = [];
    let templateSheet = null;
    //重新设置templateData
    function setTemplateData(newData) {
        templateData = _isDef(newData) && Array.isArray(newData) ? newData : [];
    }
    let setting = {
        header:[
            {headerName:"关联类别",headerWidth:110,dataCode:"type", dataType: "String", hAlign: "left", formatter: "@"},
            {headerName:"编码",headerWidth:90,dataCode:"code", dataType: "String", hAlign: "left", formatter: "@"},
            {headerName:"名称",headerWidth:240,dataCode:"name", dataType: "String", hAlign: "left", formatter: "@"},
            {headerName:"具体位置",headerWidth:90,dataCode:"billsLocation", dataType: "String", hAlign: "left", formatter: "@"}
        ],
        view:{},
    };
    //渲染时方法，停止渲染
    //@param {Object}sheet {Function}func @return {void}
    function renderSheetFunc(sheet, func){
        sheet.suspendEvent();
        sheet.suspendPaint();
        if(func){
            func();
        }
        sheet.resumeEvent();
        sheet.resumePaint();
    }
    const items = ['模板关联', '超高关联'];
    //设置下拉单元格
    //@return {void}
    function setComboCells() {
        if (!templateSheet) {
            return;
        }
        let combo = sheetCommonObj.getDynamicCombo();
        combo.items(items).editorValueType(GC.Spread.Sheets.CellTypes.EditorValueType.text);
        templateSheet.getRange(-1, 0, -1, 1).cellType(combo);
    }
    //有效数据
    //@param {String}dataCode {String}text @return {String}
    function validateData(dataCode, text) {
        //类别只能为规定的两种关联,否则将类别自动恢复为''
        if (dataCode === 'type') {
            if (text !== '' && !items.includes(text)) {
                text = '';
            }
        }
        return text;
    }
    //从当前表格获取数据
    //@return {Array}
    function getDataFromSheet() {
        let rst = [];
        if (!templateSheet) {
            return rst;
        }
        let rowCount = templateSheet.getRowCount(),
            colCount = templateSheet.getColumnCount();
        for (let row = 0; row < rowCount; row++) {
            let rowData = {type: '', code: '', name: '', billsLocation: ''},
                rowExistData = false;
            for (let col = 0; col < colCount; col++) {
                let text = templateSheet.getValue(row, col),
                    dataCode = setting.header[col]['dataCode'];
                text = _isDef(text) ? text : '';
                text = validateData(dataCode, text);
                if (text !== '') {
                    rowExistData = true;
                    if (dataCode === 'code') {//编码没有小写，自动转化为大写
                        text = text.toString().toUpperCase();
                    }
                    rowData[dataCode] = text;
                } else {
                    if (dataCode === 'code') {
                        templateSheet.setValue(row, col + 1, '');
                    }
                }
            }
            //不为空行
            if (rowExistData) {
                rst.push(rowData);
            }
        }
        return rst;
    }
    //编辑,定额编号自动匹配定额名称，匹配过程在后端进行,前端进行名称的更新输出
    //@return {void}
    function edit() {
        if (!curRation) {
            return;
        }
        let sheetData = getDataFromSheet();
        CommonAjax.post('/rationRepository/api/updateRationTemplate',
            {rationRepId: getQueryString('repository'), rationID: curRation.ID, templateData: sheetData}, function (rstData) {
            templateData = rstData;
            curRation.rationTemplateList = templateData;
            renderSheetFunc(templateSheet, function () {
                sheetCommonObj.showData(templateSheet, setting, templateData);
            });
        }, function () {
            renderSheetFunc(templateSheet, function () {
                sheetCommonObj.showData(templateSheet, setting, templateData);
            });
        });

    }
    let events = {
        onEnterCell: function (sender, args) {
            args.sheet.repaint();
        },
        onEditStarting: function (sender, args) {
            let dataCode = setting.header[args.col]['dataCode'];
            if (dataCode === 'name') {
                args.cancel = true;
            }
        },
        onEditEnded: function (sender, args) {
            edit();
        },
        onRangeChanged: function (sender, args) {
            edit();
        }
    };
    //重新绑定del建
    //@return {void}
    function bindRationTempDel() {
        if (locked || !templateSheet) {
            return;
        }
        let workBook = templateSheet.getParent();
        workBook.commandManager().register('rationTempDel', function () {
            renderSheetFunc(templateSheet, function () {
                let sels = templateSheet.getSelections();
                for (let sel of sels) {
                    sel.row = sel.row === -1 ? 0 : sel.row;
                    sel.col = sel.col === -1 ? 0 : sel.col;
                    for (let row = sel.row; row < sel.rowCount + sel.row; row++) {
                        for (let col = sel.col; col < sel.colCount + sel.col; col++) {
                            templateSheet.setValue(row, col, '');
                        }
                    }
                }
            });
            edit();
        });
        workBook.commandManager().setShortcutKey(null, GC.Spread.Commands.Key.del, false, false, false, false);
        workBook.commandManager().setShortcutKey('rationTempDel', GC.Spread.Commands.Key.del, false, false, false, false);
    }
    //建表
    //@param {Object}sheet @return {void}
    function buildSheet(sheet) {
        templateSheet = sheet;
        sheetCommonObj.initSheet(templateSheet, setting, 30);
        templateSheet.options.isProtected = true;
        setComboCells();
        const Events = GC.Spread.Sheets.Events;
        sheet.bind(Events.EditStarting, events.onEditStarting);
        sheet.bind(Events.EditEnded, events.onEditEnded);
        sheet.bind(Events.RangeChanged, events.onRangeChanged);
        sheet.bind(Events.EnterCell, events.onEnterCell);
    }

    //更改模板关联表锁定状态
    //@param {Boolean}locked @return {void}
    function changeLockMode(locked) {
        if (templateSheet) {
            if (!locked) {
                templateSheet.getRange(-1, 0, -1, 4).locked(false);
                //templateSheet.getRange(-1, 3, -1, 1).locked(false);
            } else {
                templateSheet.getRange(-1, 0, -1, 4).locked(true);
                //templateSheet.getRange(-1, 3, -1, 1).locked(true);
            }
        }
    }
    //变更定额
    function rationInitSel(ration) {
        curRation = ration ? ration : null;
        changeLockMode(!ration);
        sheetCommonObj.cleanData(templateSheet, setting, -1);
        if (ration) {
            setTemplateData(ration.rationTemplateList);
            sheetCommonObj.showData(templateSheet, setting, templateData);
        } else {
            setTemplateData([]);
        }
    }
    return {buildSheet, rationInitSel, bindRationTempDel, events}
})();