/**
 * 交付模块-标准预测计划发布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',//采购组
    shortageQuantity: '#shortageQuantity',//欠料数量非0 0 0全部
    demandStartDate: '#demandStartDate',//需求日期(起)
    demandEndDate: '#demandEndDate',
    factory: '#factory',//工厂
    quotaQuery: '#quotaQuery',//配额
    supplierFlag: '#supplierFlag',//是否已分配供应商
    deployFlag: '#deployFlag',//是否已发布
    dataType: '#dataType',//分配类型
    exportType: '#exportType',//导出类型
    planTotalNum: '#planTotalNum',
    adTotalNum: '#adTotalNum',
    unAdTotalNum: '#unAdTotalNum',
    workOrderNumber: '#workOrderNumber',
    deployToSupplier: '#deployToSupplier',
    tb: '#tb',
    editIndex: undefined,
    arData: [],
    bodyHeight: document.documentElement.clientHeight
};

$(function () {
    initDict("shortage_adjustment_reason")
    initNecessaryDatas('pc/sys/purchaseGroup/rest/listAll');
    initPageDataGird();
});


function initPageDataGird() {
    var planId = $(el.planId).val();
    var searchHeight = $(el.searchForm).outerHeight() + 52;
    var pager = initGridPagerNew(el.bodyHeight - searchHeight, 37, 30);
    $(el.tb).edatagrid({
        loadMsg: '数据远程载入中,请等待...',
        url: g.ctx + 'pc/order/shortagePlan/rest/getToPublishedData?planId=' + planId,
        height: el.bodyHeight - searchHeight,
        singleSelect: false,
        method: "GET",
        autoSave: true,
        rownumbers: true,
        pagination: true,
        pageSize: pager.pageSize,
        pageList: pager.pageList,
        toolbar: [
            // {
            //     text: '补充供应商导出',
            //     iconCls: 'icon-print',
            //     handler: function () {
            //         openExportDialog('pc/order/shortagePlan/rest/exportToFillSupplier', "tb", searchParams())
            //     }
            // }, {
            //     text: '补充供应商导入',
            //     iconCls: 'icon-import',
            //     handler: function () {
            //         $(el.tb).edatagrid("saveRow")
            //         $("#fillSupplierUpload .filebox-label").click();
            //     }
            // },
            // {
            //     text: '上线日期导入',
            //     iconCls: 'icon-import',
            //     handler: function () {
            //         $(el.tb).edatagrid("saveRow")
            //         $("#fillDateUpload .filebox-label").click();
            //     }
            // },
            {
                text: '批量补充供应商',
                iconCls: 'icon-edit',
                handler: function () {
                    $(el.tb).edatagrid("saveRow")
                    var rows = $(el.tb).edatagrid("getChecked")
                    if (rows.length <= 0) {
                        topWin.layer.alert("请选中至少一条数据!", {icon: 3});
                        return;
                    }
                    var supplierDialogElement = openDialog("supplierDialog", g.ctx + "pc/supplier/supplierSelect?single=1", {
                        title: "供应商选择",
                        width: '800',
                        height: '80%',
                        cache: false,
                        modal: true,
                        border: false,
                        draggable: false,
                        shadow: false,
                        onClose: function () {
                            supplierDialogElement.dialog('destroy');
                        },
                        buttons: [{
                            text: '保存', iconCls: 'icon-save', handler: function () {
                                topWin.frames['supplierDialog'].chooseRow(function (row) {
                                    console.log(row)
                                    var load = topWin.layer.load(0, {
                                        shade: [0.6, '#eee'] //0.1透明度的白色背景
                                    });
                                    var postRows = []
                                    for (let i = 0; i < rows.length; i++) {
                                        // 注意这个地方使用供应商名称存编码，后台有特殊处理
                                        // 注意这个地方使用供应商名称存编码，后台有特殊处理
                                        // 注意这个地方使用供应商名称存编码，后台有特殊处理
                                        // 注意这个地方使用供应商名称存编码，后台有特殊处理
                                        // 注意这个地方使用供应商名称存编码，后台有特殊处理
                                        // 注意这个地方使用供应商名称存编码，后台有特殊处理
                                        postRows.push({
                                            id: rows[i].id,
                                            supplierName: row.supplierCode
                                        })
                                    }
                                    $.ajax({
                                        url: g.ctx + 'pc/order/shortagePlan/rest/batchFillSupplier',
                                        method: "POST",
                                        contentType: 'application/json',
                                        data: JSON.stringify(postRows),
                                        complete: function () {
                                            topWin.layer.close(load)
                                        },
                                        success: function (data) {
                                            supplierDialogElement.dialog('close');
                                            topWin.layer.msg("操作成功", {icon: 1});
                                            $(el.tb).datagrid("reload")
                                        },
                                        error: function (data) {
                                            topWin.layer.alert(data.responseJSON.message, {icon: 2});
                                        }
                                    });

                                });
                            }
                        }, {
                            text: '关闭', iconCls: 'icon-cancel', handler: function () {
                                supplierDialogElement.dialog('close');
                            }
                        }]
                    })
                }
            }
        ],
        columns: [
            [
                {
                    field: 'ck',
                    checkbox: true
                },
                {
                    title: "欠料版本",
                    width: 100,
                    field: "shortageVersion",sortable: true
                },
                {
                    title: "工单号",
                    width: 100,
                    field: "workOrderNumber",sortable: true
                },
                {
                    title: "产品料号",
                    width: 100,
                    field: "productCode",sortable: true
                },
                {
                    title: "产品描述长文本",
                    width: 100,
                    field: "productLongName"
                },
                {
                    title: "工厂",
                    width: 100,
                    field: "factoryCode",sortable: true
                },
                {
                    title: "物料编号",
                    width: 100,
                    field: "materialCode",sortable: true
                },
                {
                    title: "物料描述（长描述）",
                    width: 100,
                    field: "materialLongName"
                },
                {
                    title: "物料组",
                    width: 100,
                    field: "materialGroup"
                },
                {
                    title: "物料组描述",
                    width: 100,
                    field: "materialGroupName"
                },
                {
                    title: "需求数量",
                    width: 100,
                    field: "demandQuantity",sortable: true
                },
                {
                    title: "物料异常",
                    width: 100,
                    field: "zyichng"
                },
                {
                    title: "现有量",
                    width: 100,
                    field: "currentQuantity"
                },
                {
                    title: "冻结库存",
                    width: 100,
                    field: "frozenInventory"
                },
                {
                    title: "不良品仓数量",
                    width: 100,
                    field: "defectiveWarehouseQuantity",sortable: true
                },
                {
                    title: "质量检验",
                    width: 100,
                    field: "qualityInspection",sortable: true
                },
                {
                    title: "质检冻结库存",
                    width: 100,
                    field: "checkFrozenInventory",sortable: false
                },
                {
                    title: "请购数量",
                    width: 100,
                    field: "purchaseRequestQuantity",sortable: true
                },
                {
                    title: "采购未交数量",
                    width: 100,
                    field: "undeliveredPurchaseQuantity",sortable: true
                },
                // {
                //     title: "总缺料数量",
                //     width: 100,
                //     field: "detailShortageQuantity"
                // },
                {
                    title: "缺料数量",
                    color: 13,
                    width: 100,
                    field: "shortageQuantity",sortable: true
                },
                {
                    title: "合计缺料数",
                    width: 100,
                    field: "totalShortageQuantity",sortable: true
                },
                {
                    title: "需求日期",
                    width: 100,
                    color: 13,
                    field: "demandDate",sortable: true,
                    exportDateFormatter: "yyyy-MM-dd",
                    formatter: function (value) {
                        if (value !== '') {
                            return moment(value).format("YYYY-MM-DD")
                        }
                        return value
                    }
                },
                {
                    title: "<span style='color: red'>*</span>上线日期",
                    width: 100,
                    field: "launchDate",sortable: true,
                    exportDateFormatter: "yyyy-MM-dd",
                    formatter: function (value) {
                        if (value !== '') {
                            return moment(value).format("YYYY-MM-DD")
                        }
                        return value
                    }
                },
                {
                    title: "<span style='color: red'>*</span>备注(上线日期)",
                    width: 100,
                    field: "launchDateRemark"
                },
                {
                    title: "采购组",
                    width: 100,
                    field: "purchaseGroup",sortable: true,
                    formatter: function (value) {
                        return getNecessaryDataName('pc/sys/purchaseGroup/rest/listAll', value);
                    }
                },
                {
                    title: "<span style='color: red'>*</span>供应商编码",
                    width: 100,
                    field: "supplierCode",sortable: true
                },
                {
                    title: "供应商",
                    width: 100,
                    field: "supplierName",sortable: true
                },
                {
                    title: "配额",
                    width: 100,
                    field: "quota"
                },
                {
                    title: "后继物料",
                    width: 100,
                    field: "successorMaterial",sortable: true
                },
                {
                    title: "后继物料未交数量",
                    width: 100,
                    field: "successorMaterialUndeliveredQuantity"
                },
                {
                    title: "替代料1",
                    width: 100,
                    field: "substituteMaterial1"
                },
                {
                    title: "替代料1库存",
                    width: 100,
                    field: "substituteMaterial1Inventory",sortable: true
                },
                {
                    title: "替代料2",
                    width: 100,
                    field: "substituteMaterial2"
                },
                {
                    title: "替代料2库存",
                    width: 100,
                    field: "substituteMaterial2Inventory",sortable: true
                },
                {
                    title: "替代料3",
                    width: 100,
                    field: "substituteMaterial3"
                },
                {
                    title: "替代料3库存",
                    width: 100,
                    field: "substituteMaterial3Inventory",sortable: true
                }
            ]
        ],
        onEdit: function (index) {
            el.editIndex = index;
        },
        onLoadSuccess: function () {
            $(el.tb).datagrid('clearSelections');
        }
    });
}

/**
 * 调整原因选择其他时 备注必填
 *
 * @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});
        }
    }

}

function doResetSearch() {
    $('#searchForm').form("clear");
    $('input').not('[type="radio"]').val('');
    $('.Wdate').val('');
    $('.select2').val('0');
    //遍历所有select2重置
    $('.select2').each(function () {
        $(this).val(null).trigger("change");
    });
    $('deployToSupplier').val("1");
    if (planId) {
        $('#planId').val(planId);
    }
    $('#tb').datagrid('options').queryParams = $('#searchForm').serializeJson();
    $('#tb').datagrid('load');
}

function setRadioCheckedValue(radioGroupName, valueToCheck) {
    var radios = document.getElementsByName(radioGroupName);
    // for (var i = 0; i < radios.length; i++) {
    //     if (radios[i].value === valueToCheck) {
    //         radios[i].checked = true;//不生效
    //         break;
    //     }
    // }
}


/**
 * 保存发布数据
 *
 * @param callback 回调函数
 */
function saveReleaseData(callback) {
    var supplier = $(el.supplier).val();
    var product = $(el.product).val();
    var purchaseGroup = $(el.purchaseGroup).val();
    var workOrderNumber = $(el.workOrderNumber).val();
    var deployToSupplier = $(el.deployToSupplier).val();
    // var factory = $(el.factory).val();
    if (!supplier && !purchaseGroup && !product && !workOrderNumber) {
        topWin.layer.msg('请至少选择一个发布条件！(采购组、供应商、物料信息、工单)');
        return false;
    }
    //var postData = {
        //supplier: supplier,
        //purchaseGroup: purchaseGroup,

        //planId: $("#planId").val()
    //}
    let postData = $(el.searchForm).serializeJson();
    let confirmStr = "发布给供应商?";
    if (!deployToSupplier) {
        topWin.layer.msg('请选择是否发布供应商！');
        return false;
    }
    //重置后，无法抓取到form的planId 值。
    postData.planId = planId;

    if(deployToSupplier === "1") {
        // alert(deployToSupplier);
    } else {
        confirmStr = "不发布给供应商?"
    }

    topWin.layer.confirm(confirmStr, {icon: 3}, function (index) {
        let loadIndex = topWin.layer.load(0);
        $.ajax({
            type: 'POST',
            url: g.ctx + 'pc/order/shortagePlan/rest/published',
            contentType: 'application/json',
            data: JSON.stringify(postData),
            complete: function () {
                topWin.layer.close(loadIndex);
            },
            success: function () {
                topWin.layer.msg('发布成功');
                $(el.tb).datagrid('load');
                // topWin.layer.alert("发布成功", {icon: 1}, function (idx) {
                //     // topWin.layer.close(loadIndex);
                //     $(el.tb).datagrid('load');
                // });
                // callback();
                // $(el.tb).edatagrid("reload")
            },
            error: function (data) {
                topWin.layer.close(loadIndex);
                topWin.layer.alert(data.responseJSON.message, {icon: 2});
            }
        });
    })
}

/**
 * 数据导出
 */
function gysgl_derive() {
    var params = searchParams();
    params.planId = planId;
    var tableData = getExcelKeyTitle("tb");
    xhrPostExport('pc/order/shortagePlan/rest/exportToPublishedData',  params,tableData)
}


function gysgl_upload() {
    $(el.tb).edatagrid("saveRow")
    $("#detailUpload .filebox-label").click();
}


/**
 * 数据导入回调
 */
function dataImport() {
    var files = $("#detailFileInput").filebox('files'), formData = new FormData();
    if (files.length != 1) {
        return
    }
    formData.append('file', files[0]);
    let loadIndex = topWin.layer.load(0);
    var url = g.ctx + 'pc/order/shortagePlan/rest/importForPublished'
    $.ajax({
        url: url, type: 'POST', data: formData, processData: false,
        contentType: false,
        async: true, // 设置为同步请求
        complete: function () {
            $("#detailFileInput").filebox('clear')
            topWin.layer.close(loadIndex);
        },
        success: function (data) {
            // topWin.layer.msg("导入成功", {icon: 1});
            // topWin.layer.msg(data, {icon: 1});
            topWin.layer.alert(data, {icon: 1});
            $(el.tb).datagrid("reload")
        }, error: function (data) {
            topWin.layer.alert(data.responseJSON.message, {icon: 2});
        }
    });
}

function fillSupplierImport() {
    var files = $("#fillSupplierFileInput").filebox('files'), formData = new FormData();
    if (files.length != 1) {
        return
    }
    formData.append('file', files[0]);
    let loadIndex = topWin.layer.load(0);
    var url = g.ctx + 'pc/order/shortagePlan/rest/importForFillSupplier'
    $.ajax({
        url: url, type: 'POST', data: formData, processData: false,
        contentType: false,
        async: true, // 设置为同步请求
        complete: function () {
            $("#fillSupplierFileInput").filebox('clear')
            topWin.layer.close(loadIndex);
        },
        success: function (data) {
            topWin.layer.msg("操作成功", {icon: 1});
            $(el.tb).datagrid("reload")
        }, error: function (data) {
            topWin.layer.alert(data.responseJSON.message, {icon: 2});
        }
    });
}

function fillDateImport() {
    var files = $("#fillDateFileInput").filebox('files'), formData = new FormData();
    if (files.length != 1) {
        return
    }
    formData.append('file', files[0]);
    let loadIndex = topWin.layer.load(0);
    var url = g.ctx + 'pc/order/shortagePlan/rest/importForFillDate'
    $.ajax({
        url: url, type: 'POST', data: formData, processData: false,
        contentType: false,
        async: true, // 设置为同步请求
        complete: function () {
            $("#fillDateFileInput").filebox('clear')
            topWin.layer.close(loadIndex);
        },
        success: function (data) {
            topWin.layer.msg("操作成功", {icon: 1});
            $(el.tb).datagrid("reload")
        }, error: function (data) {
            topWin.layer.alert(data.responseJSON.message, {icon: 2});
        }
    });
}

/**
 * 结束编辑
 *
 * @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 = ['materialCode', 'materialName', 'detailShortageQuantity', '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';
}