{% extends "base.html" %}

{% block title %}
{{ stock.name }} - My Flask App
{% endblock %}

{% block content %}
<h1 class="h3 mb-3">{{ stock.name }} {{ stock.code }}</h1>

<div class="editable-area" contenteditable="true" id="editableArea">
  {{ stock.memo }}
</div>


<script>
  document.addEventListener('DOMContentLoaded', () => {
    const editableArea = document.getElementById('editableArea');

    // フォーカスが外れたときのイベントリスナー
    editableArea.addEventListener('blur', () => {
      const content = editableArea.textContent.trim();

      // サーバに保存するリクエストを送信
      fetch('/update_stock_memo/{{ stock.code }}', {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ content: content }),
      })
        .then(response => {
          if (response.ok) {
            return response.json();
          } else {
            throw new Error('Failed to save content');
          }
        })
        .then(data => {
          console.log('Saved successfully:', data);
        })
        .catch(error => {
          console.error('Error saving:', error);
        });

    });
  });
</script>


<div class="row">
  <div class="col-xl-12 col-xxl-5 d-flex">
    <div class="w-100">
      <div class="card">
        <div class="card-body">

          <!-- タブのナビゲーション -->
          <ul class="nav nav-tabs mb-3" id="myTab" role="tablist">

            <!-- チャートのタブ -->
            <li class="nav-item" role="presentation">
              <button class="nav-link active" id="chart-tab" data-bs-toggle="tab" data-bs-target="#chart" type="button"
                role="tab" aria-controls="chart" aria-selected="true">Chart</button>
            </li>

            <!-- 財務状態のタブ -->
            <li class="nav-item" role="presentation">
              <button class="nav-link" id="finance-tab" data-bs-toggle="tab" data-bs-target="#finance" type="button"
                role="tab" aria-controls="finance" aria-selected="false">Finance</button>
            </li>

          </ul>

          <!-- タブのコンテンツ -->
          <div class="tab-content" id="myTabContent">

            <!-- チャート表示領域 -->
            <div class="tab-pane fade show active" id="chart" role="tabpanel" aria-labelledby="chart-tab">

              <!-- トレンドラインを表示するためのフォーム -->
              <form id="trendline-form" class="float-end d-flex flex-nowrap align-items-center gap-2">

                <div class="d-flex align-items-center">
                  <label for="lookback" class="form-label mb-0 me-1">Lookback:</label>
                  <input type="number" id="lookback" class="form-control form-control-sm input-wrapper"
                    style="width: 60px;" value="100">
                </div>

                <div class="d-flex align-items-center">
                  <label for="min_touches" class="form-label mb-0 me-2">Min:</label>
                  <input type="number" id="min_touches" class="form-control form-control-sm input-wrapper"
                    style="width: 44px;" value="5">
                </div>

                <div class="d-flex align-items-center">
                  <label for="order" class="form-label mb-0 me-1">Order:</label>
                  <input type="number" id="order" class="form-control form-control-sm input-wrapper"
                    style="width: 44px;" value="5">
                </div>

                <button type="button" id="trendline-button" class="btn btn-sm btn-secondary btn-no-outline">更新</button>

                <button type="button" id="trendline-disable-button"
                  class="btn btn-sm btn-secondary btn-no-outline">消去</button>
              </form>

              <!-- チャート表示部分 -->
              <div id="container">Loading....</div>
            </div>

            <!-- 財務状態表示領域 -->
            <div class="tab-pane fade" id="finance" role="tabpanel" aria-labelledby="finance-tab">
              <div class="d-flex align-items-start ps-3 pe-3 pb-3">
                <div class="flex">
                  <span class="me-3"><strong>PER</strong> {{ per }} </span>
                  <span class="me-3"><strong>PBR</strong> {{ pbr }} </span>
                  <span class="me-3"><strong>配当利回り</strong> {{ dividend_yield }}% </span>
                </div>
              </div>

              <div class="row">
                <div class="col-12 col-lg-6">
                  <div class="card">
                    <div class="card-header">
                      <h5 class="card-title">売上高</h5>
                    </div>
                    <div class="card-body">
                      <div class="chart">
                        <canvas id="revenue_bar"></canvas>
                      </div>
                    </div>
                  </div>
                </div>

                <div class="col-12 col-lg-6">
                  <div class="card flex-fill w-100">
                    <div class="card-header">
                      <h5 class="card-title">売上総利益率</h5>
                    </div>
                    <div class="card-body">
                      <div class="chart">
                        <canvas id="gross_profit_margin_line"></canvas>
                      </div>
                    </div>
                  </div>
                </div>
              </div>

              <div class="row">
                <div class="col-12 col-lg-6">
                  <div class="card">
                    <div class="card-header">
                      <h5 class="card-title">営業利益</h5>
                    </div>
                    <div class="card-body">
                      <div class="chart">
                        <canvas id="operating_income_bar"></canvas>
                      </div>
                    </div>
                  </div>
                </div>

                <div class="col-12 col-lg-6">
                  <div class="card flex-fill w-100">
                    <div class="card-header">
                      <h5 class="card-title">当期純利益</h5>
                    </div>
                    <div class="card-body">
                      <div class="chart">
                        <canvas id="net_income_bar"></canvas>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>


<script>
  // 日付リストを yyyy-mm-dd に変換
  function formatDatesToYYYYMMDD(dates) {
    return dates.map(dateString => {
      const date = new Date(dateString);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0'); // 月は0始まりなので+1
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    });
  }

  document.addEventListener("DOMContentLoaded", function () {

    const chartData = {{ revenue | tojson
  }};

  chartData.date = formatDatesToYYYYMMDD(chartData.dates);

  // 単位を変換（億円単位）
  const normalizedSalesData = chartData.values.map(value => value / 1e8);

  // 棒グラフ
  new Chart(document.getElementById("revenue_bar"), {
    type: "bar",
    data: {
      labels: chartData.date,
      datasets: [{
        label: '売上高 (億円)',
        backgroundColor: window.theme.primary,
        borderColor: window.theme.primary,
        hoverBackgroundColor: window.theme.primary,
        hoverBorderColor: window.theme.primary,
        data: normalizedSalesData, // 正規化したデータ
        barPercentage: .75,
        categoryPercentage: .5
      }]
    },
    options: {
      responsive: true, // 自動リサイズ
      maintainAspectRatio: false, // サイズ固定を無効化
    },
  });
    });
</script>


<script>
  document.addEventListener("DOMContentLoaded", function () {

    var ctx = document.getElementById("gross_profit_margin_line").getContext("2d");
    var gradient = ctx.createLinearGradient(0, 0, 0, 225);
    gradient.addColorStop(0, "rgba(215, 227, 244, 1)");
    gradient.addColorStop(1, "rgba(215, 227, 244, 0)");

    const chartData = {{ gross_profit_margin | tojson
  }};

  // dateを変換
  chartData.date = formatDatesToYYYYMMDD(chartData.dates);

  // Line chart
  new Chart(document.getElementById("gross_profit_margin_line"), {
    type: "line",
    data: {
      labels: chartData.date,
      datasets: [{
        label: "売上総利益率",
        fill: true,
        backgroundColor: "transparent",
        borderColor: window.theme.primary,
        data: chartData.values
      }]
    },
    options: {
      responsive: true, // 自動リサイズ
      maintainAspectRatio: false, // サイズ固定を無効化
      legend: {
        display: false,
      },
      tooltips: {
        intersect: false
      },
      hover: {
        intersect: true
      },
      plugins: {
        filler: {
          propagate: false
        }
      },
      layout: {
        padding: {
          top: 0, // グラフ全体の上側余白
          right: 20, // 右側余白
          bottom: 10, // 下側余白
          left: 20 // 左側余白
        }
      }
    }
  });

    });
</script>



<script>

  document.addEventListener("DOMContentLoaded", function () {

    const chartData = {{ operating_income | tojson
  }};

  // "date" を変換
  chartData.date = formatDatesToYYYYMMDD(chartData.dates);

  // 単位を変換（億円単位）
  const normalizedSalesData = chartData.values.map(value => value / 1e8);

  // Bar chart
  new Chart(document.getElementById("operating_income_bar"), {
    type: "bar",
    data: {
      labels: chartData.date,
      datasets: [{
        label: '営業利益 (億円)',
        backgroundColor: window.theme.primary,
        borderColor: window.theme.primary,
        hoverBackgroundColor: window.theme.primary,
        hoverBorderColor: window.theme.primary,
        data: normalizedSalesData, // 正規化したデータ
        barPercentage: .75,
        categoryPercentage: .5
      }]
    },
    options: {
      responsive: true, // 自動リサイズ
      maintainAspectRatio: false, // サイズ固定を無効化
    },
  });
    });
</script>



<script>

  document.addEventListener("DOMContentLoaded", function () {

    const chartData = {{ net_income | tojson
  }};

  // "date" を変換
  chartData.date = formatDatesToYYYYMMDD(chartData.dates);

  // 単位を変換（億円単位）
  const normalizedSalesData = chartData.values.map(value => value / 1e8);

  // 棒グラフ
  new Chart(document.getElementById("net_income_bar"), {
    type: "bar",
    data: {
      labels: chartData.date,
      datasets: [{
        label: '当期純利益 (億円)',
        backgroundColor: window.theme.primary,
        borderColor: window.theme.primary,
        hoverBackgroundColor: window.theme.primary,
        hoverBorderColor: window.theme.primary,
        data: normalizedSalesData, // 正規化したデータ
        barPercentage: .75,
        categoryPercentage: .5
      }]
    },
    options: {
      responsive: true, // 自動リサイズ
      maintainAspectRatio: false // サイズ固定を無効化
    },
  });



    });
</script>



<script>

  // データの前処理
  const chartData = {{ chart_data | tojson }};
  const dates = chartData.date.map(date => Date.UTC(new Date(date).getFullYear(), new Date(date).getMonth(), new Date(date).getDate()));

  const baseSeries = [
    {
      type: 'candlestick', name: '株価', yAxis: 0,
      data: dates.map((date, i) => [date, chartData.open[i], chartData.high[i], chartData.low[i], chartData.close[i]]),
      dataGrouping: { units: [["day", [1]]] }
    },
    { type: 'line', name: '移動平均線 (5日)', yAxis: 0, data: dates.map((date, i) => [date, chartData.ma5[i]]), color: 'magenta', lineWidth: 1 },
    { type: 'line', name: '移動平均線 (25日)', yAxis: 0, data: dates.map((date, i) => [date, chartData.ma25[i]]), color: 'limegreen', lineWidth: 1 },
    { type: 'arearange', name: 'ボリンジャーバンド', yAxis: 0, data: dates.map((date, i) => [date, chartData.lower2[i], chartData.upper2[i]]), color: '#7cb5ec', fillOpacity: 0.15, lineWidth: 0, enableMouseTracking: false },

    { type: 'line', name: '短期 RCI', yAxis: 1, data: dates.map((date, i) => [date, chartData.rci9[i]]), color: 'magenta', lineWidth: 1 },

    { type: 'line', name: '長期 RCI', yAxis: 1, data: dates.map((date, i) => [date, chartData.rci26[i]]), color: 'green', lineWidth: 1 },
    { type: 'line', name: 'MACD', yAxis: 2, data: dates.map((date, i) => [date, chartData.macd[i]]), color: 'magenta', lineWidth: 1 },
    { type: 'line', name: 'SIGNAL', yAxis: 2, data: dates.map((date, i) => [date, chartData.macd_signal[i]]), color: 'green', lineWidth: 1 },
    { type: 'column', name: 'Volume', yAxis: 3, data: dates.map((date, i) => [date, chartData.volume[i]]), color: 'slategray', lineWidth: 1 },
  ];

  let showBand = {{ is_rise | lower }}; // 上がるパターンに合致しているか

  // 直近3日間の範囲を取得
  let lastDate = new Date(dates[dates.length - 1]);
  let threeDaysAgo = new Date(lastDate);
  threeDaysAgo.setDate(lastDate.getDate() - 2);

  const options = {
    chart: {
      renderTo: 'container',
      width: 800,
      height: 800
    },
    rangeSelector: {
      selected: 2,
      inputDateFormat: '%Y-%m-%d',
      inputEditDateFormat: '%Y-%m-%d',
      inputEnabled: true
    },
    xAxis: {
      type: 'datetime',
      dateTimeLabelFormats: {
        day: '%Y-%m-%d',
        week: '%Y-%m-%d',
        month: '%Y-%m',
        year: '%Y'
      },
      // 上がるパターンに合致していれば直近3日間に背景色をつける
      plotBands: showBand ? [{
        from: threeDaysAgo.getTime(),
        to: lastDate.getTime(),
        color: 'rgba(255, 69, 0, 0.2)'  // 背景色
      }] : [],
    },
    tooltip: {
      shared: true, // すべてのシリーズをまとめて表示
      formatter: function () {
        const indent = (spaceCount) =>
          `<span style="white-space: pre;">${' '.repeat(spaceCount)}</span>`;

        let s = `<b>${Highcharts.dateFormat('%Y-%m-%d', this.x)}</b><br>`;

        this.points.forEach(point => {
          if (point.series.type === 'candlestick') {
            s += `<span style="color:${point.series.color}">\u25CF</span>
                            ${point.series.name}:<br>` +
              `${indent(4)}Open: ${point.point.open.toLocaleString()}<br>` +
              `${indent(4)}High: ${point.point.high.toLocaleString()}<br>` +
              `${indent(4)}Low: ${point.point.low.toLocaleString()}<br>` +
              `${indent(4)}Close: ${point.point.close.toLocaleString()}<br>`;
          } else {
            s += `<span style="color:${point.color}">\u25CF</span> ${point.series.name}: ${point.y.toLocaleString()}<br>`;
          }
        });
        return s;
      }
    },
    yAxis: [
      {
        title: { text: "株価", align: "middle" },
        labels: {
          align: "center",
          enabled: true,
        },
        height: "70%",
        offset: 30
      },
      {
        title: { text: "RCI", align: "middle", },
        labels: { align: "center", enabled: true },
        top: "70%",
        height: "10%",
        offset: 30
      },
      {
        title: { text: "MACD", align: "middle", },
        labels: { align: "center", enabled: true },
        top: "80%",
        height: "10%",
        offset: 30
      },
      {
        title: { text: "Volume", align: "middle", },
        labels: { align: "center", enabled: true },
        top: "90%",
        height: "10%",
        offset: 30
      }
    ],
    series: [
      ...baseSeries,
    ],
  };

  // トレンドラインの始点と終点を取得
  function fetchTrendLines() {
    const params = new URLSearchParams({
      lookback: document.getElementById("lookback").value,
      min_touches: document.getElementById("min_touches").value,
      order: document.getElementById("order").value
    });

    fetch(`/update_trendlines/{{ stock.code }}?${params.toString()}`)
      .then(response => {
        if (!response.ok) {
          throw new Error(`HTTPエラー: ${response.status}`);
        }
        return response.json();
      })
      .then(data => {
        updateTrendLines(data);
      })
      .catch(error => {
        console.error("トレンドライン取得エラー:", error);
      });
  }

  // トレンドラインの始点と終点をチャートに表示する形式に変換
  function updateTrendLines(trendLines) {
    let trendlineSeries = trendLines.map((line, i) => ({
      type: "line",
      name: `Trendline ${i + 1}`,
      yAxis: 0,
      color: line.type === "uptrend" ? "blue" : "red",
      lineWidth: 2,
      data: [
        [Date.UTC(new Date(line.start[0]).getFullYear(), new Date(line.start[0]).getMonth(), new Date(line.start[0]).getDate()), line.start[1]],
        [Date.UTC(new Date(line.end[0]).getFullYear(), new Date(line.end[0]).getMonth(), new Date(line.end[0]).getDate()), line.end[1]]
      ]
    }));

    // チャートに表示するシリーズを指定
    options.series = [
      ...baseSeries,
      ...trendlineSeries
    ];

    // 新しくチャートを再生成
    new Highcharts.StockChart(options);
  }

  document.addEventListener("DOMContentLoaded", function () {
    // チャートを表示
    new Highcharts.StockChart(options);

    // トレンドラインの処理
    document.getElementById("trendline-button").addEventListener("click", function () {
      fetchTrendLines();
    });

    document.getElementById("trendline-disable-button").addEventListener("click", function () {
      options.series = [
        ...baseSeries,
      ];
      new Highcharts.StockChart(options);
    });
  });
</script>

<link href="https://www.highcharts.com/highslide/highslide.css" rel="stylesheet">
<script src="https://code.highcharts.com/stock/6/highstock.js"></script>
<script src="https://code.highcharts.com/6/highcharts-more.js"></script>
<style>
  #container {
    padding: 20px;
    margin: 0 auto;
    display: block;
  }
</style>

{% endblock %}