$(document).ready(function() {
    loadData();
    initializeUI();
    initializeToobarContainer();
    initializeTab();
    initializateSelectC();
    initGridSearchbox();
    // 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, gridManager) {
            console.log('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) {

                let showData = refreshMapping(dataMapping, 'processed', data);
                $('#submitForm').formClean();
                $('#submitForm').formSet(showData);
                processedGrid('#processedGrid', window.dataSet.rawData.processed);
            });
            // $('#selectedTechnology').val(data.productTechnologyName)
        }
    });
}

function initGridSearchbox() {
    listeningGridSearchbox('fronColorsGrid_colorName', {
        type: "product",
        name: "color",
        autocomplete: true,
        onChange: function (value, data, fillInValue) {
            console.log('fillInValue  : '+ fillInValue);
        }
    });
    listeningGridSearchbox('backColorsGrid_colorName', {
        type: "product",
        name: "color",
        autocomplete: true,
        onChange: function (value, data, fillInValue) {
        }
    });
}


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 loadData() {
    console.log("loadData")
    var params = new URLSearchParams(document.location.search);
    Public.ajax(web_app.name + "/product/loadProductDetail.ajax", {
        data: params.get("data")
    }, function (data) {
        let showData = buildMapping(dataMapping, data.rawData);
        $('#submitForm').formSet(showData);

        if(window.dataSet.isInsert) {
            // Grid 使用  Local 模式，data 不能为 undefined
            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"
        , "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"
    ],
    frontFaces: {
        id: "productFaceId",
        columns: [ "productFaceId", "productImage" ]
    },
    fronColors: {
        id: "productFaceColorId",
        columns: [ "productFaceColorId", "coverageRate", "productFaceId", "colorId", "colorName" ]
    },
    backColors: {
        id: "productFaceColorId",
        columns: [ "productFaceColorId", "coverageRate", "productFaceId", "colorId", "colorName" ]
    },
    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, gridManager){
            let isBack = true;
            if(gridManager.id.indexOf('fronColors') >= 0) { isBack = false; }
            window.dataSet.newData.frontFaces.raw.forEach(item=> {
                if(isBack === item.back) {
                    if(isBack) {
                        window.dataSet.newData.backColors.compares[rawData.rowIndex].productFaceId = item.productFaceId;
                    } else {
                        window.dataSet.newData.fronColors.compares[rawData.rowIndex].productFaceId = item.productFaceId;
                    }
                }
            })
        },
        deleteHandler: (rowData, gridManager) => {
            console.log(rowData.rowIndex);
        },
    });
    var gridManager =  listeningGrid(elId, {
        columns: [
            { display: "颜色名称", name: "colorName", width: 140, minWidth: 60, type: "string", align: "left",
                editor: { type: 'select', fillProperty: 'colorId'} },
            { display: "油墨覆盖率(%)", name: "coverageRate", 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: "90%",
        onBeforeEdit : function(editParm, gg) {
            console.log('original run onBeforeEdit()');
        },
        onBeforeSubmitEdit: function(editParm, gg){
            // debugger;
        },
    });
}

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
// });