window.addEventListener('load', () => {
    const queryString  = location.search;
    const params = new URLSearchParams(queryString);
    const query_order = params.getAll("order");

    const dfimgRadios = document.querySelectorAll('.dfimg_radio');
    // const shiyo_kakaku_radios = document.querySelectorAll('.shiyo_kakaku_radio');
    dfimgRadios.forEach((dfimgRadio)=>{
        dfimgRadio.addEventListener('change',(e)=>{
            let order_no = e.target.parentNode.parentNode.children[1].textContent;
            let row = e.target.parentNode.parentNode;
            let row_child_list = row.children;
            for (const child of row.parentNode.querySelectorAll('tr')){
                child.classList.remove('checked');
            }
            row.classList.add('checked');

            // list = document.querySelectorAll('.shiyo_kakaku_radio');
            // list.forEach((val)=>{
            //     let other_order_no = val.nextElementSibling.value;
            //     if(other_order_no == order_no){
            //         val.checked = true;
            //         let row2 = val.parentNode.parentNode;
            //         for (const child of row2.parentNode.querySelectorAll('tr')){
            //             child.classList.remove('checked');
            //         }
            //         row2.classList.add('checked');

            //         $(row2).siblings().each((i,row_color)=>{
            //             row_color.querySelectorAll('.haiban').forEach((target)=>{
            //                 target.setAttribute('style','color:red');
            //             });
            //         });
            //         row2.querySelectorAll('.haiban').forEach((target)=>{
            //             target.setAttribute('style','color:white');
            //         });
            //     }
            // })

            const section = e.target.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode;
            const dftimg = section.querySelector('.DIFTIMG_IMG');
            if(dftimg){
                
                if(typeof row_child_list[row_child_list.length-1].value == "undefined"){
                    dftimg.src = "/Catalog/imgdft/not.gif";
                }else{
                    dftimg.src = row_child_list[row_child_list.length-1].value;
                }
            }
            const diftdiv = section.querySelector('.DIFTIMG_DIV');
            if(diftdiv){
                diftdiv.removeAttribute('style')
            }


        })
        if(dfimgRadio.classList.value.includes('radio_first')){
            dfimgRadio.checked = true;
            dfimgRadio.parentNode.parentNode.classList.add('checked');
            let event = new Event('change');
            dfimgRadio.dispatchEvent(event);
        }
    })

    // shiyo_kakaku_radios.forEach((shiyo_kakaku_radio)=>{
    //     shiyo_kakaku_radio.addEventListener('change',(e)=>{
    //         let order_no = e.target.nextElementSibling.value;
    //         let row = e.target.parentNode.parentNode;
    //         for (const child of row.parentNode.querySelectorAll('tr')){
    //             child.classList.remove('checked');
    //         }
    //         row.classList.add('checked');
    //         list = document.querySelectorAll('.dfimg_radio');
    //         list.forEach((val)=>{
    //             let other_order_no = val.parentNode.parentNode.children[1].textContent;
    //             if(other_order_no == order_no){
    //                 val.checked = true;
    //                 let row2 = val.parentNode.parentNode;
    //                 let row_child_list = row2.children;
    //                 for (const child of row2.parentNode.querySelectorAll('tr')){
    //                     child.classList.remove('checked');
    //                 }
    //                 row2.classList.add('checked');
    //                 const section = val.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode;
    //                 const dftimg = section.querySelector('.DIFTIMG_IMG');
   
    //                 if(dftimg){
    //                     if(typeof row_child_list[row_child_list.length-1].value == "undefined"){
    //                         dftimg.src = "/Catalog/imgdft/not.gif";
    //                     }else{
    //                         dftimg.src = row_child_list[row_child_list.length-1].value;
    //                     }
    //                 }
    //                 const diftdiv = section.querySelector('.DIFTIMG_DIV');
    //                 if(diftdiv){
    //                     diftdiv.removeAttribute('style')
    //                 }
    //             }
    //         })
    //         $(row).siblings().each((i,row_color)=>{
    //             row_color.querySelectorAll('.haiban').forEach((target)=>{
    //                 target.setAttribute('style','color:red');
    //             });
    //         });
    //         row.querySelectorAll('.haiban').forEach((target)=>{
    //             target.setAttribute('style','color:white');
    //         });
    //     })
    //     if(shiyo_kakaku_radio.classList.value.includes('radio_first_shiyo')){
    //         shiyo_kakaku_radio.checked = true;
    //         shiyo_kakaku_radio.parentNode.parentNode.classList.add('checked');
    //         let event = new Event('change');
    //         shiyo_kakaku_radio.dispatchEvent(event);
    //     }
    //     let order = shiyo_kakaku_radio.nextElementSibling.value;
    //     if(query_order.length > 0 && (order == query_order[0])){
    //         shiyo_kakaku_radio.checked = true;
    //         shiyo_kakaku_radio.parentNode.parentNode.classList.add('checked');
    //         let event = new Event('change');
    //         shiyo_kakaku_radio.dispatchEvent(event);
    //     }
    // })

    const click_row_size_list = document.querySelectorAll('.click_row_size');
    // const click_row_shiyou_list = document.querySelectorAll('.click_row_shiyou');
    click_row_size_list.forEach((click_row_size)=>{
        click_row_size.addEventListener('click',(e)=>{
            const radio = click_row_size.querySelector('.dfimg_radio');
            radio.checked = true;
            let event = new Event('change');
            radio.dispatchEvent(event);
        })
    });
    // click_row_shiyou_list.forEach((click_row_shiyou)=>{
    //     click_row_shiyou.addEventListener('click',(e)=>{
    //         const radio = click_row_shiyou.querySelector('.shiyo_kakaku_radio');
    //         radio.checked = true;
    //         let event = new Event('change');
    //         radio.dispatchEvent(event);
    //     })
    // });

    const dlBtnSelecters = document.querySelectorAll('.btn_dl');
    dlBtnSelecters.forEach((dlBtnSelecter)=>{
            dlBtnSelecter.addEventListener('click',(e)=>{
            ext = e.target.dataset.ext;
            key = e.target.dataset.key;
            cadDownload(key,ext);
        })
    })
    const productAddNodes = document.querySelectorAll('.btn_add');
    productAddNodes.forEach((productAdd)=>{
        productAdd.addEventListener('click',(e)=>{
            let order_no = e.target.dataset.value
            let productList = JSON.parse(window.localStorage.getItem('productList'))??[];
            if((productList.length)+1 > 100){
                alert("製品BOXの追加上限100に達しました。");
                return false;
            }
            let old_count = productList.length;
            productList.push(order_no);
            window.localStorage.setItem('productList',  JSON.stringify(Array.from(new Set(productList))));
            const prodbox = document.querySelector('.prodbox');
            if(prodbox){
                const num = prodbox.querySelector('.num');
                let prodbox_list = JSON.parse(window.localStorage.getItem('productList'))??[]
                if(num){
                    num.textContent = prodbox_list.length;
                    if(prodbox_list.length != old_count){
                        num.setAttribute('style','transform: scale(1.3);color:red;font-size:bold;');
                        setTimeout(
                            function(){
                                num.setAttribute('style','transform: scale(1.2);color:red;font-size:bold;');
                            }
                            , 50 );
                        setTimeout(
                            function(){
                                num.setAttribute('style','transform: scale(1.1);color:red;font-size:bold;');
                            }
                            , 100 );
                        setTimeout(
                            function(){
                                num.setAttribute('style','');
                            }
                            , 300 );
                    }
                }
                let message = '製品BOXに追加しました。';
                if(prodbox_list.length == old_count){
                    message='製品BOXにすでに追加されています。';
                }
                $(e.target).attr("data-content", message);
                $(e.target).popover('show')
                setTimeout(
                    ()=>{
                        $(e.target).popover('hide')
                    }
                    , 2500 );
            }
        })
    });

    const stock_link_list = document.querySelectorAll('.stock_link');
    stock_link_list.forEach((stock_link)=>{
        stock_link.addEventListener('click',async (e)=>{
            // const form = document.createElement('form');
            // form.id = 'dynamicStockForm';
            // form.method = 'POST';
            // form.action = '/productStockCheck';

            // const order_no = stock_link.parentNode.parentNode.querySelector('.tr_order_no')
            // if(order_no){
            //     const order_noInput = document.createElement('input');
            //     order_noInput.type = 'text';
            //     order_noInput.name = 'order_no[]';
            //     order_noInput.value = order_no.value;
        
            //     const numInput = document.createElement('input');
            //     numInput.type = 'text';
            //     numInput.name = 'num['+order_no.value+']';
            //     numInput.value = 1;
            //     const csrf = document.getElementsByName('_token');
         
            //     form.appendChild(csrf[0]);
            //     form.appendChild(order_noInput);
            //     form.appendChild(numInput);
        
            //     document.body.appendChild(form);
            //     form.submit(); 
            // }
            let productList = JSON.parse(window.localStorage.getItem('productList'))??[];
            if((productList.length)+1 > 100){
                alert("製品BOXの追加上限100に達しました。");
                return false;
            }
            const order_no = stock_link.parentNode.parentNode.querySelector('.tr_order_no') 
            await setProductNumList(order_no.value,1);

            setTimeout(
                ()=>{
                    window.location.href = "/productBox";
                }
                , 200 );
        })
    });
})
async function setProductNumList(order_no,num) {
    let productList = JSON.parse(window.localStorage.getItem('productList'))??[]
    let productNumList = JSON.parse(window.localStorage.getItem('productNumList'))??[];

    let productNum = productNumList.find((val)=>val.order_no == order_no);
    let product = productList.find((val)=>val == order_no);
    if(typeof productNum == "undefined"){
        productNumList.push({order_no,num})
    }
    if(typeof product == "undefined"){
        productList.push(order_no)
    }
    window.localStorage.setItem('productNumList',  JSON.stringify(productNumList));
    window.localStorage.setItem('productList',  JSON.stringify(productList));
}
async function cadDownload(key,ext){
    const requestBody = {
          "data": [{
                      "key": key,
                      "ext": [
                        ext
                      ]
                   }]
    };

    const response = await fetch("/api/cadDownload", {
              method: "POST", 
              headers: {
                'Content-Type': 'application/json' 
              },
              body: JSON.stringify(requestBody),    
        });
    const disposition = response.headers.get('Content-Disposition');
    if (disposition && disposition.indexOf('attachment') !== -1) {
          var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
          var matches = filenameRegex.exec(disposition);
          if (matches != null && matches[1]) {
            const fileName = decodeURIComponent(matches[1].replace(/['"]/g, ''));
            const a = document.createElement('a');
            a.href = window.URL.createObjectURL(await response.blob());
            a.download = fileName;
            a.click();
          }
    }
}
const check = (node,index)=>{
    if(node.checked){
        node.parentNode.parentNode.className = 'checked';
    }else{
        node.parentNode.parentNode.className = '';
    }
}

