<style>
    .object{
        background-color: #bfe4ff;
        border: dashed 4px transparent;
        border-radius: 4px;
        height: 55px;
        width: 55px;
        margin: 5px;
        margin-top: 0px;
        margin-bottom: 20px;
    }
    img{
        width: 100%;
        height: 100%;
        object-fit: contain;
        pointer-events: none;
    }
    #objs_in_group,#founded_objs_list{
        display: flex;
        flex-wrap: wrap;
        padding: 0px;
    }
    #find_obj_btns{
        /* display: flex; */
        margin: auto 0px;
        /* height: 25px; */
    }
</style>

<h1>Изменение объектов</h1>
<div>
    <div id="objs_in_group"></div>
</div>
<div style="display: flex;justify-content: space-between;float: right;">
    <div id="find_obj_btns">
        <button onclick="edit_get_objs(true)" class="btn_blue">найти по имени</button>
        <button onclick='gids = [];edit_get_objs();' class="btn_blue">очистить</button>
    </div>
</div>

<script>
    // load_groups(()=>{
    //     edit_get_objs();
    // });

    function set_edit(id){
        let menu = document.getElementById(`object_${id}`);
        set_obj_edit_params(menu.getAttribute("src"),
        menu.getAttribute("name").split("~")[0],
        menu.getAttribute("height"),
        menu.getAttribute("width"),
        menu.getAttribute("cost"),
        menu.getAttribute("gid"),
        menu.getAttribute("colors"),
        menu.getAttribute("obj_id"));
    }

    function edit_get_objs(by_name = false){
        document.getElementById("objs_in_group").innerHTML = "";
        if (obj_edit_type == "edit") set_obj_edit_params();
        edit_load_objs((data)=>{
            data.forEach(value => {
                // console.log(value);
                // // console.log($.cookie("cache"));
                edit_load_obj(value["name"],"`img`",(odata)=>{
                    make_obj(odata["img"],value,"objs_in_group");
                })           
            });
        },by_name)
    }

    function gids_change(){
        if (typeof gids[0] == 'undefined'){
            gids = []
            edit_get_objs();
        }
        else{
            let last = gids.at(-1)
            gids = [last];
            edit_get_objs();
        }
        hide_menus();
        
    }

    function obj_del(id){
        // let select = document.getElementById("group_select");
        let menu = document.getElementById(`object_${id}`);
        msg(`вы точно хотите удалить ${menu.getAttribute("name").split("~")[0]}?`,{type:"ask",res:(out)=>{if(res){
            let wait_msg = msg("удаление товара",{type:"wait"});
            $.post( "/admin/objects/delete", { id:id,})
            .done(function( res ) {
                if(res["out"] == "good"){
                    msg_del(wait_msg.id);
                    msg("товара удалён");
                    edit_get_objs();
                }
            });
        }}})
    }

    function save_edited_obj(id){
        let gid = gids[0];
        let menu = document.getElementById(`object_${id}`);
        let attributes = ["name","img","height","width","cost","colors"];
        let cur_atts = {
            name : document.getElementById("nobj_name").value,
            height : document.getElementById("obj_height").value,
            width : document.getElementById("obj_width").value,
            img : document.getElementById('img_prev').src,
            cost : document.getElementById("obj_cost").value,
            colors : String(document.getElementById("obj_color_check").checked)
        }
        let changes = {}
        attributes.forEach(element => {
            if(element != attributes.at(-1)){
                check_change(element);
                // console.log(element);
            }
            else if (element == attributes.at(-1)){
                check_change(element);
                // console.log(changes);
                if(Object.keys(changes).length > 0){
                    make_obj_save(changes);
                    // console.log(changes);
                }
                else{
                    msg("нет изменений")
                }
            }
        });
        function check_change(element){
            // console.log(changes[element],cur_atts[element]);
            if(element == "name" && cur_atts[element] != menu.getAttribute(`${element}`).split("~")[0]){
                changes[element] = cur_atts[element];
            }
            else if (element == "img" && cur_atts[element] != menu.getAttribute(`src`)){
                changes[element] = cur_atts[element];
            }
            else if ((element != "name" && element != "img") && cur_atts[element] != menu.getAttribute(`${element}`)){
                changes[element] = cur_atts[element];
            }
        }
        function make_obj_save(){
            load_group(gid,(group_db)=>{
                if(changes["name"]) changes["name"] = (changes["name"]+"~g~"+group_db["name"]).replaceAll(" ","$");
                let wait_msg = msg("сохранение товара",{type:"wait"});
                $.post( "/admin/objects/edit", { id:menu.getAttribute(`obj_id`),changes:JSON.stringify(changes),gid:gid})
                .done(function( res ) {
                    // console.log(res);
                    msg_del(wait_msg.id);
                    if(res["out"] == "good"){
                        if(res["name_err"]){
                            msg("название товара не было изменино поскольку оно занято",{type:"warning"})
                        }
                        else{
                            msg("товар сохранён");
                            setTimeout(()=>{
                                edit_get_objs();
                                set_obj_edit_params();
                            },1500)
                        }
                    }
                });
            })
        }
    }

    function edit_load_obj(name,key,callback){
        $.post( "/get_obj",{name:name,key:key})
        .done(function( res ) {
            if(res["out"] == "good"){
                // console.log(res["body"]);
                callback(res["body"]);
            }
        });
    }
        
    function edit_load_objs(callback,by_name = false){
        // let select = document.getElementById("group_select");
        if(!by_name){
            gids.forEach(gid => {
                $.post( "/get_objs",{gid:gid})
                .done(function( res ) {
                    if(res["out"] == "good"){
                        // console.log(res["body"]);
                        // res["body"].forEach(object => {
                        //     // objs_store[`${element["name"]}`] = {description:element["description"],height:element["height"],width:element["width"],id:element["id"],name:element["name"]}
                        //     let obj_main = document.createElement("div");
                        // });
                        callback(res["body"]);
                    }
                });
            });
        }
        else{
            ask("название",{func:(name)=>{
                    $.post( "/admin/objects/find", { name:name.replaceAll(" ","$")})
                    .done(function( res ) {
                        if(res["out"] == "good"){
                            // console.log(res["body"]);
                            callback(res["body"])
                        }
                    })
                }
            });
        }
    }

        function make_obj(img,value,list_id){
            let obj_list = document.getElementById(list_id);
            let obj =  document.createElement('div');
            let name_text =  document.createElement('div');
            let img_elm =  document.createElement('img');
            obj.title = `название:${value["name"].split("~")[0].replaceAll("$"," ")}\nцена:${value["cost"]}\nширина:${value["width"]}\nвысота${value["height"]}\nименение цвета:${Boolean(value["colors"])}\nартикуль:${value["name"]}`;
            obj.id = `object_${value["id"]}`;
            obj.setAttribute("onclick",`set_edit(${value["id"]})`)
            obj.classList.add(value["name"]);
            obj.classList.add("object");
            obj.setAttribute("name",value["name"].split("~")[0].replaceAll("$"," "))

            obj.setAttribute("src",img)
            obj.setAttribute("height",value["height"])
            obj.setAttribute("width",value["width"])
            obj.setAttribute("obj_id",value["id"])
            obj.setAttribute("cost",value["cost"])
            obj.setAttribute("colors",Boolean(value["colors"]))
            obj.setAttribute("gid",value["gid"])
            // name_text.innerText = value["name"].split("~")[0].replaceAll("$"," ");
            img_elm.src = img;
            obj.append(img_elm)
            obj.append(name_text)
            obj_list.append(obj)

            // console.log("obj");
        }              
</script>