/**
 * 组成物Spread
 *
 * @author CaiAoLin
 * @date 2017/7/18
 * @version
 */

/**
 * 构造函数
 *
 * @return {void}
 */
function CompositionSpread () {
    this.isChanging = false;
    this.sheetObj = null;
    this.successCallback = null;
    this.rightClickTarget = null;
}

/**
 * 初始化
 *
 * @param {String} target
 * @return {Object}
 */
CompositionSpread.prototype.init = function(target) {
    let name = target === 'machine' ? '用量' : '消耗量';
    let header = [
        {name: '编码', field: 'code', visible: true},
        {name: '名称', field: 'name', visible: true},
        {name: '单位', field: 'unit', visible: true},
        {name: 'ID', field: 'id', visible: false},
        {name: '类型', field: 'unit_price.type', visible: false},
        {name: '定额价', field: "base_price", visible: true,decimalField:"glj.unitPrice"},
        {name: '调整价', field: 'adjust_price', visible: true,decimalField:"glj.unitPrice"},
        {name: '市场价', field: "unit_price.market_price", visible: true,decimalField:"glj.unitPrice"},
        {name: name, field: 'consumption', visible: true, validator: 'number',decimalField:'glj.quantity'},
        {name: 'CID', field: 'mix_ratio_id', visible: false},
    ];

    this.sheetObj = new CommonSpreadJs(header);
    this.sheetObj.init(target);

    // 获取列号
    let codeColumn = this.sheetObj.getFieldColumn('code');
    let unitColumn = this.sheetObj.getFieldColumn('unit');
    let consumptionColumn = this.sheetObj.getFieldColumn('consumption');
    let basePriceCol = this.sheetObj.getFieldColumn('base_price');
    let adjustPriceCol = this.sheetObj.getFieldColumn('adjust_price');
    let marketPriceCol = this.sheetObj.getFieldColumn('unit_price.market_price');
    // 居中样式
    let centerStyleSetting = {hAlign: 1};
    this.sheetObj.setStyle(-1, codeColumn, centerStyleSetting);
    this.sheetObj.setStyle(-1, unitColumn, centerStyleSetting);

    //靠右设置
    let rightStyleSetting={hAlign: 2};
    this.sheetObj.setStyle(-1, basePriceCol, rightStyleSetting);
    this.sheetObj.setStyle(-1, adjustPriceCol, rightStyleSetting);
    this.sheetObj.setStyle(-1, marketPriceCol, rightStyleSetting);
    this.sheetObj.setStyle(-1, consumptionColumn, rightStyleSetting);

    // 设置可编辑列
    this.sheetObj.setColumnEditable(consumptionColumn);

    // 绑定事件
    let self = this;
    this.sheetObj.bind(GC.Spread.Sheets.Events.ValueChanged, function(element, info) {
        self.updateConsumption(info, self.successCallback);
    });

    return this.sheetObj;
};

/**
 * 初始化右键
 *
 * @param {String} target
 * @return {void}
 */
CompositionSpread.prototype.initRightClick = function(target) {
    let activeSheet = this.sheetObj.getSheet();
    let self = this;
    $.contextMenu({
        selector: '#' + target,
        build: function ($trigger, e) {
            self.rightClickTarget = SheetDataHelper.safeRightClickSelection($trigger, e, self.sheetObj.spread);
            return self.rightClickTarget.hitTestType === GC.Spread.Sheets.SheetArea.viewport ||
                self.rightClickTarget.hitTestType === GC.Spread.Sheets.SheetArea.rowHeader;
        },
        items: {
            "deleteMixRatio": {
                name: "删除",
                icon: 'fa-trash-o',
                disabled: function () {
                    return self.rightClickTarget.row === undefined;
                },
                callback: function (key, opt) {
                    let row = self.rightClickTarget.row;
                    let idColumn = self.sheetObj.getFieldColumn('mix_ratio_id');
                    let deleteId = activeSheet.getValue(row, idColumn);
                    self.deleteComposition(deleteId, row, self.successCallback);
                }
            },
        }
    });
};

/**
 * 获取组成物数据
 *
 * @param {Number} projectGLJid
 * @return {void | boolean}
 */
CompositionSpread.prototype.getRatioData = function(projectGLJid) {
    projectGLJid = parseInt(projectGLJid);
    let self = this;
    if (isNaN(projectGLJid) || projectGLJid <= 0) {
        this.sheetObj.setData(null);
        return false;
    }
    $.ajax({
        url: '/glj/get-ratio',
        type: 'post',
        data: {id: projectGLJid, project_id: scUrlUtil.GetQueryString('project')},
        error: function(jqXHR, textStatus, errorThrown) {
            ajaxErrorInfo(jqXHR, textStatus, errorThrown);
            self.sheetObj.setData(null);
        },
        beforeSend: function() {

        },
        success: function(response) {
            if (response.err === 0) {
                response.data = JSON.parse(response.data);
                // 设置数据
                self.sheetObj.setData(response.data);
                self.specialColumn(response.data);
            } else {
                self.sheetObj.setData(null);
                console.log('不存在对应数据');
            }
        }
    });
};

/**
 * 设置特殊单元格数据
 *
 * @param {object} sourceData
 * @return {void}
 */
CompositionSpread.prototype.specialColumn = function(sourceData) {
    let rowCounter = 0;
    // 获取市场单价列号
    let consumptionColumn = this.sheetObj.getFieldColumn('consumption');
    let basePriceColumn = this.sheetObj.getFieldColumn('base_price');
    let adjustPriceColumn = this.sheetObj.getFieldColumn('adjust_price');
    let idColumn = this.sheetObj.getFieldColumn('mix_ratio_id');
    let activeSheet = this.sheetObj.getSheet();
    for(let data of sourceData) {
        // 把消耗量从对象中抽离出来
        if (data.ratio_data.consumption !== undefined) {
            activeSheet.setValue(rowCounter, consumptionColumn, data.ratio_data.consumption);
            activeSheet.setValue(rowCounter, idColumn, data.ratio_data.id);
        }
        data=this.sheetObj.setProjectGLJDiffPrice(data);
        activeSheet.setValue(rowCounter, basePriceColumn, data.base_price);
        activeSheet.setValue(rowCounter, adjustPriceColumn, data.adjust_price);
        rowCounter++;
    }
};

/**
 * 更新组成物消耗量或用量
 *
 * @param {Object} info
 * @param {function} callback
 * return {void}
 */
CompositionSpread.prototype.updateConsumption = function(info, callback) {
    // 获取修改的数据
    let column = info.col;
    let row = info.row;
    let field = this.sheetObj.getColumnField(column);
    if (field === '') {
        return false;
    }
    // 防止快速同时提交
    if (this.isChanging) {
        return false;
    }
    let activeSheet = this.sheetObj.getSheet();
    // 校验数据
    let value = info.newValue;
    if (!this.sheetObj.checkData(column, value)) {
        alert('数据格式错误，请重新输入!');
        activeSheet.setValue(row, column, info.oldValue);
        return false;
    }

    // 获取id
    let idColumn = this.sheetObj.getFieldColumn('mix_ratio_id');
    if (idColumn < 0) {
        return false;
    }
    let id = activeSheet.getValue(row, idColumn);
    let [parentMarketPrice, parentBasePrice] = this.getCompositionSumPrice('modify', row, info.newValue);

    let self = this;
    $.ajax({
        url: '/glj/update',
        type: 'post',
        data: {id: id, field: 'mix_ratio.' + field, value: value, market_price: parentMarketPrice, base_price: parentBasePrice},
        dataType: 'json',
        error: function(jqXHR, textStatus, errorThrown) {
            ajaxErrorInfo(jqXHR, textStatus, errorThrown);
            self.isChanging = false;
            activeSheet.setValue(row, column, info.oldValue);
        },
        beforeSend: function() {
            self.isChanging = true;
        },
        success: function(response) {
            self.isChanging = false;
            // 修改失败则恢复原值
            if (response.err !== 0) {
                activeSheet.setValue(row, column, info.oldValue);
                alert('更改数据失败!');
            } else {
                info.id = id;
                info.field = field;
                info.parentMarketPrice = parentMarketPrice;
                info.parentBasePrice = parentBasePrice;
                info.change = info.newValue - info.oldValue;
                callback(info);
            }
        }
    });
};

/**
 * 获取当前所有组成物累积的市场单价和基价单价
 * 用于同步修改父级市场单价和基价单价
 *
 * @param {String} scene
 * @param {Number} affectRow
 * @param {Number} newValue
 * @return {Array}
 */
CompositionSpread.prototype.getCompositionSumPrice = function(scene, affectRow, newValue = 0) {
    let activeSheet = this.sheetObj.getSheet();
    // 计算父级3个价格
    let maxRow = activeSheet.getRowCount();
    // 获取对应列的列号
    let marketPriceColumn = this.sheetObj.getFieldColumn('unit_price.market_price');
    let consumptionColumn = this.sheetObj.getFieldColumn('consumption');
    let basePriceColumn = this.sheetObj.getFieldColumn('base_price');

    let parentMarketPrice = 0;
    let parentBasePrice = 0;
    for(let i = 0; i < maxRow; i++) {
        // 获取市场单价
        let marketPrice = activeSheet.getValue(i, marketPriceColumn);
        // 获取基价单价
        let basePrice = activeSheet.getValue(i, basePriceColumn);

        // 如果是删除则忽略即将被删除的行数据
        if (scene === 'delete' && affectRow === i) {
            continue;
        }

        // 获取消耗量(如果是当前修改的行则替换数据)
        let consumption = i === affectRow ? newValue : activeSheet.getValue(i, consumptionColumn);
        parentMarketPrice += operationWithRound(consumption,marketPrice,"glj.unitPrice","*");
        parentBasePrice += operationWithRound(consumption,basePrice,"glj.unitPrice","*");
    }

    parentMarketPrice = parentMarketPrice.toDecimal(getDecimal("glj.unitPrice"));
    parentBasePrice = parentBasePrice.toDecimal(getDecimal("glj.unitPrice"));

    return [parentMarketPrice, parentBasePrice]
};

/**
 * 删除组成物
 *
 * @param {Number} id
 * @param {Number} row
 * @param {function} callback
 * @return {void | boolean}
 */
CompositionSpread.prototype.deleteComposition = function (id, row, callback) {
    id = parseInt(id);
    if (isNaN(id) || id <= 0) {
        alert('参数错误!');
    }
    if (isDeleting) {
        return false;
    }
    let activeSheet = this.sheetObj.getSheet();
    // 获取当前行的消耗量
    let consumptionColumn = this.sheetObj.getFieldColumn('consumption');
    let consumption = activeSheet.getValue(row, consumptionColumn);
    let self = this;
    $.ajax({
        url: '/glj/delete-ratio',
        type: 'post',
        data: {id: id},
        dataType: 'json',
        error: function(jqXHR, textStatus, errorThrown) {
            ajaxErrorInfo(jqXHR, textStatus, errorThrown);
            isDeleting = false;
            alert('服务器繁忙');
        },
        beforeSend: function() {
            isDeleting = true;
        },
        success: function(response) {
            if (response.err === 0) {
                // 计算同级的市场单价和基价单价
                let [parentMarketPrice, parentBasePrice] = self.getCompositionSumPrice('delete', row);
                let info = {
                    parentMarketPrice: parentMarketPrice,
                    parentBasePrice: parentBasePrice,
                    change: -consumption
                };
                activeSheet.setValue(row, consumptionColumn, 0);
                callback(info);
            }
        }
    });
};