var rawData={};
$(document).ready(function() {
    initializeUI();
    initializeToobarContainer();
    initializateSelectC();
    $('#pageTab').tab();
    loadDataTest();
    runObserver();
});

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

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

function loadDataTest() {
    console.log("loadData")
    var params = new URLSearchParams(document.location.search);
    var paramsData = JSON.parse(params.get("data"));
    Public.ajax(web_app.name + "/product/loadProductDetail.ajax", {
        productId: paramsData.productId
    }, function (data) {
        rawData = data;
        $('#submitForm').formSet(data);
        var fronData = {};
        fronData.Rows = data.fronColors;
        faceGrid("#frontFaceGrid", fronData);
        fronData.Rows = data.backColors;
        faceGrid("#backFaceGrid", fronData);
        inputEventListener();
    });
}
// 数据映射配置
var dataMapping = {
    "productDetail": [
        "factoryName"
        , { "productLayout": "productLayout" }
    ],
    "ProductLooked": [
        "productLength"
        , "productWidth"
    ]
}

// 构建映射关系。
function mapping(dataMapping, rawData) {
    let entitySet =  Object.entries(dataMapping);
    entitySet.tryForEach((entity, index) => {
        let beanName = entity[0];
        let propertyNames = entity[1];
        let entityData = isExist(rawData, beanName) ? rawData[beanName] : throw {};
        propertyNames.tryForEach((item, index) => {
            if(typeof item === "string") {
                let value = isExist(entityData, item, item) ? entityData[item] : throw {};
                dataMapping.item = beanName;
                console.log(item);
                return;
            }
            if(item instanceof Object) {
                let entry = Object.entries(item);
                let property = entry[0];
                let value = isExist(entityData, property, property) ? entityData[property] : throw {};
                let alias = entry[1];
                dataMapping.alias = { beanName: property };
            }
        })
    })
}

Array.prototype.tryForEach = function (callback, thisArg) {
    try {
        this.forEach(callback, thisArg);
    } catch { }
}

function isExist(obj, property) { this.isExist(bj, property, 'rawData') }

function isExist(obj, property, objName) {
    if(!obj[property]) {
        console.error('No data for name of ' + entity[0] + ' in ' + objName + ' !');
        return false;
    }
    return true;
}

function faceGrid(elId, data) {
    var toolbarOptions = UICtrl.getDefaultToolbarOptions({
        updateHandler: function(){
            updateHandler();
        },
        aaHandler: { id: 'ccAA', text: 'Hello', img: 'fa-music', className: 'btn-gray',
            click: function () {
                alert('hello~!');
            }
        }
    });
    var gridManager =  UICtrl.grid(elId, {
        columns: [
            { display: "颜色名称", name: "productFaceColorId", width: 140, minWidth: 60, type: "string", align: "left" },
            { display: "油墨覆盖率(%)", name: "coverageRate", width: 120, minWidth: 60, type: "string", align: "left" }
        ],
        toolbar: toolbarOptions,
        dataType: "local",
        data: data, // data 数据结构 data: ("Rows": [ {}, {} ])
        usePager: false,
        width: "100%",
        height: 150,
        onDblClickRow : function(data, rowindex, rowobj) {
            updateHandler(data);
        }
    });
}

function save() {
    $('#submitForm').ajaxSubmit({
        url: web_app.name + '/product/saveProductAndDetail.ajax',
        param:{ rawData: JSON.stringify(rawData) },
        success: function(data) {
            debugger;
        }
    });
}

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 runObserver() {
    observer.observe(document.querySelector('#panelContainer'), mutationConfig);
}

// 补充方案 监听 Value 属性
const observer = new MutationObserver((mutations) => {
    mutations.forEach((mutation) => {
        if(mutation.type === 'attributes'&& mutation.attributeName === 'value') {
            console.log('属性变化节点 ： ' + mutation.target);
            console.log('变化属性名 ： ' + mutation.attributeName);
            console.log('变化属性值 ： ' + mutation.target.value);
        }
    })
})
const mutationConfig = { attributes: true, childList: true, subtree: true}

// 监听 input 管理页面显示的 Data，提交数据时，只提交修改过的 Data
function inputEventListener() {
    const inputElements = document.querySelectorAll('input');
    inputElements.forEach(item => {
        item.addEventListener('input', (event) => {
            console.log('Input value changed:', event.target.value);
        });
    });
}

// 用于判断字符串是否更改。
function getHashCode(str) {
    getHashCode(getHashCode, true);
}

function getHashCode (str, caseSensitive) {
    if(!caseSensitive) {
        str = str.toLowerCase();
    }
    if (str.length === 0) return 0;
    var len = str.length;
    var hash = 1315423911, i, ch;
    for (i = len - 1; i >= 0; i--) {
        ch = str.charCodeAt(i);
        hash = (hash << 5) + ch + (hash >> 2);
    }
    var hash2 = hash ^ (hash << 7) ^ (hash >> 6);
    var hash3 = hash2 ^ (hash2 << 1) ^ (hash2 >> 13);
    if (len < 50) {
        var hash4 = this.getHashCode(str + str + str, caseSensitive);
        return (hash ^ hash2 ^ hash3  ^ hash4) & 0x7FFFFFFF ;
    } else {
        return (hash ^ hash2 ^ hash3 >> 3 ) & 0x7FFFFFFF;
    }
}

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