検索条件 保存機能

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>検索条件の保存・読み込み</title>
    <style>
        .form-group {
            display: flex;
            gap: 10px;
            margin-bottom: 10px;
        }
    </style>
</head>
<body>

    <h2>検索条件を追加</h2>

    <form id="searchForm">
        <div id="formContainer">
            <!-- 元となる検索フォーム -->
            <div class="form-group" id="originalForm">
                <select name="searchField[]">
                    <option value="project_id">プロジェクトID</option>
                    <option value="case_name">案件名</option>
                </select>

                <input type="text" name="searchValue[]" placeholder="検索キーワード">

                <select name="searchCondition[]">
                    <option value="contains">を含む</option>
                    <option value="equals">等しい</option>
                </select>

                <select name="logicalOperator[]">
                    <option value="and">かつ</option>
                    <option value="or">または</option>
                </select>

                <button type="button" onclick="removeForm(this)">削除</button>
            </div>
        </div>

        <button type="button" onclick="addForm()">条件を追加</button>
        <button type="submit">検索</button>
        <button type="button" onclick="exportCSV()">条件を保存 (CSV)</button>
        <input type="file" id="importCSV" accept=".csv" onchange="importCSV(event)">
    </form>

    <script>
        function addForm(field = "", value = "", condition = "", operator = "") {
            const original = document.getElementById("originalForm");
            const newForm = original.cloneNode(true);
            newForm.id = ""; // ID を削除（重複防止）

            // 各フォームの初期値をセット
            const selects = newForm.querySelectorAll("select");
            const input = newForm.querySelector("input");

            if (field) selects[0].value = field;
            if (value) input.value = value;
            if (condition) selects[1].value = condition;
            if (operator) selects[2].value = operator;

            document.getElementById("formContainer").appendChild(newForm);
        }

        function removeForm(button) {
            const formContainer = document.getElementById("formContainer");
            if (formContainer.children.length > 1) {
                button.parentElement.remove();
            } else {
                alert("少なくとも 1 つの検索条件は必要です！");
            }
        }

        // 検索条件を CSV 形式で保存
        function exportCSV() {
            const rows = [];
            const forms = document.querySelectorAll("#formContainer .form-group");

            forms.forEach(form => {
                const selects = form.querySelectorAll("select");
                const input = form.querySelector("input");

                rows.push([
                    selects[0].value, // 検索対象
                    input.value,      // 検索文言
                    selects[1].value, // 検索条件
                    selects[2].value  // 論理演算子
                ].join(","));
            });

            const csvContent = "data:text/csv;charset=utf-8," + rows.join("\n");
            const encodedUri = encodeURI(csvContent);
            const link = document.createElement("a");
            link.setAttribute("href", encodedUri);
            link.setAttribute("download", "search_conditions.csv");
            document.body.appendChild(link);
            link.click();
        }

        // CSV をインポートして検索条件を復元
        function importCSV(event) {
            const file = event.target.files[0];
            if (!file) return;

            const reader = new FileReader();
            reader.onload = function(e) {
                const text = e.target.result;
                const rows = text.split("\n");

                // 現在のフォームをクリア
                document.getElementById("formContainer").innerHTML = "";

                rows.forEach(row => {
                    if (row.trim() === "") return;
                    const [field, value, condition, operator] = row.split(",");
                    addForm(field, value, condition, operator);
                });
            };
            reader.readAsText(file);
        }

        // フォーム送信時のデバッグ用
        document.getElementById("searchForm").addEventListener("submit", function(event) {
            event.preventDefault();

            const formData = new FormData(event.target);
            console.log("検索条件:");
            for (let [key, value] of formData.entries()) {
                console.log(key, ":", value);
            }
        });
    </script>

</body>
</html>