/**
 * 交付模块-标准预测计划发布JS
 *
 * Created by jt on 2019/10/21.
 * Modified by li.kui on 2020/6/9.
 */
'use strict';
var el = {
    planId: '#planId',
    searchForm: '#searchForm',
    product: '#product',
    supplier: '#supplier',
    purchaseGroup: '#purchaseGroup',
    quotaQuery: '#quotaQuery',
    planTotalNum: '#planTotalNum',
    adTotalNum: '#adTotalNum',
    unAdTotalNum: '#unAdTotalNum',
    tb: '#tb',
    editIndex: undefined,
    arData: [],
    bodyHeight: document.documentElement.clientHeight
};

$(function () {
    initDict("shortage_adjustment_reason")
    el.arData = [
        {label: popupi18n.xqlsbsh, value: '1'},
        {label: popupi18n.xhyybh, value: '2'},
        {label: popupi18n.gyscnwt, value: '3'},
        {label: popupi18n.gyscnwtbu, value: '4'},
        {label: popupi18n.ypzwtg, value: '5'},
        {label: popupi18n.qtgyszfe, value: '6'},
        {label: popupi18n.vmibz, value: '7'},
        {label: popupi18n.gyszlyc, value: '8'},
        {label: popupi18n.qtgyszlwt, value: '9'},
        {label: popupi18n.gysgxjg, value: '10'},
        {label: popupi18n.qt, value: '11'}
    ];
    initNecessaryDatas('pc/sys/purchaseGroup/rest/listAll');
    initDict("shortage_adjustment_reason")
    initPageDataGird();
});


function initPageDataGird() {
    var planId = $(el.planId).val();
    var searchHeight = $(el.searchForm).outerHeight() + 20;
    var pager = initGridPagerNew(el.bodyHeight - searchHeight, 37, 30);

    var tbTitle = '<span style="display: inline-block; width: 40%;">配额调整</span>';
    tbTitle += '<span style="display: inline-block; width: 20%;">预测发布总额: ' + $(el.planTotalNum).val() + '</span>';
    tbTitle += '<span style="display: inline-block; width: 20%;">已分配数量: ' + $(el.adTotalNum).val() + '</span>';
    tbTitle += '<span style="display: inline-block; width: 20%;">未分配数量: ' + $(el.unAdTotalNum).val() + '</span>';

    $(el.tb).edatagrid({
        title: tbTitle,
        loadMsg: '数据远程载入中,请等待...',
        url: g.ctx + 'pc/order/basicPlan/rest/find/wait/release/data',
        height: el.bodyHeight - searchHeight,
        singleSelect: false,
        rownumbers: true,
        pagination: true,
        pageSize: pager.pageSize,
        pageList: pager.pageList,
        queryParams: {
            planId: planId
        },
        columns: [
            [
                {
                    field: 'ck',
                    checkbox: true
                },
                {
                    field: 'detailId',
                    width: 50,
                    hidden: true
                },
                {
                    field: 'productCode',
                    title: '物料',
                    width: 100
                },
                {
                    field: 'productName',
                    title: '物料名称',
                    width: 300
                },
                {
                    field: 'purchaseGroup',
                    title: '采购组',
                    width: 100,
                    formatter: function (value) {
                        return getNecessaryDataName('pc/sys/purchaseGroup/rest/listAll', value);
                    }
                },
                /* {
                     field: 'isRiskMaterial',
                     title: '是否风险物料',
                     width: 85,
                     formatter: function (value) {
                         if ('是' === value) {
                             return '<span style="color:red">是</span>';
                         }
                         return value;
                     }
                 },*/
                {
                    field: 'planNum',
                    title: '预测数量',
                    width: 100
                },
                {
                    field: 'onOrderNum',
                    title: '未清总数',
                    width: 100
                },
                {
                    field: 'factoryCode',
                    title: '工厂',
                    width: 100
                },
                {
                    field: 'supplierCode',
                    title: '供应商',
                    width: 80
                },
                {
                    field: 'supplierName',
                    title: '供应商名称',
                    width: 200
                },
                {
                    field: 'outstandingPoNum',
                    title: '未清PO数量',
                    width: 100
                },
                {
                    field: 'oriQuota',
                    title: '配额（%）',
                    width: 80,
                    formatter: function (value) {
                        if (!value) {
                            return '';
                        }
                        return value;
                    }
                },
                {
                    field: 'distributeNum',
                    title: '分配数量',
                    width: 80,
                    formatter: function (value) {
                        if (!value) {
                            return '';
                        }
                        return value;
                    }
                },
                {
                    field: 'adjustmentNum',
                    title: '调整数量',
                    width: 80,
                    editor: {
                        type: 'numberbox',
                        options: {
                            precision: 0,
                            onChange: function (newValue) {
                                if (newValue !== '') {
                                    var cellEdit = $(el.tb).datagrid('getEditor', {
                                        index: el.editIndex,
                                        field: 'adjustmentReason'
                                    });
                                    if (cellEdit != null) {
                                        var $input = cellEdit.target;
                                        $input.combobox({required: true});
                                    }
                                } else {
                                    var cellEdit = $(el.tb).datagrid('getEditor', {
                                        index: el.editIndex,
                                        field: 'adjustmentReason'
                                    });
                                    if (cellEdit != null) {
                                        var $input = cellEdit.target;
                                        $input.combobox({required: false});
                                    }
                                }
                            }
                        }
                    },
                },
                {
                    field: 'adjustmentReason',
                    title: '调整原因',
                    width: 150,
                    formatter: function (value) {
                        return getDicName("shortage_adjustment_reason", value)
                    },
                    editor: {
                        type: 'combobox',
                        options: {
                            prompt: '-- ' + itablei8n.plchoose + ' --',
                            valueField: 'code',
                            textField: 'codeWithDesc',
                            data: getDictList("shortage_adjustment_reason"),
                            required: false,
                            editable: false,
                            panelHeight: 190,
                            panelWidth: 200,
                            onSelect: function (data) {
                                adjustmentReasonChange(data.value);
                            }
                        }
                    }
                },
                {
                    field: 'remark',
                    title: '备注',
                    width: 200,
                    editor: {
                        type: 'text'
                    }
                }
            ]
        ],
        onLoadSuccess: function () {
            $(el.tb).datagrid('clearSelections');

            autoMergeCells(el.tb);
        },
        onClickRow: function (index) {
            if (el.editIndex !== undefined) {
                endEditor(el.tb);
            }
            // 启动编辑
            $(el.tb).datagrid('beginEdit', index);
            el.editIndex = index;
            autoMergeCells(el.tb);
        }
    });
}



/**
 * 调整原因选择其他时 备注必填
 *
 * @param data 选中的数据
 */
function adjustmentReasonChange(data) {
    var cellEdit = $(el.tb).datagrid('getEditor', {index: el.editIndex, field: 'remark'});
    if (cellEdit != null) {
        var $input = cellEdit.target;
        if (Number(data) === 11) {
            $input.textbox({required: true});
        } else {
            $input.textbox({required: false});
        }
    }

}


/**
 * 保存发布数据
 *
 * @param callback 回调函数
 */
function saveReleaseData(callback) {
    $(el.tb).edatagrid("saveRow")
    var rows = $(el.tb).datagrid('getSelections'), submitData = [];
    if (rows.length < 1) {
        topWin.layer.alert(itablei8n.pdselect, {icon: 0});
        return false;
    }
    for (var i = 0; i < rows.length; i++) {
        var item = rows[i];
        //逻辑待修改 如果修改了明细行需要立即进行修改关联数据
        if (item.adjustmentNum === null || item.adjustmentNum === undefined || item.adjustmentNum.length === 0) {
            if ((item.adjustmentReason === "" || item.adjustmentReason == null) && item.adjustmentNum !== '') {
                topWin.layer.alert("您选择的第" + (i + 1) + "行物料调整数量后调整原因必填", {icon: 0});
                return false;
            }
        }
    }
    for (var i = 0; i < rows.length; i++) {
        var item = rows[i], rowIndex = $(el.tb).datagrid('getRowIndex', rows[i]);

        $(el.tb).datagrid('endEdit', rowIndex);
        var obj = {};
        obj.version = item.version;
        obj.detailId = item.detailId;
        obj.productCode = item.productCode;
        obj.productName = item.productName;
        obj.planNum = item.planNum;
        obj.supplierCode = item.supplierCode;
        obj.supplierName = item.supplierName;
        obj.applyNum = item.oriQuota;
        obj.distributeNum = item.adjustmentNum;
        obj.adjustmentReason = item.adjustmentReason;
        obj.remark = item.remark;
        submitData.push(obj);
    }

    var load = topWin.layer.load(0);
    $.ajax({
        type: 'POST',
        url: g.ctx + 'pc/order/basicPlan/rest/save/release/data',
        data: {
            planId: $(el.planId).val(),
            data: JSON.stringify(submitData)
        },
        success: function () {
            topWin.layer.close(load);
            $(el.tb).datagrid('reload');
            callback();
        },
        error: function (data) {
            topWin.layer.close(load);
            topWin.layer.alert(data.responseJSON.message, {icon: 2});
        }
    });
}


/**
 * 数据查询
 */
function dataQuery() {
    var queryParams = $(el.tb).datagrid('options').queryParams;
    queryParams.product = $.trim($(el.product).val());
    queryParams.supplier = $.trim($(el.supplier).val());
    queryParams.quotaQuery = $(el.quotaQuery).val();
    queryParams.purchaseGroup = $(el.purchaseGroup).val();
    $(el.tb).datagrid('load');
}


/**
 * 重置查询
 */
function resetQuery() {
    $(el.product).val('');
    $(el.supplier).val('');
    $(el.quotaQuery).val('');
    $(el.purchaseGroup).combobox('setValue', '');

    dataQuery();
}

/**
 * 数据导出
 */
function gysgl_derive() {
    var planId = $(el.planId).val();
    var purchaseGroup = $(el.purchaseGroup).val();

    var queryParams = $('#searchForm').serializeJson();
    var url = g.ctx + "pc/order/basicPlan/rest/deriveData?planId=" + planId +
        '&purchaseGroup=' + purchaseGroup;

    setTimeout(function () {
        window.open(url);
    }, 500);
}


/**
 * 数据导入
 */
function gysgl_upload() {
    debugger;
    var url = g.ctx + 'pc/order/basicPlan/uploadData';
    openLayerWin(common_layer_title.require_upload, url, '500px', '400px');
}


/**
 * 数据导入回调
 */
function updateDate(datas) {
    debugger;
    dataQuery();
    layer.close(layer.index);
}

/**
 * 结束编辑
 *
 * @param tbDom 数据表格HTML中的DOM节点
 * @return {boolean}
 */
function endEditor(tbDom) {
    $(tbDom).datagrid('endEdit', el.editIndex);
    el.editIndex = undefined;
    return true;
}


/**
 * 自动合并单元格
 */
function autoMergeCells(tableDom) {
    // tableDom 表格HTML中DOM; judge 判断条件
    var judge = 'detailId';
    var field_arr = ['productCode', 'productName', 'planNum', 'onOrderNum', 'factoryCode'];

    var rows = $(tableDom).datagrid('getRows');
    if (NULL(field_arr) || NULL(rows)) {
        return;
    }
    for (var i = 1; i < rows.length; i++) {
        for (var k = 0; k < field_arr.length; k++) {
            // 要排序的字段
            var field = field_arr[k];
            // 相邻的上下两行
            if (rows[i][field] === rows[i - 1][field]) {
                if (NOTNULL(judge)) {
                    if (rows[i][judge] !== rows[i - 1][judge]) {
                        continue;
                    }
                }
                var rowSpan = 2;
                // 判断上下多行内容一样
                for (var j = 2; i - j >= 0; j++) {
                    if (rows[i][field] !== rows[i - j][field]) {
                        break;
                    } else {
                        if (NOTNULL(judge)) {
                            if (rows[i][judge] !== rows[i - j][judge]) {
                                break;
                            }
                        }
                        rowSpan = j + 1;
                    }
                }
                // 合并
                $(tableDom).datagrid('mergeCells', {
                    index: i - rowSpan + 1,
                    field: field,
                    rowspan: rowSpan
                });
            }
        }
    }
}


/**
 * 判断字符串不为空
 *
 * @return {boolean}
 */
function NOTNULL(obj) {
    return !(typeof (obj) === 'undefined' || obj === '' || obj == null || obj === 'null');
}


/**
 * 判断字符串为空
 *
 * @return {boolean}
 */
function NULL(obj) {
    return typeof (obj) === 'undefined' || obj === '' || obj == null || obj === 'null';
}