var el = {
    tb: '#tb',
    dataPanel: '#dataPanel',
    dataDiv: '#dataDiv',
    componentTb: '#component_tb',
    planTb: '#plan_tb',
    costTb: '#cost_tb',
    bodyHeight: document.documentElement.clientHeight,
    dataForm: '#dataForm',
    editIndex: undefined,
    addIndex: undefined
};
var submitFlag = 0
var cacheData = {}
var editIndex = undefined
$(function () {
    $(el.dataPanel).panel({
        collapsible: true,
        onCollapse: function () {
            $(el.tb).datagrid('resize', {height: el.bodyHeight - 80});
        },
        onExpand: function () {
            $(el.tb).datagrid('resize', {height: el.bodyHeight - 300});
        }
    });
    initDict("po_item_type,unit")
    initNecessaryDatas('pc/sys/tax/rest/listAll')
    initNecessaryDatas('pc/sys/factory/rest/listAll')
    loadGrid();
    initOrderFileTb();
    initPlanGrid();
    initCostGrid();
});

function loadGrid() {
    var columns = [
        {
            field: 'unitCode', sortable: true, title: '订单单位<span style="color: red">*</span>',
            width: '90', align: 'left',
            formatter: function (value) {
                return getDicName("unit", value);
            }
        },
        {
            field: 'num', sortable: true, title: '订单数量<span style="color: red">*</span>',
            width: '90', align: 'left'
        },
        {
            field: 'price', sortable: true, title: '含税单价<span style="color: red">*</span>',
            width: '90', align: 'left'
        },
        {
            field: 'taxCode', sortable: true, title: '税率<span style="color: red">*</span>',
            width: '80', align: 'left',
            formatter: function (value) {
                return getNecessaryDataName("pc/sys/tax/rest/listAll", value);
            }
        },
        {
            field: 'sumTaxMoney', title: '含税金额', sortable: true,
            width: '80', align: 'left'
        },
        {
            field: 'originalRequireDate', title: '原始需求日期', sortable: true,
            width: '100', align: 'left',
            formatter: function (value) {
                if (value) {
                    return new Date(value).format("yyyy-MM-dd");
                }
                return value;
            }
        },
        {
            field: 'requireDate', sortable: true,
            title: '需求日期', width: '80', align: 'left'
        },

        {
            field: 'replayRequireDate', sortable: true,
            title: '回复交期', width: '80', align: 'left',
            formatter: function (value) {
                if (value !== '') {
                    return moment(value).format('YYYY-MM-DD');
                }
                return ''

            }
        },
        {
            field: 'factoryCode', title: '收货工厂<span style="color: red">*</span>',
            width: '80', align: 'left', sortable: true,
            formatter: function (value) {
                return getNecessaryDataName("pc/sys/factory/rest/listAll", value)
            }

        },
        {
            field: 'purchaseApplyDeatilId', sortable: true, title: '采购申请明细的id', hidden: true,
            width: '120', align: 'left'
        },
        {
            field: 'purchApplyNo', title: '采购申请号', sortable: true,
            width: '70', align: 'left'
        },
        {
            field: 'purchApplyRow', title: '采购申请行', sortable: true,
            width: '70', align: 'left'
        },
        {
            field: 'shouHuoDiZhi', sortable: true,
            title: '收货地址',
            width: '100', align: 'left'

        },
        {
            field: 'rowTypeCode', title: '项目类别', sortable: true,
            width: '80', align: 'left',
            formatter: function (value) {
                return getDicName("po_item_type", value);
            }
        },
        {
            field: 'assetNo',
            title: '资产卡片号', sortable: true,
            width: 200
        },
        {
            field: 'freeFlag', title: '是否赠送', sortable: true,
            width: '60', align: 'left',
            formatter: function (value) {
                if (value == 'N') {
                    return "否"
                } else if (value == 'Y') {
                    return "是"
                }
            }
        },
        {
            field: 'finishFlag', title: '交货已完成', sortable: true,
            width: '70', align: 'left',
            formatter: function (value) {
                if (value == 'N') {
                    return "否"
                } else if (value == 'Y') {
                    return "是"
                }
            }
        },
        {
            field: 'remark', title: '订单行备注', sortable: true,
            width: '100', align: 'left'
        }
    ]
    var toolbar = [{
        text: '批量修改交期',
        iconCls: 'icon-import',
        id: 'icon_print',
        handler: function () {
            var rows = $(el.tb).datagrid('getChecked');
            let html = [];
            html.push("<form class='form form-horizontal pl-10 pr-10'>");
            html.push("<div class='ui-form-row ui-form-row-margin' style='margin-top: 10px !important;margin-bottom: 5px !important;'>");
            html.push("<table class='ui-form-table topline'>");
            html.push("    <colgroup>");
            html.push("        <col style='width:80px'>");
            html.push("        <col>");
            html.push("    </colgroup>");
            html.push("    <tbody>");
            html.push("        <tr>");
            html.push("            <td class='ui-form-row-column title required '>");
            html.push("                <span class='ui-form-item-title'>回复交期</span>");
            html.push("            </td>");
            html.push("            <td class='ui-form-row-column'>");
            html.push("                <input id='replayDate' name='replayDate' type='date' class='ui-form-item required' style='width: 100%'/>");
            html.push("            </td>");
            html.push("        </tr>");
            html.push("    </tbody>");
            html.push("</table>");
            html.push("</div>");
            html.push("</form>");
            topWin.layer.open({
                type: 1,
                area: ['420px', '200px'], // 宽高
                title: '批量修改交期', // 不显示标题栏
                closeBtn: 0,
                shadeClose: true, // 点击遮罩关闭层
                content: html.join(""),
                btn: ['确定', '关闭'],
                btn1: function (index, layero, that) {
                    let replayDate = layero.find("input[name='replayDate']").val();
                    if (!replayDate) {
                        topWin.layer.msg("请选择回复交期");
                        return;
                    }
                    //需要修改列表中的回复交期
                    $.each(rows, function (idx, itm) {
                        //更新每行的回复交期
                        let rowIndex = $(el.tb).datagrid('getRowIndex', itm);
                        $(el.tb).datagrid('updateRow', {index: rowIndex, row: {replayRequireDate: replayDate}});
                    })
                    topWin.layer.close(index);
                },
                btn2: function (index, layero, that) {
                    topWin.layer.close(index);
                },
            });
        }
    }]
    if (type === '2') {
        toolbar = []
        $.each(columns, function (idx, itm) {
            delete itm.editor
        })
    }
    var h = ((el.bodyHeight - $("#dataForm").height() - 330) * 0.75) <= 200 ? 200 : ((el.bodyHeight - $("#dataForm").height() - 330) * 0.75)
    $(el.tb).edatagrid({
        loadMsg: '数据远程载入中,请等待...',
        singleSelect: true,
        autoSave: true,
        pagination: false,
        rownumbers: true,
        height: h,
        frozenColumns: [[
            {field: 'ck', checkbox: true},
            {
                field: 'delFlag', title: '是否删除', sortable: true,
                width: '62', align: 'left',
                formatter: function (value) {
                    if (value === 0) {
                        return "否";
                    } else if (value === 1) {
                        return "<span style='color: red;'>是</span>";
                    }
                }
            },
            {
                field: 'orderRow', title: '行项目', sortable: true,
                width: '50', align: 'left'
            },
            {
                field: 'returnFlag', sortable: true,
                title: '是否退货',
                width: 80,
                formatter: function (value) {
                    if (value === 'X') {
                        return "是"
                    } else {
                        return "否"
                    }
                }
            },
            {
                field: 'materialCode', title: '物料编码', sortable: true,
                width: '90', align: 'left'
            },
            {
                field: 'materialName', sortable: true, title: '物料名称<span style="color: red">*</span>',
                width: '90', align: 'left'
            },
            // {
            //     field: 'specs', title: '规格',
            //     width: '90', align: 'left'
            // },
            // {
            //     field: 'brand', title: '品牌',
            //     width: '90', align: 'left'
            // }
        ]],
        columns: [columns],
        onCheck: function (index, rowData) {
            loadPlanData(rowData);
            loadCostData(rowData);
        },
        // toolbar: toolbar
    });
   debugger;
    let url = g.ctx + 'pc/order/purchaseOrderDetail/rest/list?delFlag=0&orderId=' + id+"&supplierCode1="+supplierCode1;
    $.ajax({
        url: url,
        type: 'GET',
        success: function (data) {
            var rows = []
            //需要判断是否是拆行答交

            $.each(data.rows, function (idx, itm) {
                if (itm.replayNum === "") {
                    itm.replayNum = itm.num;
                }
                if (type === '2') {
                    if (itm.finishFlag !== 'Y') {
                        rows.push(itm)
                    }
                } else {
                    rows.push(itm)
                }
            })
            $(el.tb).edatagrid('loadData', rows);
        },
        error: function (data) {
            topWin.layer.alert(data.responseJSON.message, {icon: 2});
        }
    });
}

function loadPlanData(rowData) {
    if (cacheData[rowData.orderRow] !== undefined) {
        $(el.planTb).datagrid('loadData', cacheData[rowData.orderRow]);
    } else {
        let load = topWin.layer.load(0);
        $.ajax({
            url: g.ctx + 'pc/order/purchaseOrderDetail/rest/planList',
            method: "GET",
            data: {orderCode: rowData.orderCode, row: rowData.orderRow},
            complete: function () {
                topWin.layer.close(load)
            },
            success: function (data) {
                cacheData[rowData.orderRow] = data.rows;
                $(el.planTb).datagrid('loadData', data.rows);
            },
            error: function (data) {
                topWin.layer.alert(data.responseJSON.message, {icon: 2});
            }
        });
    }

}

function loadCostData(rowData) {
    if (cacheData[rowData.orderRow] !== undefined) {
        $(el.costTb).datagrid('loadData', cacheData[rowData.orderRow]);
    } else {
        let load = topWin.layer.load(0);
        $.ajax({
            url: g.ctx + 'pc/order/purchaseOrderDetail/rest/costList',
            method: "GET",
            data: {orderCode: rowData.orderCode, row: rowData.orderRow},
            complete: function () {
                topWin.layer.close(load)
            },
            success: function (data) {
                $(el.costTb).datagrid('loadData', data.rows);
            },
            error: function (data) {
                topWin.layer.alert(data.responseJSON.message, {icon: 2});
            }
        });
    }

}

function savePlan(callback) {
    // 关闭明细行编辑
    // if (editIndex !== undefined) {
    //     var isValid = $(el.planTb).datagrid('validateRow', editIndex);
    //     if (!isValid) {
    //         topWin.layer.msg("交货计划未填写不完整")
    //         return
    //     }
    // }
    $(el.planTb).edatagrid("saveRow");
    var orderRows = $(el.tb).datagrid("getRows");
    let tipMsg = []
    // $.each(orderRows, function (idx, itm) {
    //     if (cacheData[itm.orderRow] === undefined) {
    //         tipMsg.push("订单行:" + itm.orderRow + ",交货计划未填写")
    //     }
    // })
    // 遍历 orderRows 数组
    let detailCache = {}
    for (var i = 0; i < orderRows.length; i++) {
        detailCache[orderRows[i].orderRow] = orderRows[i].num
    }
    let rows = []
    //需要统计数量
    $.each(cacheData, function (idx, itm) {
        //需要判断数量问题
        let num = detailCache[idx]
        let tt = 0
        $.each(itm, function (iid, iit) {
            if (iit['scheduleDeliveryQuantity'] === '' || iit['scheduleDeliveryDate'] === '') {
                tipMsg.push("订单行:" + iit.lineItem + ",交货计划未填写")
            }
            if (iit['delFlag'] === 0) {
                tt = tt + parseFloat(iit['scheduleDeliveryQuantity'])
            }
            //需要判断计划行接收数量和交货计划数量
            //需要判断计划行接收数量和交货计划数量
            var receivedQuantity = parseFloat(iit['receivedQuantity']);
            var scheduleDeliveryQuantity = parseFloat(iit['scheduleDeliveryQuantity']);
            // 检查是否成功转换为数字
            if (!isNaN(receivedQuantity) && !isNaN(scheduleDeliveryQuantity)) {
                // 现在可以进行比较
                if (receivedQuantity > scheduleDeliveryQuantity) {
                    tipMsg.push("订单行:" + iit.lineItem + ",交货行:" + iit.scheduleLine + "计划交货数量不得小于计划行接收数量");
                }
            }
        })

        //tipMsg.push("订单行:" + idx + ",交货计划数量跟订单数量不一致, 计划交货数：" + tt.toFixed(2) + "/订单数量:" + (num.toFixed(2)) + (tt.toFixed(2) - num.toFixed(2)))

        if (tt.toFixed(2) !== num.toFixed(2)) {
            //计算订单数量是否与计划交货数量一致。
            tipMsg.push("订单行:" + idx + ",交货计划数量跟订单数量不一致,差额为：" + (num.toFixed(2) - tt.toFixed(2)));
        }
        let items = itm.filter(item => !(item.id === undefined && item.delFlag === 1));
        console.log(items)
        rows = rows.concat(items)
    })
    if (tipMsg.length !== 0) {
        topWin.layer.alert(tipMsg.join("</br>"), {icon: 3})
        return
    }
    if (submitFlag === 1) {
        return;
    }
    submitFlag = 1
    let load = topWin.layer.load(0);
    $.ajax({
        type: "post",
        url: g.ctx + "pc/order/purchaseOrder/rest/sumbitDevPlan",
        contentType: "application/json",
        data: JSON.stringify(rows),
        complete: function () {
            topWin.layer.close(load);
            submitFlag = 0
        },
        success: function (data) {
            topWin.layer.alert("保存成功", {icon: 1}, function (idx) {
                topWin.layer.close(idx);
                callback();
            });
        },
        error: function (data) {
            topWin.layer.alert(JSON.parse(data.responseText).message);
        }
    });
}

function save(callback) {
    if (submitFlag === 1) {
        return;
    }
    // 关闭明细行编辑
    $(el.tb).edatagrid("saveRow");
    var rows = $(el.tb).datagrid("getRows");
    //需要判断订单文件是否上传了
    let tipMsg = [];
    if (rows.length === 0) {
        // topWin.layeralert('请等待数据加载完成后再点击确认', {icon: 0});
        // return false;
    } else {

        for (let i = 0; i < rows.length; i++) {
            let pre = "第" + (i + 1) + "行明细，";
            var rowDemo = rows[i];

            if (!rowDemo.replayNum) {
                topWin.layer.alert(pre + "“回复数量”不可为空", {time: 2000});
                return false;
            }
            if (rowDemo.markCount) {
                if (rowDemo.replayNum && rowDemo.replayNum != rowDemo.markCount) {
                    tipMsg.push(pre + "“回复数量”和“订单数量”不等");
                }
            } else {
                if (rowDemo.replayNum && rowDemo.noClearNum && rowDemo.replayNum != rowDemo.noClearNum) {
                    tipMsg.push(pre + "“回复数量”和“订单数量”不等");
                }
            }
        }
    }

    let load = topWin.layer.load(0);
    submitFlag = 1
    $.ajax({
        type: "post",
        url: g.ctx + "pc/order/purchaseOrder/rest/sumbitReply",
        contentType: "application/json",
        data: JSON.stringify(rows),
        complete: function () {
            topWin.layer.close(load);
            submitFlag = 0
        },
        success: function (data) {
            topWin.layer.alert("保存成功", {icon: 1}, function (idx) {
                topWin.layer.close(idx);
                callback();
            });
        },
        error: function (data) {
            topWin.layer.alert(JSON.parse(data.responseText).message, {icon: 2});
        }
    });
}

function postRefusal(remark, id, callback) {
    $.ajax({
        type: "post",
        url: g.ctx + "pc/order/purchaseOrder/rest/refusal",
        data: {remark: remark, id: id},
        complete: function () {
            submitFlag = 0
        },
        success: function (data) {
            topWin.layer.alert("保存成功", {icon: 1}, function (idx) {
                topWin.layer.close(idx);
                callback();
            });
        },
        error: function (data) {
            topWin.layer.alert(JSON.parse(data.responseText).message, {icon: 2});
        }
    });
}

function refusal(callback) {
    if (submitFlag === 1) {
        return;
    }
    // 关闭明细行编辑
    $(el.tb).edatagrid("saveRow");
    topWin.layer.prompt({title: '请输入拒收原因', formType: 2}, function (value, index, elem) {
        if (value === '') {
            topWin.layer.msg("请输入拒收原因")
            return
        }
        postRefusal(value, id, function () {
            topWin.layer.close(index);
            callback()
        })

    });

}

function initOrderFileTb() {
    var toolbar;
    if (isSupplier === 1) {
        toolbar = [{
            text: BJGL.BJGL__SC,
            iconCls: 'icon-add',
            hidden: true,
            handler: function () {
                $("#fileUpload").find('.filebox-label').click();
            }
        }];
    } else {
        toolbar = [{
            text: BJGL.BJGL__SC,
            iconCls: 'icon-add',
            hidden: true,
            handler: function () {
                $("#fileUpload").find('.filebox-label').click();
            }
        }, "-", {
            text: BJGL.BJGL__SHANC,
            iconCls: 'icon-remove',
            handler: function () {
                topWin.layer.confirm('确定要删除选中的附件吗?', {icon: 3}, function (index) {
                    var rows = $("#file_table").datagrid("getChecked");
                    $.ajax({
                        type: 'post',
                        url: g.ctx + 'pc/order/purchaseOrder/rest/removeAttachment',
                        data: {
                            ids: rows[0].id
                        },
                        async: false,
                        success: function () {
                            topWin.layer.close(index);
                            topWin.layer.msg('保存成功', {icon: 1});
                            $("#file_table").datagrid('reload');
                        },
                        error: function (data) {
                            topWin.layer.alert(data.responseJSON.message, {icon: 2});
                        }
                    });
                })
            }
        }];
    }
    var url = g.ctx + 'pc/order/purchaseOrder/rest/attachmentList?ids=' + id;
    // 加载附件列表
    $("#file_table").datagrid({
        url: url,
        height: 200,
        method: "GET",
        width: gridwidth,
        singleSelect: true,
        pagination: false,
        autoHeight: true,
        loadMsg: ALLCOMMON.LOADING,
        rownumbers: true,
        fitColumns: false,
        nowrap: true,
        remoteSort: true,
        striped: true,
        columns: [
            [
                {
                    field: 'ck',
                    checkbox: true
                },
                {
                    field: 'fileName',
                    title: BJGL.BJGL__FJM,
                    width: '60%'
                },
                {
                    field: 'fileId',
                    title: BJGL.BJGL__XZ,
                    width: '35%',
                    formatter: function (value, row, index) {
                        return "<a href='" + g.ctx + "pc/sys/file/rest/download/" + value + "'>" + row.fileName + "</a>";
                    }
                }
            ]
        ],
        toolbar: toolbar
    });
}

function uploadOrderFile() {
    var addFiles = [];
    var files = $("#fileInput").filebox('files'), formData = new FormData()
    for (var r = 0; r < files.length; r++) {
        addFiles.push(files[r]);
    }
    for (var n = 0; n < addFiles.length; n++) {
        formData.append('files', addFiles[n]);
    }
    if (addFiles.length > 0) {
        fileUploadAjaxWithCall(formData, function (rows) {
            const postData = []
            $.each(rows, function (idx, itm) {
                postData.push({
                    fileId: itm.id,
                    masterId: id
                })
            })
            $.ajax({
                url: g.ctx + 'pc/order/purchaseOrder/rest/saveAttachment',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(postData),
                success: function () {
                    topWin.layer.msg('保存成功', {icon: 1});
                    $("#file_table").datagrid('reload');
                },
                error: function (data) {
                    topWin.layer.alert(data.responseJSON.message, {icon: 2});
                }
            });
        }, true)
        $("#fileInput").filebox('clear')
    }
}

function initPlanGrid() {
    var columns = [{field: 'ck', checkbox: true},
        {
            field: 'delFlag', title: '是否删除',
            width: '105', align: 'left', sortable: true,
            formatter: function (value, row) {
                if (value === 1) {
                    return '<span style="color: red;">是</span>'
                }
                return '否'
            }
        },
        {
            field: 'purchaseOrder', title: '采购订单号', sortable: true,
            width: '105', align: 'left'
        },
        {
            field: 'lineItem', title: '采购订单行号', sortable: true,
            width: '90', align: 'left'
        }, {
            field: 'scheduleLine', title: '计划行号', sortable: true,
            width: '90', align: 'left'
        }, {
            field: 'lastRequireDate', title: '需求日期', sortable: true,
            width: '90', align: 'left',
            formatter: function (value) {
                if (value) {
                    return new Date(value).format("yyyy-MM-dd");
                }
                return value;
            }
        },
        {
            field: 'scheduleDeliveryDate', title: '计划交货日期', sortable: true,
            width: '110', align: 'left',
            editor: {
                type: 'datebox',
                options: {
                    required: true,
                    editable: true,
                    parser: function (value) {
                        if (value) {
                            return new Date(value);
                        } else {
                            return new Date();
                        }
                    },
                    // 验证选择时间 <= 今天
                    onShowPanel: function () {
                        $(this).datebox('calendar').calendar({
                            validator: function (date) {
                                //并且还有当年的1月2号
                                var dateToCheck = moment(date);
                                // 获取当前日期
                                let today = moment().subtract(1, 'days');
                                // 判断是否是今天之后
                                let isAfterToday = dateToCheck.isAfter(today, 'day');
                                // 获取今年的1月2号
                                let jan2ThisYear = moment().startOf('year').add(1, 'days');
                                let isJan2ThisYear = dateToCheck.isSame(jan2ThisYear, 'day');
                                return true || isJan2ThisYear
                            }
                        });
                    }
                }
            },
            formatter: function (value, row) {
                if (value) {
                    return new Date(value).format("yyyy-MM-dd");
                }
                return value;
            }
        },
        {
            field: 'scheduleDeliveryQuantity', title: '计划交货数量', sortable: true,
            width: '90', align: 'left',
            editor: {type: "numberbox", options: {required: true, min: 0, precision: 0}},
            formatter: function (value, row) {
                if (value) {
                    return value;
                }
                return "";
            }
        },
        {
            field: 'diffDays', title: '差异天数', sortable: true,
            width: '90', align: 'left',
            formatter: function (value, row) {
                if (row.scheduleDeliveryDate !== '' && row.lastRequireDate !== '') {
                    let diff = moment(row.lastRequireDate).diff(moment(row.scheduleDeliveryDate), 'days');
                    return diff + "天"
                }
                return ''
            }
        },
        {
            field: 'okStatus', title: '需求满足状态', sortable: true,
            width: '90', align: 'left',
            formatter: function (value, row) {
                if (row.scheduleDeliveryDate !== '') {
                    let diff = moment(row.lastRequireDate).diff(moment(row.scheduleDeliveryDate), 'days');
                    console.log(diff)
                    if (diff > 0) {
                        return '<span style="color: olivedrab;">OK</span>'
                    } else {
                        return '<span style="color: orangered;">NG</span>'
                    }
                }
                return '<span style="color: orangered;">NG</span>'
            }
        },

        {
            field: 'purchaseRequest', title: '采购申请', sortable: true,
            width: '90', align: 'left'
        },
        {
            field: 'purchaseRequestLine', title: '采购申请行号', sortable: true,
            width: '90', align: 'left'
        },
        {
            field: 'noClearNum', title: '未清数量',
            width: '90', align: 'left',
            formatter: function (value, row) {
                return Number(row.scheduleDeliveryQuantity) - Number(row.receivedQuantity)
            }
        },
        {
            field: 'receivedQuantity', title: '已收货数量', sortable: true,
            width: '90', align: 'left'
        },
        {
            field: 'look', title: '组件查看', sortable: true,
            width: '90', align: 'left',
            formatter: function (index, row) {
                return '<a href="javascript:void(0)" onclick="openComponentDialog(\'' + row.purchaseOrder + '\',\'' + row.lineItem + '\',\'' + row.scheduleLine + '\')">组件查看</a>';
            }
        },
        {
            field: 'day1',
            title: 'day1', sortable: true,
            width: 120
        },
        {
            field: 'day2',
            title: 'day2',
            sortable: true,
            width: 120
        },
        {
            field: 'day3',
            title: 'day3',
            sortable: true,
            width: 120
        }, {
            field: 'day4',
            title: 'day4',
            sortable: true,
            width: 120
        }, {
            field: 'day5',
            title: 'day5',
            sortable: true,
            width: 120
        },
        {
            field: 'day6',
            title: 'day6',
            sortable: true,
            width: 120
        },
        {
            field: 'day7',
            title: 'day7',
            sortable: true,
            width: 120
        },
        {
            field: 'week1',
            title: 'week1',
            sortable: true,
            width: 120
        },
        {
            field: 'week2',
            title: 'week2',
            sortable: true,
            width: 120
        },
        {
            field: 'week3',
            title: 'week3',
            sortable: true,
            width: 120
        },
        {
            field: 'week4',
            title: 'week4',
            width: 120
        }, {
            field: 'week5',
            title: 'week5',
            sortable: true,
            width: 120
        }, {
            field: 'week6',
            title: 'week6',
            sortable: true,
            width: 120
        },
        {
            field: 'week7',
            title: 'week7',
            sortable: true,
            width: 120
        },
        {
            field: 'week8',
            title: 'week8',
            sortable: true,
            width: 120
        },
        {
            field: 'month1',
            title: 'month1',
            sortable: true,
            width: 120
        },
        {
            field: 'month2',
            title: 'month2',
            sortable: true,
            width: 120
        },
        {
            field: 'month3',
            title: 'month3',
            sortable: true,
            width: 120
        }, {
            field: 'month4',
            sortable: true,
            title: 'month4',
            width: 120
        }]
    var toolbar = [{
        text: '添加',
        iconCls: 'icon-add',
        id: 'plan_add',
        handler: function () {
            let rows = $(el.tb).datagrid("getChecked")
            if (rows.length !== 1) {
                topWin.layer.msg("请选中订单行!")
                return
            }
            let row = rows[0]
            $(el.planTb).datagrid("appendRow", {
                delFlag: 0,
                receivedQuantity: 0,
                purchaseOrder: row.orderCode,
                lineItem: row.orderRow,
                purchaseRequest: row.purchApplyNo,
                purchaseRequestLine: row.purchApplyRow
            })
        }
    }, {
        text: '删除',
        iconCls: 'icon-remove',
        id: 'plan_del',
        handler: function () {
            let rows = $(el.planTb).datagrid("getChecked")
            if (rows.length !== 1) {
                topWin.layer.msg("请选中订单行!")
                return
            }
            let tipMsg = []
            $.each(rows, function (idx, itm) {
                var receivedQuantity = parseFloat(itm['receivedQuantity']);
                if (!isNaN(receivedQuantity) && receivedQuantity > 0) {
                    tipMsg.push(itm['scheduleLine'] + '行号:已存在收货数量无法删除')
                }
            })
            if (tipMsg.length > 0) {
                topWin.layer.msg(tipMsg.join('<br/>'))
                return
            }
            $.each(rows, function (idx, itm) {
                let rowIndex = $(el.planTb).datagrid("getRowIndex", itm)
                $(el.planTb).datagrid("updateRow", {index: rowIndex, row: {delFlag: 1}})
            })

        }
    }, {
        text: '取消删除',
        iconCls: 'icon-redo',
        id: 'plan_del',
        handler: function () {
            let rows = $(el.planTb).datagrid("getChecked")
            if (rows.length !== 1) {
                topWin.layer.msg("请选中订单行!")
                return
            }
            $.each(rows, function (idx, itm) {
                let rowIndex = $(el.planTb).datagrid("getRowIndex", itm)
                $(el.planTb).datagrid("updateRow", {index: rowIndex, row: {delFlag: 0}})
            })

        }
    }]
    if (type === '1') {
        toolbar = []
        $.each(columns, function (idx, itm) {
            delete itm.editor
        })
    }
    $(el.planTb).edatagrid({
        method: "GET",
        loadMsg: '数据远程载入中,请等待...',
        singleSelect: false,
        autoSave: true,
        pagination: false,
        rownumbers: true,
        height: 250,
        columns: [columns],
        onEdit: function (index) {
            editIndex = index
        },
        onSave: function () {
            let rows = $(el.planTb).datagrid("getRows")
            if (rows.length < 1) {
                topWin.layer.msg("请添加交货计划行!")
                return
            }
            let key = rows[0].lineItem
            cacheData[key] = rows
            editIndex = undefined
        },
        toolbar: toolbar
    });
}

function initCostGrid() {
    $(el.costTb).edatagrid({
        method: "GET",
        loadMsg: '数据远程载入中,请等待...',
        singleSelect: false,
        autoSave: true,
        pagination: false,
        rownumbers: true,
        height: 250,
        columns: [[
            {
                field: 'purchaseOrder', title: '采购订单号',
                width: '105', align: 'left'
            },
            {
                field: 'lineItem', title: '采购订单行号',
                width: '90', align: 'left'
            }, {
                field: 'generalLedgerAccount', title: '总账科目',
                width: '90', align: 'left'
            }, {
                field: 'costCenter', title: '成本中心',
                width: '90', align: 'left'

            }, {
                field: 'accountAssignmentNumber', title: '科目分配序号',
                width: '90', align: 'left'
            }, {
                field: 'assetCode', title: '资产编码',
                width: '90', align: 'left'
            }, {
                field: 'order_number', title: '订单',
                width: '90', align: 'left'
            }
        ]]
    });
}

function openComponentDialog(purchaseOrder, row, scheduleLine) {
    let url = g.ctx + 'pc/order/purchaseOrderDetail/page/componentList?orderCode=' + purchaseOrder + "&row=" + row + "&planLine=" + scheduleLine;
    var componentDialog = openDialog('componentDialog', url, {
            title: "查看组件数据",
            width: '800px',
            height: '600px',
            cache: false,
            modal: true,
            border: false,
            draggable: true,
            shadow: false,
            onClose: function () {
                componentDialog.dialog('destroy');
            },
            buttons: [
                {
                    text: itablei8n.close,
                    handler: function () {
                        componentDialog.dialog('close');
                    }
                }
            ]
        }
    );
}