$(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() {
    $('#selectedCategory').searchbox({
        type: "product",
        name: "productCode2",
        onChange: function (value, data) {
            $('#selectedCategory').val(data.productCategoryName)
        }
    });

    listeningSearchbox('#selectedFactory', {
        type: "product",
        name: "productFactoryName",
        onChange: function (value, data, fillInValue) {
            console.log('fillInValue  : '+ fillInValue);
        }
    });

    listeningSearchbox('#selectedTechnology', {
        type: "product",
        name: "productTechnologyType",
        onChange: function (value, data, fillInValue) {
            console.log('fillInValue  : '+ fillInValue);
            window.dataSet.original.ProductTechnology = data;

            Public.ajax(web_app.name + "/product/queryProcessbyTechnologyId.ajax",{
                    productTechnologyId: data.productTechnologyId
                },function (data) {
                window.dataSet.original.processed = data;
                let showData = mapping(dataMapping, window.dataSet.original);
                $('#submitForm').formClean();
                $('#submitForm').formSet(showData);
                processedGrid('#processedGrid', window.dataSet.rawData.processed);
            });

            // $('#selectedTechnology').val(data.productTechnologyName)
        }
    });

}

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

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

function save() {
    var process = $('#submitForm').formToJSON({ check: true });
    if (!process) {
        return false;
    }
    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);
        debugger;
        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"
        , "isOnlyCode", "isBodyColor", "isDisable", "isBuildBom"
        , "confirmDate", "comfirmPerson"
        , "isFreeInspection", "isNoQualityLoss", "sampleOrderNo", "stockNo", "fileNo", "brandName"
    ],
    ProductDetail: [
        {"factoryName": "factoryName"}, "productLayout", "materialCode", "productCode", "productEnCode", "bodyColor"
        , "customerMaterialCode" ,"versionNo", "isNewSpecification", "specificationNo", "productSubstrate"
    ],
    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", "physicalTest", "chemistryTest"
        , "productMaterial", {"productTechnologyName": "technology_productId"}
        , "copperpNo", "colorNoCard", "plateNo", "plasticBagStructure"
    ],
    ProductPublishedConf: [
        "modulus" , "columnNum", "rowNum", "contactNum", "columnDoubleBlade", "rowDoubleBlade"
        , "dispatchMultiple", "sheetLength", "sheetWidth", "productSheetConf"
    ],
    productFace: {
        id: "productFaceId",
        columns: [ "productFaceId", "productImage" ]
    },
    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: (rowData) => {
            console.log(rowData.rowIndex);
        },
    });
    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", editor: { type: 'text' }},
            { display: "工序名称", name: "processName", width: 120, minWidth: 60, type: "string", align: "left", editor: { type: 'text' } },
            { display: "是否排期工序", name: "isScheduleProcess", width: 120, minWidth: 60, type: "string", align: "left", editor: { type: 'text' } },
            { display: "是否完成工序", name: "isFinishedProcess", width: 120, minWidth: 60, type: "string", align: "left", editor: { type: 'text' } },
            { display: "工艺备注", name: "processRemark", width: 120, minWidth: 60, type: "string", align: "left", editor: { type: 'text' } },
            { display: "完成时间", name: "finishedTime", width: 120, minWidth: 60, type: "string", align: "left", editor: { type: 'text' } },
            { display: "签字", name: "signed", width: 120, minWidth: 60, type: "string", align: "left", editor: { type: 'text' } },
        ],
        // 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: false }},
            { display: "产品最大loss数量", name: "productLossMax", width: 120, minWidth: 60, type: "string", align: "left", editor: { type: 'text',  required: false } },
            { display: "loss比率", name: "productLossRate", width: 120, minWidth: 60, type: "string", align: "left", editor: { type: 'text',  required: false } },
            { display: "备注信息", name: "productLossRedundance", width: 120, minWidth: 60, type: "string", align: "left", editor: { type: 'text',  required: false } },
            { display: "产品最大loss数量", name: "productLossRemark", width: 120, minWidth: 60, type: "string", align: "left", editor: { type: 'text',  required: false } }
        ],
        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
// });