
<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <title>KAKAKU-FILE</title>
  <style>
    body { font-family: sans-serif; }
    nav { margin-bottom: 20px; }
    nav button { margin-right: 10px; padding: 8px 12px; }
    .section { display: none; }
    .active { display: block; }
    table { border-collapse: collapse; margin-top: 10px; }
    th, td { border: 1px solid #999; padding: 5px; }
    select, input[type='number'], input[type='text'] { width: 150px; }
  </style>
</head>
<body>
  <h1>KAKAKU-FILE</h1>
  <nav>
    <button onclick="switchSection('search')">さがす</button>
    <button onclick="switchSection('calc')">みつもる</button>
  </nav>

  <!-- 単価検索ツール -->
  <div id="search" class="section active">
    <h2>単価検索ツール</h2>
    <input type="file" id="searchCsvFile" accept=".csv">
    <br><br>
    <label>カテゴリ選択：</label>
    <select id="categoryFilter"><option value="">すべて</option></select>
    <br><br>
    <label>掛け率（検索結果にも反映）：</label>
<input type="number" id="searchMultiplier" value="1" step="0.01" min="0"><button onclick="search()">適用</button><br><br>
<label>キーワード検索（品名・備考）：</label>
    <input type="text" id="keyword" placeholder="例：グラス 90mm 高性能">
    <button onclick="search()">検索</button>
    <br><br>
    <div id="results"></div>
  </div>

  <!-- 合計計算ツール -->
  <div id="calc" class="section">
    <h2>見積ツール</h2>
    <label>① 単価リストCSVを読み込む：</label>
    <input type="file" id="calcCsvFile" accept=".csv">
    <br><br>
    <label>掛け率：</label>
<input type="number" id="calcMultiplier" value="1" step="0.01" min="0"><button onclick="recalculateSubtotals()">適用</button><br><br>
<label>② カテゴリを選択：</label>
    <select id="categorySelect" onchange="populateItems()">
      <option value="">-- カテゴリを選んでください --</option>
    </select>
    <br><br>
    <label>③ 資材と数量を選択：</label>
    <div id="itemTableContainer">
      <table id="itemTable">
        <tr><th>資材名</th><th>単価</th><th>数量</th><th>単位</th><th>小計</th></tr>
      </table>
      <button onclick="addItemRow()">＋ 資材行を追加</button>
    </div>
    <br>
    <button onclick="calculateTotal()">計算する</button>
    <button onclick="downloadCSV()">CSVで保存</button>
    <br><br>
    <div id="totalDisplay"></div>
  </div>

  <script>
    function switchSection(id) {
      document.querySelectorAll('.section').forEach(sec => sec.classList.remove('active'));
      document.getElementById(id).classList.add('active');
    }

    // --- Shared data ---
    let searchMaterials = [];
    let calcMaterials = [];
    let filteredItems = [];
    let selectedCategory = "";

    // --- Search Tool ---
    document.getElementById('searchCsvFile').addEventListener('change', function(event) {
      const file = event.target.files[0];
      const reader = new FileReader();
      reader.onload = function(e) {
        const lines = e.target.result.split('\n').filter(Boolean);
        const headers = lines[0].split(',');
        searchMaterials = lines.slice(1).map(line => {
          const values = line.split(',');
          return headers.reduce((obj, key, i) => {
            obj[key.trim()] = values[i]?.trim() || '';
            return obj;
          }, {});
        });

        const categories = [...new Set(searchMaterials.map(m => m['カテゴリ']))];
        const categorySelect = document.getElementById('categoryFilter');
        categorySelect.innerHTML = `<option value="">すべて</option>` +
          categories.map(cat => `<option value="${cat}">${cat}</option>`).join('');
      };
      reader.readAsText(file, 'Shift_JIS');
    });

    function search() {
      const keyword = document.getElementById('keyword').value.trim();
      const words = keyword.split(/\s+/);
      const selectedCategory = document.getElementById('categoryFilter').value;

      const results = searchMaterials.filter(item => {
        const matchesCategory = !selectedCategory || item['カテゴリ'] === selectedCategory;
        const searchableText = [
          item['品名'], item['備考1'], item['備考2'], item['備考3'], item['備考4'], item['備考5']
        ].join(' ');
        const matchesKeyword = words.every(word => searchableText.includes(word));
        return matchesCategory && matchesKeyword;
      });

      const multiplier = parseFloat(document.getElementById('searchMultiplier').value) || 1;
let html = `<table><tr><th>カテゴリ</th><th>品名</th><th>単価（掛け後）</th><th>単位</th><th>仕入先</th><th>備考</th></tr>`;
      results.forEach(item => {
        const remarks = ['備考1', '備考2', '備考3', '備考4', '備考5'].map(k => item[k]).filter(val => val).join(' / ');
        const adjusted = (parseFloat(item['単価']) || 0) * multiplier;
html += `<tr><td>${item['カテゴリ']}</td><td>${item['品名']}</td><td>${adjusted}</td><td>${item['単位']}</td><td>${item['仕入先']}</td><td>${remarks}</td></tr>`;
      });
      html += `</table>`;
      document.getElementById('results').innerHTML = results.length ? html : '該当なし';
    }

    // --- Calc Tool ---
    document.getElementById('calcCsvFile').addEventListener('change', function(event) {
      const file = event.target.files[0];
      const reader = new FileReader();
      reader.onload = function(e) {
        const lines = e.target.result.split('\n').filter(Boolean);
        const headers = lines[0].split(',');
        calcMaterials = lines.slice(1).map(line => {
          const values = line.split(',');
          return headers.reduce((obj, key, i) => {
            obj[key.trim()] = values[i]?.trim() || '';
            return obj;
          }, {});
        });

        const categories = [...new Set(calcMaterials.map(m => m['カテゴリ']).filter(Boolean))];
        const catSelect = document.getElementById('categorySelect');
        catSelect.innerHTML = '<option value="">-- カテゴリを選んでください --</option>';
        categories.forEach(cat => {
          const opt = document.createElement('option');
          opt.value = cat;
          opt.textContent = cat;
          catSelect.appendChild(opt);
        });

////        alert('CSV読み込み完了 (' + calcMaterials.length + ' 件)');
      };
      reader.readAsText(file, 'Shift_JIS');
    });

    function populateItems() {
      selectedCategory = document.getElementById('categorySelect').value;
      filteredItems = calcMaterials.filter(m => m['カテゴリ'] === selectedCategory);
      document.getElementById('itemTable').innerHTML = '<tr><th>資材名</th><th>単価</th><th>数量</th><th>単位</th><th>小計</th></tr>';
      addItemRow();
    }

    function addItemRow() {
      const table = document.getElementById('itemTable');
      const row = table.insertRow(-1);
      const itemCell = row.insertCell(0);
      const priceCell = row.insertCell(1);
      const qtyCell = row.insertCell(2);
      const unitCell = row.insertCell(3);
      const subtotalCell = row.insertCell(4);

      const itemSelect = document.createElement('select');
      const defaultOpt = document.createElement('option');
      defaultOpt.value = "";
      defaultOpt.textContent = "--選択--";
      itemSelect.appendChild(defaultOpt);

      filteredItems.forEach(m => {
        const opt = document.createElement('option');
        opt.value = m['品名'];
        opt.textContent = m['品名'];
        itemSelect.appendChild(opt);
      });

      const priceInput = document.createElement('input');
      priceInput.type = 'text';
      priceInput.readOnly = true;

      const qtyInput = document.createElement('input');
      const unitSpan = document.createElement('span');
      unitSpan.style.marginLeft = '6px';
      qtyInput.type = 'number';
      qtyInput.min = '0';
      qtyInput.value = '0';

      const subtotalSpan = document.createElement('span');

      itemSelect.onchange = function() {
        const selected = filteredItems.find(m => m['品名'] === itemSelect.value);
        if (selected) {
          priceInput.value = selected['単価'];
          unitSpan.textContent = selected['単位'] || '';
        } else {
          priceInput.value = '';
        }
      };

      [qtyInput, itemSelect].forEach(input => {
        input.addEventListener('input', () => {
          const price = parseFloat(priceInput.value) || 0;
          const qty = parseFloat(qtyInput.value) || 0;
          subtotalSpan.textContent = price * qty;
        });
      });

      itemCell.appendChild(itemSelect);
      priceCell.appendChild(priceInput);
      qtyCell.appendChild(qtyInput);
      unitCell.appendChild(unitSpan);
      subtotalCell.appendChild(subtotalSpan);
    }

function calculateTotal() {
  const rows = document.querySelectorAll('#itemTable tr');
  let total = 0;
  const results = [];

  rows.forEach((row, idx) => {
    if (idx === 0) return;
    const item = row.cells[0].querySelector('select').value;
    const unit = parseFloat(row.cells[1].querySelector('input').value) || 0;
    const qty = parseFloat(row.cells[2].querySelector('input').value) || 0;
    const subtotal = unit * qty;
    row.cells[4].querySelector('span').textContent = subtotal.toFixed(2);
    if (item) {
      results.push({ item, unit, qty, subtotal });
      total += subtotal;
    }
  });

  window.lastResults = results;
  document.getElementById('totalDisplay').innerHTML = `<h3>合計金額:${total.toLocaleString()}</h3>`;
}


    function downloadCSV() {
      if (!window.lastResults || !window.lastResults.length) return alert('先に計算してください');
      let csv = '品名,単価,単位,数量,小計\n';
      window.lastResults.forEach(r => {
      const match = filteredItems.find(m => m['品名'] === r.item);
      const unitLabel = match ? match['単位'] : '';
        csv += `${r.item},${r.unit},${unitLabel},${r.qty},${r.subtotal}\n`;
      });
      const total = window.lastResults.reduce((sum, r) => sum + r.subtotal, 0);
      csv += `,,,合計,${total}\n`;

      const BOM = new Uint8Array([0xEF, 0xBB, 0xBF]);
      const blob = new Blob([BOM, csv], { type: 'text/csv' });
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = '見積結果.csv';
      a.click();
      URL.revokeObjectURL(url);
    }
  
    
    function recalculateSubtotals() {
      const rows = document.querySelectorAll('#itemTable tr');
      const multiplier = parseFloat(document.getElementById("calcMultiplier").value) || 1;
      rows.forEach((row, idx) => {
        if (idx === 0) return;
        const priceInput = row.cells[1].querySelector('input');
        const qtyInput = row.cells[2].querySelector('input');
        const subtotalSpan = row.cells[4].querySelector('span');
        let originalPrice = parseFloat(priceInput.dataset.original) || parseFloat(priceInput.value) || 0;

        // Save original price if not already stored
        if (!priceInput.dataset.original) {
          priceInput.dataset.original = originalPrice;
        }

        const adjustedPrice = originalPrice * multiplier;
        priceInput.value = adjustedPrice.toFixed(2);

        const qty = parseFloat(qtyInput.value) || 0;
        subtotalSpan.textContent = adjustedPrice * qty;
      });
    }


</script>
</body>
</html>

