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

$(document).ready(function () {
    initialize();
    loadGrid();
    loadStockGrid();
    bindEvent();
    //$("#reasonForChangeMATERIAL CHANGE").remove();
});
function initialize(){
    UICtrl.layout("#layout", {leftWidth: 3});
    $('#changeList').fileList({
        bizId : $("#id").val()
    });
    $(".hg-form-list option[value='MATERIAL CHANGE']").remove();

    // var reasonForChange = $("#reasonForChangeMATERIAL CHANGE").checked;
    // if (reasonForChange){
    //     //涉及成品编码+旧原材料库存+涉及原材料成品库存 true
    //     materialChangeOtherRequire();
    //     //成品变更：产品代号+产品名称+制程工艺+原材料+其他 false
    //     noMaterialChangeNoRequire();
    //
    // }else {
    //     //成品变更：产品代号+产品名称+制程工艺+原材料+其他 true
    //     noMaterialChangeRequire();
    //     //涉及成品编码+旧原材料库存+涉及原材料成品库存 false
    //     materialChangeOtherNoRequire();
    // }
    //$("#deptNameAndPersonName").val($("#deptName").val()+"-"+$("#personMemberName").val())
}

function bindEvent(){
    $('#brandName').searchbox({
        type: "system", name: "queryBrand",
        checkbox:true,
        checkboxIndex:"brandCode",
        textIndex:"brandName",
        valueIndex:"brandCode",
        getParam: function (item) {
            return {
                //fieldName:"MEINS"
            }
        },
        onChange: function (value, data) {
            $('#brandCode').val(value.value);
            $('#brandName').val(value.text);
        }
    });

    $('#pd').searchbox({
        type: "system", name: "queryPd",
        checkbox:true,
        checkboxIndex:"productCode",
        textIndex:"productName",
        valueIndex:"productCode",
        getParam: function (item) {
            return {
                filterValue:$("#brandCode").val()
            }
        },
        onChange: function (value, data) {
            $('#pd').val(value.value);
            $('#changedPd').val(value.value);
            //$('#productName').val(value.text);
            //$('#changedProductName').val(value.text);
        }
    });

    // $('#process').searchbox({
    //     type: "system", name: "queryProductAndBom",
    //     // checkbox:true,
    //     // checkboxIndex:"process",
    //     // textIndex:"material,",
    //     // valueIndex:"process",
    //     // idIndex:"productionSolutionId",
    //     getParam: function (item) {
    //         return {
    //             filterValue:$('#pd').val()
    //         }
    //     },
    //     onChange: function (value, data) {
    //         $('#process').val(data.process);
    //         $('#material').val(data.material);
    //         $('#productionSolutionId').val(data.productionSolutionId);
    //     }
    // });


    // $('input[name="reasonForChange"]').change(function () {
    //     //变更后的制程工艺和原材料可以不必填，原材料变更不需要
    //     if ($(this).is(':checked')) {
    //         if ($(this).val() == "MATERIAL CHANGE"){
    //             //涉及成品编码+旧原材料库存+涉及原材料成品库存 true
    //             materialChangeOtherRequire();
    //             //成品变更：产品代号+产品名称+制程工艺+原材料+其他 false
    //             noMaterialChangeNoRequire();
    //
    //         }else {
    //             //成品变更：产品代号+产品名称+制程工艺+原材料+其他 true
    //             noMaterialChangeRequire();
    //             //涉及成品编码+旧原材料库存+涉及原材料成品库存 false
    //             materialChangeOtherNoRequire();
    //         }
    //     } else {
    //         if ($(this).val() == "MATERIAL CHANGE"){
    //             //成品变更：产品代号+产品名称+制程工艺+原材料+其他 true
    //             noMaterialChangeRequire();
    //             //涉及成品编码+旧原材料库存+涉及原材料成品库存 false
    //             materialChangeOtherNoRequire();
    //
    //         }
    //     }
    // })

    $("#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 materialChangeOtherRequire(){
//原材料变更：产品代号+产品名称+涉及成品编码+旧原材料库存+涉及原材料成品库存。 true
    UICtrl.setElRequiredFlag("#otherProcess",true);
    UICtrl.setElRequiredFlag("#oldMaterial",true);
    UICtrl.setElRequiredFlag("#othersMaterialStore",true);
}

function materialChangeOtherNoRequire(){
//涉及成品编码+旧原材料库存+涉及原材料成品库存 false
    UICtrl.setElRequiredFlag("#otherProcess",false);
    UICtrl.setElRequiredFlag("#oldMaterial",false);
    UICtrl.setElRequiredFlag("#othersMaterialStore",false);
}

function noMaterialChangeRequire(){
    //成品变更：产品代号+产品名称+制程工艺+原材料+其他 true
    UICtrl.setElRequiredFlag("#changedProcess",true);
    UICtrl.setElRequiredFlag("#changedMaterial",true);
    UICtrl.setElRequiredFlag("#process",true);
    UICtrl.setElRequiredFlag("#material",true);
}

function noMaterialChangeNoRequire(){
//成品变更：产品代号+产品名称+制程工艺+原材料+其他 false
    UICtrl.setElRequiredFlag("#changedProcess",false);
    UICtrl.setElRequiredFlag("#changedMaterial",false);
    UICtrl.setElRequiredFlag("#process",false);
    UICtrl.setElRequiredFlag("#material",false);
}

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: 200, minWidth: 60, type: "string", align: "left",
                editor: {
                    type: "text"
                }
            },
            {
                display: "执行人", name: "executor", width: 200, 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: 140, 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: 200, minWidth: 60, type: "dateTime", align: "left",
                editor: {
                    type: "dateTime"
                }
            }
        ],
        dataAction: "server",
        url: web_app.name + '/epChangeForm/slicedEpChangeFormImplItems.ajax',
        pageSize: 10,
        usePager: true,
        parms:{epChangeFormId:getId()},
        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: 300, minWidth: 60, type: "string", align: "left",
                editor: {
                    type: "text"
                }
            },
            {
                display: "执行人", name: "executor", width: 200, 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: 140, 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: 200, minWidth: 60, type: "dateTime", align: "left",
                editor: {
                    type: "dateTime"
                }
            }
        ],
        dataAction: "server",
        url: web_app.name + '/epChangeForm/slicedEpChangeFormStockItems.ajax',
        pageSize: 10,
        usePager: true,
        parms:{epChangeFormId:getId()},
        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 print(){
    if ($("#statusId").val() != 3){
        Public.tip("请审批完成再打印!");
        return;
    }
    var url='/epChangeForm/print.load';
    Public.openPostWindow(web_app.name+url,{id :$("#id").val()});
}
