const baseTrHTML = (index) => {
    let trHTML = `
    <tr class="prodbox-item tr_index`+ index + `" data-index="` + index + `">
    <td>&nbsp;</td>
    <td>&nbsp;</td>
    <td class="ordernum"><input type="text" class="ordernum order_no" inputmode="tel" onChange="callbackChangeOrderNo(event.target)"></td>
    <td>&nbsp;</td>
    <td><input type="text" class="number" inputmode="tel"></td>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
    <td class="sticky_right"><input type="button" onclick="addProduct(`+ index + `);" value="リストに追加"></td>
    </tr>
    `;

    return trHTML
}
const getProductBox = () => {
    return JSON.parse(window.localStorage.getItem('productList')) ?? [];
}
const removeProBox = (order_no) => {
    const target_row = document.querySelector('.tr' + order_no);
    if (target_row) {
        target_row.remove();
        callbackChangeNumnber(target_row.querySelector('.number'));
        setProductListStorage(order_no, "remove")
        setProductNumListStorage(order_no, 0, "remove")
    }
}
const getProduct = async (order_no) => {
    const response = await fetch("/api/detail?orderno=" + order_no, {
        method: "POST",
        headers: {
            'Content-Type': 'application/json'
        },
    })
    const data = await response.json();
    return data;
}
const setProductTr = (data, order_no, index, number) => {
    const cad2flag = (data[0].CA2D1) ? true : false;
    const cad3flag = (data[0].CA3D1 || data[0].CA3D2) ? true : false;
    let kakaku = (data[0].ITEM49).replace(/,/g, "");
    return `
    <tr class="prodbox-item tr`+ order_no + ` tr_index` + index + `" data-index="` + index + `">
    <td><img src="/Catalog/CatalogPic/`+ data[0].PIC1 + `" width="80" height="80" alt=""></td>
    <td><a href="/product?key=`+ data[0].BKEY + `" target="_blank" >` + data[0].HNAME + `</a></td>
    <td class="ordernum">
    `+ order_no + `
    <input type="hidden" class="order_no_hidden" name="order_no[]" value="`+ order_no + `" >
    </td>
    <td>`+ data[0].HNBAN + `</td>
    <td>
    <input type="number" class="number" name="num[`+ order_no + `]" inputmode="tel" value="` + number + `" onChange="callbackChangeNumnber(event.target)">
    <input type="hidden" class="kakaku"  value="`+ kakaku + `"  />
    </td>
    <td>-円</td>
    <td>
    `+ ((cad2flag) ? '<input type="checkbox" class="checkbox2D" value="' + order_no + '">' : '該当無し') + `
    </td>
    <td>
    `+ ((cad3flag) ? '<input type="checkbox" class="checkbox3D" value="' + order_no + '">' : '該当無し') + `
    </td>
    <td class="sticky_right"><input type="button" class="removeProBox" onclick="removeProBox(`+ order_no + `)" value="削除"></td>
    </tr>
    `;

}
const addProduct = async (index) => {
    setTimeout(
        function () { }
        , 200);
    const target_row = document.querySelector('.tr_index' + index);
    const productTable = document.querySelector('.productBox');
    const tbody = productTable.querySelector('tbody');
    if (target_row) {
        const order_num = target_row.querySelector('.order_no')
        if (order_num && !order_num.value) {
            alert('オーダーNo.を入力して下さい。');
            return false;
        }
        if (order_num && !/^[0-9]+$/.test(order_num.value)) {
            alert('オーダーNo.は数字のみ入力してください。');
            return false;
        }
        const trim_order_no = (order_num.value).trim()
        if (!checkDoubleOrdeNo(trim_order_no)) {
            return false;
        }
        const data = await getProduct(trim_order_no);
        if (data.length == 0) {
            alert('該当のオーダーNo.の製品は存在しませんでした。');
            return false;
        }
        const number = target_row.querySelector('.number');
        const trProduct = setProductTr(data, trim_order_no, index, number.value);
        target_row.insertAdjacentHTML("afterend", trProduct);
        target_row.remove();
        setProductListStorage(trim_order_no)
        const new_row = document.querySelector('.tr_index' + index);
        callbackChangeNumnber(new_row.querySelector('.number'));
        index++;
    }
    //  const trNodes = productTable.querySelectorAll('.prodbox-item');
    // tbody.insertAdjacentHTML("beforeend", baseTrHTML(trNodes.length))
}
const deleteNum = () => {
    const productTable = document.querySelector('.productBox');
    const trNodes = productTable.querySelectorAll('.prodbox-item');
    for (const node of trNodes) {
        const number = node.querySelector('.number');
        if (number) {
            number.value = "";
        }
        const sum_kakaku_hidden = document.querySelector('.sum_kakaku');
        if (sum_kakaku_hidden) {
            sum_kakaku_hidden.parentElement.textContent = "-円";
            sum_kakaku_hidden.remove();
        }
        callbackChangeNumnber(node)
        const order_no = node.querySelector('.order_no_hidden')
        if (order_no && order_no.value) {
            setProductNumListStorage(order_no.value, '', 'remove');
        }
    }
}
const addBulkProduct = async () => {
    setTimeout(
        function () { }
        , 200);
    const productTable = document.querySelector('.productBox');
    const trNodes = productTable.querySelectorAll('.prodbox-item');
    for (const node of trNodes) {
        const index = node.dataset.index;
        if (index) {
            const target_row = document.querySelector('.tr_index' + index);
            if (target_row) {
                const order_no = target_row.querySelector('.order_no');
                const number = target_row.querySelector('.number');
                if (order_no && order_no.value) {
                    if (order_no && !/^[0-9]+$/.test(order_no.value)) {
                        alert('オーダーNo.は数字のみ入力してください。');
                        return false;
                    }
                    const data = await getProduct(order_no.value);
                    if (data.length > 0) {
                        const trProduct = setProductTr(data, order_no.value, index, number.value);
                        target_row.insertAdjacentHTML("afterend", trProduct);
                        target_row.remove();
                        setProductListStorage(order_no.value)
                    }
                }
                const new_target_row = document.querySelector('.tr_index' + index);
                const new_number = new_target_row.querySelector('.number');
                new_number.value = number.value;
                callbackChangeNumnber(new_number)
            }
            //  const trNodes = productTable.querySelectorAll('.prodbox-item');
            // tbody.insertAdjacentHTML("beforeend", baseTrHTML(trNodes.length))
        }
    }
}
const addBulkDelete = async () => {
    const message = '一括削除してもよろしいですか？';

    if (window.confirm(message)) {
        localStorage.removeItem('productNumList');
        localStorage.removeItem('productList');
        window.location.reload();
    }
}
const bulkDownloadCAD = async () => {
    const productTable = document.querySelector('.productBox');
    const trNodes = productTable.querySelectorAll('.prodbox-item');
    let requestData = [];
    for (const node of trNodes) {
        const CA2D1 = node.querySelector('.checkbox2D:checked');
        const CA3D1 = node.querySelector('.checkbox3D:checked');
        const order_no = node.querySelector('.order_no_hidden');
        let ext = [];
        if (CA2D1) {
            ext.push('CA2D1');
        }
        if (CA3D1) {
            ext.push('CA3D1');
        }
        if (order_no && order_no.value && ext.length > 0) {
            let data = {
                "key": order_no.value,
                "ext": ext
            }
            requestData.push(data);
        }
    }
    if (requestData.length > 0) {
        const requestBody = {
            "data": requestData
        };
        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 bulkStockCheck = () => {
    const trNodes = document.querySelectorAll('.prodbox-item');
    let check = true;
    trNodes.forEach((trNode) => {
        const num = trNode.querySelector('.number');
        const order_no_hidden = trNode.querySelector('.order_no_hidden');
        if ((!num || !num.value) && order_no_hidden) {
            check = false;
        }
    });
    if (check) {
        const form = document.getElementById('form_table');
        form.submit();
    } else {
        alert("個数を入力してください。");
    }
}
const cilickInquiry = () => {
    const form = document.getElementById('form_table');
    form.submit();
}
const checkDoubleOrdeNo = (order_no) => {
    let order_no_hidden_list = document.querySelectorAll('.order_no_hidden');
    for (const order_no_hidden of order_no_hidden_list) {
        if (order_no_hidden.value && order_no == order_no_hidden.value) {
            alert("追加済みのオーダーNo.です。");
            return false;
        }
    }
    return true;
}
const callbackChangeNumnber = (numberNode) => {
    if (numberNode.value && numberNode.nextElementSibling && numberNode.nextElementSibling.value && !isNaN(numberNode.value) && !isNaN(numberNode.nextElementSibling.value)) {
        const kakaku = numberNode.nextElementSibling.value * numberNode.value;
        numberNode.parentNode.nextElementSibling.textContent = kakaku.toLocaleString() + '円';
        numberNode.parentNode.nextElementSibling.insertAdjacentHTML("beforeend", '<input type="hidden" class="sum_kakaku" value="' + kakaku + '"  />')
        const numNode_order_no = ((numberNode.name).replace("num[", '')).replace("]", '');
        if (numNode_order_no) {
            setProductNumListStorage(numNode_order_no, numberNode.value);
        }
    } else if (numberNode.nextElementSibling && numberNode.nextElementSibling.value && numberNode.nextElementSibling && numberNode.nextElementSibling.value && numberNode.parentNode.nextElementSibling.nextElementSibling) {
        numberNode.parentNode.nextElementSibling.textContent = '-円';
        const numNode_order_no = ((numberNode.name).replace("num[", '')).replace("]", '');
        // if(numNode_order_no){
        //     setProductNumListStorage(numNode_order_no,'','delete');
        // }
    }
    const sum_kakakuNodes = document.querySelectorAll('.sum_kakaku');
    let sum = 0;
    const sum_goukeiNode = document.querySelector('.sum_goukei');
    if (sum_kakakuNodes.length > 0 && sum_goukeiNode) {
        sum_kakakuNodes.forEach((sum_kakaku) => {
            if (sum_kakaku && sum_kakaku.value && !isNaN(sum_kakaku.value)) {
                sum = sum + Number(sum_kakaku.value);
            }
        });
        sum_goukeiNode.textContent = sum.toLocaleString();
    } else if (sum_kakakuNodes.length == 0 && sum_goukeiNode) {
        sum_goukeiNode.textContent = '';
    }
}
const callbackChangeOrderNo = (target) => {
    const limit = document.querySelectorAll('.prodbox-item');
    if (limit.length > 100) {
        return false;
    }
    const trNode = target.parentElement.parentElement;
    if (trNode) {
        let productTable = document.querySelector('.productBox');
        let tbody = productTable.querySelector('tbody');
        const tr_index = Number(trNode.dataset.index);
        tbody.insertAdjacentHTML("beforeend", baseTrHTML(tr_index + 1))
    }
}
const setProductListStorage = (order_no, type = "add") => {
    let productList = JSON.parse(window.localStorage.getItem('productList')) ?? [];
    let old_count = productList.length;
    if (type == "add") {
        productList.push(order_no);
    } else {
        productList = productList.filter((val) => val != 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);
            }
        }
    }
}

const setProductNumListStorage = (order_no, num, type = "add") => {
    let productNumList = JSON.parse(window.localStorage.getItem('productNumList')) ?? [];
    let productNum = productNumList.find((val) => val.order_no == order_no);
    if (type == "add") {
        if (typeof productNum == "undefined") {
            productNumList.push({ order_no, num })
        } else {
            productNum.num = num;
        }
    } else {

        if (typeof productNum != "undefined") {
            productNumList = productNumList.filter((val) => val.order_no != order_no);
        }
    }

    window.localStorage.setItem('productNumList', JSON.stringify(productNumList));
}
const getProductNum = (order_no) => {
    let productNumList = JSON.parse(window.localStorage.getItem('productNumList')) ?? [];
    let productNum = productNumList.find((val) => val.order_no == order_no);
    if (productNum && Object.keys(productNum).indexOf('num') !== -1) {
        return productNum.num;
    } else {
        return '';
    }

}

window.addEventListener('load', async () => {
    let productBoxList = getProductBox();
    let order_no_hidden_list = document.querySelectorAll('.order_no_hidden');
    for (const order_no_hidden of order_no_hidden_list) {
        if (order_no_hidden.value && !(productBoxList.indexOf(order_no_hidden.value) >= 0)) {
            removeProBox(order_no_hidden.value);
        } else {
            productBoxList = productBoxList.filter((val) => val != order_no_hidden.value);
        }
    }
    let re_order_no_hidden_list = document.querySelectorAll('.order_no_hidden');
    let index = re_order_no_hidden_list.length;
    let productTable = document.querySelector('.productBox');
    let tbody = productTable.querySelector('tbody');
    tbody.insertAdjacentHTML("beforeend", baseTrHTML(index))
    //  tbody.insertAdjacentHTML("beforeend", baseTrHTML(index+1))
    //  tbody.insertAdjacentHTML("beforeend", baseTrHTML(index+2))
    let husoku_index = Number(index);
    for (const order_no of productBoxList) {
        const target_row = document.querySelector('.tr_index' + husoku_index);
        if (target_row) {
            const order_num = target_row.querySelector('.order_no');
            if (order_num) {
                order_num.value = order_no;
                await addProduct(husoku_index);
                husoku_index++;
                const limit = document.querySelectorAll('.prodbox-item');
                if (limit.length < 100) {
                    tbody.insertAdjacentHTML("beforeend", baseTrHTML(husoku_index))
                }
            }
        }
    }
    const numberNodes = document.querySelectorAll('.number');
    numberNodes.forEach((numberNode) => {
        numberNode.addEventListener('change', () => {
            callbackChangeNumnber(numberNode);
        });
        const numNode_order_no = ((numberNode.name).replace("num[", '')).replace("]", '');
        if (numNode_order_no) {
            const num = getProductNum(numNode_order_no);
            numberNode.value = num;
            let event = new Event('change');
            numberNode.dispatchEvent(event);
        }
    });


})
