$(document).ready(function() {
    loadDataTest();
    initializeUI();
    initializeToobarContainer();
    initializeTab();
    // initializateSelectC();
    // runObserver();

});

function initializeTab() {
    $('#pageTab').tab({
        onClick:function(item){
            var _id=item.data('id');
            var gm=UICtrl.getGridManager('#'+_id);
            UICtrl.onGridResize(gm);
        }
    });
}

function initializateSelectC() {
    $('#productId').searchbox({
        type: "product",
        name: "productCode",
        onChange: function (value, data) {
        }
    });
}

function initializeUI() {
    UICtrl.layout("#layout",{
        heigth:'280px',
        leftWidth:6,
        rightWidth:6,
        allowRightCollapse: false,
        allowRightResize: false
    });
    var gm=UICtrl.getGridManager("#layout");
    UICtrl.onGridResize(gm);
}

function deleteHandler(){
    DataUtil.del({
        gridManager:gridManager,idFieldName:'id',
        onSuccess:function(){
        }
    });
}

function save() {
    let upData = checkUpdata();
    if(!upData) { return; }
    Public.ajax(web_app.name + "/product/saveOrUpdataOnAllDetail.ajax", {
        data: JSON.stringify(upData)
    }, function (data) {

    });
}

function initializeToobarContainer(){
    var toolBarOptions= {
        dropup: $('#toolBar').data('dropup') === true,//显示更多按钮时 是否向上打开菜单
        items: [{
            id: 'save',
            remark: '保存',
            name: 'common.button.save',
            icon: 'fa-save',
            delay: true,
            relation: 'advance',
            event: save
        }]
    };
    $('#toolBar').toolBar(toolBarOptions);
    //dropup==true 更多按钮向上展示
    $('#toolBar').data('dropup',true).removeClass('job-button-fixed-top').addClass('job-button-fixed-bottom');
}

function loadDataTest() {
    console.log("loadData")
    var params = new URLSearchParams(document.location.search);
    Public.ajax(web_app.name + "/product/loadProductDetail.ajax", {
        data: params.get("data")
    }, function (data) {
        var showData = mapping(dataMapping, data.rawData);
        $('#submitForm').formSet(showData);
        var fronData = {};
        if(window.dataSet.isInsert) {
            data.rawData = {};
            data.rawData.fronColors = {};
            data.rawData.backColors = {};
            data.rawData.processed = {};
        }
        faceGrid("#fronColorsGrid", data.rawData.fronColors);
        faceGrid("#backColorsGrid", data.rawData.backColors);
        processedGrid('#processedGrid', data.rawData.processed);
        productLossGrid('#productLossGrid', data.rawData.productLoss);
        inputEventListener();
    });
}
// 数据映射配置
//      Form:  映射数据格式为elementName(alias): { objName: property }
//          alias必须唯一.这里不再要求所有对象的属性名唯一 { property : alias }
//          未设 alias 情况同 { property : property }
//      Grid:   需要监听 Grid Data 时，必须设置 唯一 id 列。
var dataMapping = {
    Product: [
        "productId", "brandName","productCategoryId",  "productUnit", "productSizeGroupId", "confirmDate", "comfirmPerson",
        "isFreeInspection", "isNoQualityLoss", "sampleOrderNo", "stockNo", "fileNo", "brandName"
    ],
    ProductDetail: [
        {"factoryName": "factoryName"}, "productLayout", "materialCode", "productCode", "productEnCode", "bodyColor",
        "customerMaterialCode" ,"versionNo", "isNewSpecification", "specificationNo"
    ],
    ProductLooked: [
        "productLength", "productWidth", "productHeight", "productThick", "productWeight", "productAngleType", "productAngle"
        , "productAperture", "productSingleLayer", "productSingleWeight", "productLayerNum", "productMould", "productCoding"
        , "productSysCertification", "storeName", "productBuyUnit", "purchaseConversionValue", "coefficient"
    ],
    ProductTechnology: [
        "beerPlateNo", "goldPlateNo" , "dieCutPlateNo", "copperpResinLateNo", "netPlateNo",
        "productTechnologyRequire", "packageStyle", "packageStyle", "physicalTest", "chemistryTest"
        , "productMaterial"
        , "copperpNo", "colorNoCard", "plateNo", "plasticBagStructure"
    ],
    ProductPublishedConf: [
        "modulus" , "columnNum", "rowNum", "contactNum", "columnDoubleBlade", "rowDoubleBlade"
        , "dispatchMultiple", "sheetLength", "sheetWidth", "productSheetConf"
    ],
    fronColors: {
        id: "productFaceColorId",
        columns: [ "productFaceColorId", "coverageRate" ]
    },
    backColors: {
        id: "productFaceColorId",
        columns: [ "productFaceColorId", "coverageRate" ]
    },
    processed: {
        id: "productTechnologyId",
        columns: [ "productionSequence", "processName", "isScheduleProcess", "isFinishedProcess", "processRemark", "finishedTime", "signed" ]
    },
    productLoss: {
        id: "productLossId",
        columns: [ "productId", "customerName", "productLossMax", "productLossRate", "productLossRedundance", "productLossRemark" ]
    }
}

function faceGrid(elId, data) {
    var toolbarOptions = UICtrl.getDefaultToolbarOptions({
        addHandler: function(rawData){
        },
        updateHandler: function(){
            updateHandler();
        },
        deleteHandler: () => {
            gridManager.deleteSelectedRow();
        },
    });
    var gridManager =  listeningGrid(elId, {
        columns: [
            { display: "颜色名称", name: "productFaceColorId", width: 140, minWidth: 60, type: "string", align: "left", editor: {
                    type: 'text',
                    required: true
                }},
            { display: "油墨覆盖率(%)", name: "coverageRate", width: 120, minWidth: 60, type: "string", align: "left", editor: { type: 'text',  required: true } }
        ],
        toolbar: toolbarOptions,
        dataType: "local",
        data: data, // data 数据结构 data: ("Rows": [ {}, {} ])
        enabledEdit: true,
        checkbox: true,
        usePager: false,
        width: "100%",
        height: 150,
        onBeforeEdit : function(editParm, gg) {
            console.log('original run onBeforeEdit()');
        },
        onDblClickRow : function(data, rowindex, rowobj) {
        }
    });
}

function processedGrid(elId, data) {
    // var toolbarOptions = UICtrl.getDefaultToolbarOptions({
    //     addHandler: function(){
    //     },
    //     updateHandler: function(){
    //         updateHandler();
    //     },
    //     deleteHandler: () => {
    //         gridManager.deleteSelectedRow();
    //     },
    // });
    var gridManager =  listeningGrid(elId, {
        columns: [
            { display: "生成顺序", name: "productionSequence", width: 140, minWidth: 60, type: "string", align: "left"},
            { display: "工序名称", name: "processName", width: 120, minWidth: 60, type: "string", align: "left" },
            { display: "是否排期工序", name: "isScheduleProcess", width: 120, minWidth: 60, type: "string", align: "left" },
            { display: "是否完成工序", name: "isFinishedProcess", width: 120, minWidth: 60, type: "string", align: "left" },
            { display: "工艺备注", name: "processRemark", width: 120, minWidth: 60, type: "string", align: "left" },
            { display: "完成时间", name: "finishedTime", width: 120, minWidth: 60, type: "string", align: "left" },
            { display: "签字", name: "signed", width: 120, minWidth: 60, type: "string", align: "left" },
        ],
        // toolbar: toolbarOptions,
        dataType: "local",
        data: data, // data 数据结构 data: ("Rows": [ {}, {} ])
        enabledEdit: true,
        checkbox: true,
        usePager: false,
        width: "98%",
        height: 150,
        onAfterEdit: function(editParm) {
            // 后备方案: 表格遍历完成时
        },
        onBeforeEdit : function(editParm) {
            console.log('original run onBeforeEdit()');
        },
        onDblClickRow : function(data, rowindex, rowobj) {

        }
    });
}

function productLossGrid(elId, data) {
    var toolbarOptions = UICtrl.getDefaultToolbarOptions({
        addHandler: function(rawData){
        },
        deleteHandler: () => {
            gridManager.deleteSelectedRow();
        },
    });
    var gridManager =  listeningGrid(elId, {
        columns: [
            { display: "客户名称", name: "customerName", width: 140, minWidth: 60, type: "string", align: "left", editor: { type: 'text', required: true }},
            { display: "产品最大loss数量", name: "productLossMax", width: 120, minWidth: 60, type: "string", align: "left", editor: { type: 'text',  required: true } },
            { display: "loss比率", name: "productLossRate", width: 120, minWidth: 60, type: "string", align: "left", editor: { type: 'text',  required: true } },
            { display: "备注信息", name: "productLossRedundance", width: 120, minWidth: 60, type: "string", align: "left", editor: { type: 'text',  required: true } },
            { display: "产品最大loss数量", name: "productLossRemark", width: 120, minWidth: 60, type: "string", align: "left", editor: { type: 'text',  required: true } },
        ],
        toolbar: toolbarOptions,
        dataType: "local",
        data: data, // data 数据结构 data: ("Rows": [ {}, {} ])
        enabledEdit: true,
        checkbox: true,
        usePager: false,
        width: "98%",
        height: 500,
        onBeforeEdit : function(editParm, gg) {
            debugger;
            console.log('original run onBeforeEdit()');
        },
        onDblClickRow : function(data, rowindex, rowobj) {
        }
    });
}


// if(!isExist(rawData, entity[0])) {
//     throw {};
// }
// let entityData = rawData[entity[0]];

// checkbox: true,
//     enabledSort: false,
//     autoAddRowByKeydown:false,
//     heightDiff: -10,
//     fixedCellHeight: true,
//     selectRowButtonOnly: true,

// var selectedCategory = data.selectedCategory;
// $("#selectedCategory").ligerComboBox({
//     textField: 'productCategoryName',
//     valueField: 'productCategoryId',
//     columns: [
//         { header: 'ID', name: 'productCategoryId', width: 20 },
//         { header: '名字', name: 'productCategoryName' }
//     ],
//     data: selectedCategory,
//     selectBoxWidth: 200
// });