var gridManager = null,stockGridManager = null,orgRoot = null;

$(document).ready(function () {
    initialize();
    loadGrid();
    loadStockGrid();
    bindEvent();
});
function initialize(){
    UICtrl.layout("#layout", {leftWidth: 3});
    $('#changeList').fileList({
        bizId : $("#id").val()
    });
}

function bindEvent(){

    $('#pd').searchbox({
        type: "system", name: "sapMaterialSelect",
        checkbox:true,
        checkboxIndex:"MATNR",
        textIndex:"MAKTX",
        valueIndex:"MATNR",
        getParam: function (item) {
            return {
                noWlfl1:"ZZCP",
                noWlfl2:"ZBCP"
                //filterValue:$("#brandCode").val()
            }
        },
        onChange: function (value, data) {
            var values = value.value.split(",");
            var pds = [];
            for (let i = 0; i < values.length; i++) {
                pds.push(values[i].replace(/^0+/g, ""));
            }
            $('#pd').val(pds.join(","));
            $('#productName').val(value.text);
        }
    });

    $('#changedPd').searchbox({
        type: "system", name: "sapMaterialSelect",
        checkbox:true,
        checkboxIndex:"MATNR",
        textIndex:"MAKTX",
        valueIndex:"MATNR",
        getParam: function (item) {
            return {
                noWlfl1:"ZZCP",
                noWlfl2:"ZBCP"
                //filterValue:$("#brandCode").val()
            }
        },
        onChange: function (value, data) {
            var values = value.value.split(",");
            var pds = [];
            for (let i = 0; i < values.length; i++) {
                pds.push(values[i].replace(/^0+/g, ""));
            }
            $('#changedPd').val(pds.join(","));
            $('#changedProductName').val(value.text);
        }
    });

    $("#changePerson").orgTree({
        filter: "psm", excludePos: 0, param: {orgKindId: "ogn,dpt,pos,psm"},
        back: {
            text: "#changePerson",
            value : '#changePersonId'
        },
        //manageType: 'taskQuery',
        onChange:function(value,data){
            $('#changePerson').val(data.deptName+"-"+data.name);
        }
    });

}

function loadGrid() {
    var toolbarOptions = UICtrl.getDefaultToolbarOptions({
        addHandler: function () {
            UICtrl.addGridRow(gridManager);
        },
        deleteHandler: function () {
            var _grid = UICtrl.getGridManager('#maingrid');
            DataUtil.delSelectedRows({
                action: 'epChangeForm/deleteEpChangeFormImplItem.ajax',
                param: {},
                gridManager: _grid,
                idFieldName: 'id',
                onSuccess: function () {
                    reloadGrid();
                }
            });
        }
    });
    gridManager = UICtrl.grid("#maingrid", {
        columns: [
            {
                display: "部门", name: "deptName", width: 200, minWidth: 60, type: "string", align: "left",
                // editor: {
                //     type: 'tree',
                //     required: true,
                //     data: {
                //         name: 'org',
                //         filter: 'dpt',
                //         minWidth: 250,
                //         param: {
                //             orgRoot: "14636F3F48934EE7811768692A0AC5E1"
                //         }
                //     },
                //     textField: 'deptName',
                //     valueField: 'deptId'
                // }
            },
            {
                display: "跟进事项", name: "followMatter", width: 500, minWidth: 60, type: "string", align: "left",
                editor: {
                    type: "text"
                }
            },
            {
                display: "执行人", name: "executor", width: 100, minWidth: 60, type: "string", align: "left",
                editor: {
                    type: 'tree',
                    required: true,
                    checkbox: true,
                    data: {
                        name: 'org',
                        filter: 'psm',
                        minWidth: 250,
                        param: {
                            orgRoot: "14636F3F48934EE7811768692A0AC5E1"
                        }
                    },
                    back: {
                        deptName:'deptName',
                        deptId:'deptId',
                        name: 'executor',
                        id: 'executorId'
                    },
                    // textField: 'executor',
                    // valueField: 'executorId',
                }
            },
            {
                display: "签名确认", name: "confirmTextView", width: 100, minWidth: 60, type: "string", align: "left",
                editor: {
                    type: 'dictionary',
                    data: {name: 'confirm'},
                    textField: 'confirmTextView',
                    valueField: 'confirm',
                    required: false,
                    render: function (item) {
                        return item.confirmTextView;
                    }
                },
            },
            {
                display: "日期", name: "date", width: 150, minWidth: 60, type: "dateTime", align: "left",
                editor: {
                    type: "dateTime"
                }
            },
            {
                display: "COMMENTS评论", name: "comments", width: 400, minWidth: 60, type: "string", align: "left"
            },
        ],
        dataAction: "server",
        url: web_app.name + '/epChangeForm/slicedEpChangeFormImplItems.ajax',
        pageSize: 10,
        usePager: true,
        parms:{epChangeFormId:getId(),oldId:$('#oldId').val()},
        toolbar: toolbarOptions,
        enabledEdit: true,
        width: "100%",
        height: "200px",
        heightDiff: -8,
        checkbox: true,
        fixedCellHeight: true,
        selectRowButtonOnly: true,
    });
    UICtrl.setSearchAreaToggle(gridManager);
}
function loadStockGrid() {
    var toolbarOptions = UICtrl.getDefaultToolbarOptions({
        addHandler: function () {
            UICtrl.addGridRow(stockGridManager);
        },
        deleteHandler: function () {
            var _grid = UICtrl.getGridManager('#stockMainGrid');
            DataUtil.delSelectedRows({
                action: 'epChangeForm/deleteEpChangeFormStockItem.ajax',
                param: {},
                gridManager: _grid,
                idFieldName: 'id',
                onSuccess: function () {
                    reloadGrid();
                }
            });
        }
    });
    stockGridManager = UICtrl.grid("#stockMainGrid", {
        columns: [
            {
                display: "仓库", name: "deptName", width: 200, minWidth: 60, type: "string", align: "left",
                // editor: {
                //     type: 'tree',
                //     required: true,
                //     data: {
                //         name: 'org',
                //         filter: 'dpt',
                //         minWidth: 250,
                //         param: {
                //             orgRoot: "14636F3F48934EE7811768692A0AC5E1"
                //         }
                //     },
                //     textField: 'deptName',
                //     valueField: 'deptId'
                // }
            },
            {
                display: "专属原材料/半成品/在制品/成品数量(张）", name: "description", width: 500, minWidth: 60, type: "string", align: "left",
                editor: {
                    type: "text"
                }
            },
            {
                display: "执行人", name: "executor", width: 100, minWidth: 60, type: "string", align: "left",
                editor: {
                    type: 'tree',
                    required: true,
                    checkbox: true,
                    data: {
                        name: 'org',
                        filter: 'psm',
                        minWidth: 250,
                        param: {
                            orgRoot: "14636F3F48934EE7811768692A0AC5E1"
                        }
                    },
                    back: {
                        deptName:'deptName',
                        deptId:'deptId',
                        name: 'executor',
                        id: 'executorId'
                    },
                    // textField: 'executor',
                    // valueField: 'executorId',
                }
            },
            {
                display: "签名确认", name: "confirmTextView", width: 100, minWidth: 60, type: "string", align: "left",
                editor: {
                    type: 'dictionary',
                    data: {name: 'confirm'},
                    textField: 'confirmTextView',
                    valueField: 'confirm',
                    //  checkbox:true,
                    required: false,
                    render: function (item) {
                        return item.confirmTextView;
                    }
                },
            },
            {
                display: "日期", name: "date", width: 150, minWidth: 60, type: "dateTime", align: "left",
                editor: {
                    type: "dateTime"
                }
            },
            {
                display: "COMMENTS评论", name: "comments", width: 400, minWidth: 60, type: "string", align: "left"
            },
        ],
        dataAction: "server",
        url: web_app.name + '/epChangeForm/slicedEpChangeFormStockItems.ajax',
        pageSize: 10,
        usePager: true,
        parms:{epChangeFormId:getId(),oldId:$('#oldId').val()},
        toolbar: toolbarOptions,
        enabledEdit: true,
        width: "100%",
        height: "200px",
        heightDiff: -8,
        checkbox: true,
        fixedCellHeight: true,
        selectRowButtonOnly: true,
    });
    UICtrl.setSearchAreaToggle(stockGridManager);
}

/**
 * 流程引擎回调设置打样的id
 * @param value
 */
function setId(id) {
    $("#id").val(id);
    $('#changeList').fileList({
        bizId : id
    });
    var _grid=UICtrl.getGridManager('#maingrid');
    _grid.options.parms.epChangeFormId = id;

    var _stockGrid=UICtrl.getGridManager('#stockMainGrid');
    _stockGrid.options.parms.epChangeFormId = id;
}

/**
 * 流程引擎获取打样申请id的回掉方法。
 * @return
 */
function getId() {
    return $("#id").val() || "";
}

function reloadGrid() {
    gridManager.loadData();
    stockGridManager.loadData();
}

function getExtendedData(processAction) {
//回退、打回、转交时，不需要验证必填项是否已经填写；
    if (processAction == ProcessAction.BACK
        || processAction == ProcessAction.REPLENISH
        || processAction == ProcessAction.TRANSMIT) {
//不验证
        $('#submitForm').attr('check', false);
    }
    var extendedData = {};
    var _grid = UICtrl.getGridManager('#maingrid');
    if (_grid) {
        var datas = DataUtil.getGridData({
            gridManager: _grid,
            isAllData: true
        });
        if (!datas) {
            return false;
        }
        extendedData.EpChangeFormImplItem = Public.encodeJSONURI(datas);
    }
    var _stockGrid = UICtrl.getGridManager('#stockMainGrid');
    if (_stockGrid) {
        var datas = DataUtil.getGridData({
            gridManager: _stockGrid,
            isAllData: true
        });
        if (!datas) {
            return false;
        }
        extendedData.epChangeFormStockItem = Public.encodeJSONURI(datas);
    }
    return extendedData;
}

function checkConstraints() {
    if (UICtrl.isApplyProcUnit()) {
        var chceked = true;
        // 检查是否有至少一个复选框被选中
        if ($("input[name='materialReasonForChange']:checked").length === 0) {
            chceked = false; // 显示错误消息
        }
        if (!chceked) {
            Public.tip('请选择变更类型');
            return false;
        }

        var changeEffectiveChceked = true;
        // 检查是否有至少一个复选框被选中
        if ($("input[name='changeEffective']:checked").length === 0) {
            changeEffectiveChceked = false; // 显示错误消息
        }
        if (!changeEffectiveChceked) {
            Public.tip('请选择生效日期');
            return false;
        }
    }
    return true;
}

function print(){
    // if ($("#statusId").val() != 3){
    //     Public.tip("请审批完成再打印!");
    //     return;
    // }
    var url='/epChangeForm/print.load';
    Public.openPostWindow(web_app.name+url,{id :$("#id").val()});
}
