/**
 * 聊天室相关
 *
 * @author CaiAoLin
 * @date 2017/6/15
 * @version
 */
let header = [];
let sheet = null;
$(document).ready(function () {
    // excel
     header = [
        {name: '编码', field: 'code', visible: true},
        {name: '名称', field: 'name', visible: true},
        {name: '规格型号', field: 'unit_price.specs', visible: true},
        {name: '单位', field: 'unit_price.unit', visible: true},
        {name: 'ID', field: 'id', visible: false},
        {name: '类型', field: 'unit_price.type', visible: false},
        {name: '总消耗量', field: '', visible: true},
        {name: '基价单价', field: "unit_price.base_price", visible: true},
        {name: '调整基价', field: 'adjust_price', visible: true},
        {name: '市场单价', field: "unit_price.market_price", visible: true, validator: 'number'},
        {name: '是否暂估', field: 'is_evaluate', visible: true, cellType: new GC.Spread.Sheets.CellTypes.CheckBox(),  validator: 'boolean'},
        {name: '供货方式', field: 'supply', visible: true},
        {name: '甲供数量', field: 'supply_quantity', visible: true},
        {name: '交货方式', field: 'delivery', visible: true},
        {name: '送达地点', field: 'delivery_address', visible: true},
        {name: '不调价', field: 'is_adjust_price', visible: true, cellType: new GC.Spread.Sheets.CellTypes.CheckBox(),  validator: 'boolean'},
        {name: 'UID', field: 'unit_price.id', visible: false},
    ];
    // 数据转换格式
    let sourceData = JSON.parse(jsonData);

    let setting = {
        header: []
    };
    for(let tmp of header) {
        setting.header.push({headerName: tmp.name, headerWidth: 120});
    }

    let spread = sheetCommonObj.buildSheet(document.getElementById("test"), setting, sourceData.length);
    spread.options.scrollbarShowMax = true;
    spread.options.scrollbarMaxAlign = true;
    spread.options.showHorizontalScrollbar = true;
    sheet = spread.getActiveSheet();

    // 设置表单不可编辑
    sheet.options.isProtected = true;

    // 居中样式
    let centerStyleSetting = {hAlign: 1};
    sheet.setStyle(-1, 10, getStyle(centerStyleSetting), GC.Spread.Sheets.SheetArea.viewport);
    sheet.setStyle(-1, 15, getStyle(centerStyleSetting), GC.Spread.Sheets.SheetArea.viewport);
    sheet.setStyle(-1, 3, getStyle(centerStyleSetting), GC.Spread.Sheets.SheetArea.viewport);

    // 向右对齐样式
    let rightStyleSetting = {hAlign: GC.Spread.Sheets.HorizontalAlign.right};
    sheet.setStyle(-1, 6, getStyle(rightStyleSetting), GC.Spread.Sheets.SheetArea.viewport);
    sheet.setStyle(-1, 7, getStyle(rightStyleSetting), GC.Spread.Sheets.SheetArea.viewport);
    sheet.setStyle(-1, 8, getStyle(rightStyleSetting), GC.Spread.Sheets.SheetArea.viewport);
    sheet.setStyle(-1, 9, getStyle(rightStyleSetting), GC.Spread.Sheets.SheetArea.viewport);


    // 设置可编辑列
    sheet.getRange(-1, 9, -1, 1).locked(false);
    sheet.getRange(-1, 10, -1, 1).locked(false);
    sheet.getRange(-1, 15, -1, 1).locked(false);

    // 设置json数据
    let rowCounter = 0;
    for(let data of sourceData) {
        let columnCounter = 0;
        for(let columnInfo of header) {
            // 设置是否显示
            sheet.setColumnVisible(columnCounter, columnInfo.visible);

            let dataString = columnInfo.field !== '' && columnInfo.field !== undefined ?
                "data." + columnInfo.field : '';
            let cellData = eval(dataString);

            // 设置复选框
            if (columnInfo.cellType !== undefined) {
                let checkbox = new GC.Spread.Sheets.CellTypes.CheckBox();
                sheet.setCellType(rowCounter, columnCounter, checkbox, GC.Spread.Sheets.SheetArea.viewport);
            }

            // 如果不为材料“是否暂估列”根据条件显示
            if (columnInfo.field === 'is_evaluate' && materialIdList.indexOf(data.unit_price.type + '') < 0) {
                let string = new GC.Spread.Sheets.CellTypes.Text();
                sheet.setCellType(rowCounter, columnCounter, string, GC.Spread.Sheets.SheetArea.viewport);
                cellData = '';
                // 并且锁定该单元格
                sheet.getRange(rowCounter, columnCounter, 1, 1).locked(true);
            }

            // 如果类型为混凝土、砂浆、配合比、机械，则市场单价不能修改
            if (columnInfo.field === 'unit_price.market_price' && canNotChangeTypeId.indexOf(data.unit_price.type + '') >= 0) {
                // 锁定该单元格
                sheet.getRange(rowCounter, columnCounter, 1, 1).locked(true);
            }

            sheet.setValue(rowCounter, columnCounter, cellData, GC.Spread.Sheets.SheetArea.viewport);
            columnCounter++;
        }
        rowCounter++;
    }

/*
    let socket = io('http://notify.smartcost.com.cn:3300');
    socket.on('connect', function () {
        socket.emit('join', project);
        console.log('连接成功');
    });

    // 接受到改变
    let changeInfo = [];
    socket.on('dataChange', function(data) {
        data = JSON.parse(data);
        if (data.newValue === undefined) {
            return false;
        }
        changeInfo.push(data);
        $("#message").html('基价单位已被修改，<a href="javascript:void(0);" id="load-data">点击加载</a>');
        $("#notify").slideDown('fast');
        initiativeChange = false;
    });

    // 是否主动更改数据
    let initiativeChange = false;
    $("#message").on('click', '#load-data', function() {
        $("#notify").slideUp('fast');
        if (changeInfo.length > 0) {
            for (let index in changeInfo) {
                let cell = sheet.getCell(changeInfo[index].row, changeInfo[index].col, GC.Spread.Sheets.SheetArea.viewport);
                cell.value(changeInfo[index].newValue);
            }
        }
        changeInfo = [];
    });

    // 进入单元格后设置为主动设置数据
    sheet.bind(GC.Spread.Sheets.Events.EditEnding, function (element, info) {
        initiativeChange = true;
    });
 */
    // 绑定事件
    let isChanging = false;
    sheet.bind(GC.Spread.Sheets.Events.ValueChanged, function (element, info) {
        // 获取修改的数据
        let column = info.col;
        let row = info.row;
        let model = 'glj';
        let idString = 'id';
        let field = header[column] !== undefined && header[column].field !== undefined ?
            header[column].field : '';
        if (field === '') {
            return false;
        }

        // 切割字段
        let fieldArray = field.split('.');
        idString = fieldArray.length > 1 ? 'unit_price.id' : idString;

        // 防止快速同时提交
        if (isChanging) {
            return false;
        }
        // 校验数据
        let validator = header[column].validator !== undefined ? header[column].validator : null;
        let value = info.newValue;
        if (validator && !checkData(validator, value)) {
            alert('数据格式错误，请重新输入!');
            sheet.setValue(row, column, info.oldValue);
            return false;
        }

        // 获取id
        let idColumn = getFieldColumn(header, idString);
        if (idColumn < 0) {
            return false;
        }
        let id = sheet.getValue(row, idColumn);

        $.ajax({
            url: '/glj/update',
            type: 'post',
            data: {id: id, field: field, value: value, model: model},
            dataType: 'json',
            error: function() {
                alert('数据传输有误!');
                isChanging = false;
            },
            beforeSend: function() {
                isChanging = true;
            },
            success: function(response) {
                isChanging = false;
                // 修改失败则恢复原值
                if (response.err !== 0) {
                    sheet.setValue(row, column, info.oldValue);
                    alert('更改数据失败!');
                } else {
                    // 成功则触发相应事件
                    successTrigger(field, info);
                }
            }
        });
        /*
        // 如果修改了数据且为主动修改，先存库再广播给其他页面
        if (info.newValue !== undefined && info.oldValue !== undefined && initiativeChange) {
            let id = sheet.getCell(info.row, 0).value();
            $.ajax({
                url: '/save',
                type: 'post',
                data: {priceValue: info.newValue, id: id},
                error: function() {
                    // @todo 替换为更好地错误提示
                    alert('error');
                },
                beforeSend: function() {

                },
                success: function(response) {
                    if (response.err === 0) {
                        socket.emit('dataNotify', JSON.stringify(info));
                    } else {
                        // @todo 替换为更好地错误提示
                        alert(response.msg);
                    }
                }
            });
        }
        */
    });

    // 绑定双击事件
    sheet.bind(GC.Spread.Sheets.Events.CellDoubleClick, function (element, info) {
        let column = info.col;
        let row = info.row;
        let field = header[column] !== undefined && header[column].field !== undefined ?
            header[column].field : '';

        // 获取类型
        let typeColumn = getFieldColumn(header, 'unit_price.type');
        let type = sheet.getValue(row, typeColumn);

        // 如果类型为混凝土、砂浆、配合比、机械，则提示
        if (field === 'unit_price.market_price' && canNotChangeTypeId.indexOf(type + '') >= 0) {
            alert('当前工料机的市场单价由组成物计算得出，不可直接修改');
        }
    });

});

/**
 * 生成样式
 *
 * @param {object} setting
 * @return {object}
 */
function getStyle(setting) {
    let style = new GC.Spread.Sheets.Style();
    style.locked = setting.readOnly === undefined ? true : setting.readOnly;
    style.hAlign = setting.hAlign === undefined ? GC.Spread.Sheets.HorizontalAlign.center : setting.hAlign;
    return style;
}

/**
 * 查找指定字段的列index
 *
 * @param {object} data
 * @param {String} field
 * @return {Number}
 */
function getFieldColumn(data, field) {
    let result = -1;
    if (data.length <= 0) {
        return result;
    }
    for (let tmp in data) {
        if (data[tmp].field === field) {
            result = tmp;
            break;
        }
    }

    return result;
}

/**
 * 校验数据
 *
 * @param {string} validator
 * @param {string} value
 * @return {boolean}
 */
function checkData(validator, value) {
    let result = false;
    switch (validator) {
        case 'number':
            let regular = /^\d+(\.\d+)?$/;
            result = regular.test(value);
            break;
        case 'boolean':
            let booleanValue = [true, false];
            result = booleanValue.indexOf(value) >= 0;
            break;
    }

    return result;
}

/**
 * 成功事件
 *
 * @param {string} field
 * @param {object} info
 * @return {void}
 */
function successTrigger(field, info) {
    switch (field) {
        case 'unit_price.market_price':
            let row = info.row;
            let basePriceColumn = getFieldColumn(header, 'unit_price.base_price');
            let adjustPriceColumn = getFieldColumn(header, 'adjust_price');

            // 获取类型
            let typeColumn = getFieldColumn(header, 'unit_price.type');
            let type = sheet.getValue(row, typeColumn);

            // 主材、设备自动赋值基价单价=市场单价、调整基价=市场单价
            if (autoChangeGLJType.indexOf(type + '') >= 0) {
                sheet.setValue(info.row, basePriceColumn, info.newValue);
                sheet.setValue(info.row, adjustPriceColumn, info.newValue);
            }

            // 人工、材料(普通材料)触发 需计算混凝土、砂浆、配合比、机械的市场单价 @todo 后续添加
            if (triggerCalculateGLJType.indexOf(type + '') >= 0) {
                // 计算
                console.log('触发计算');
            }
            break;
    }
}