<!-- detail.ejs  股票数据可视化分析，推荐分析  -->

<style>
  #container {
    height: 100%;
    padding: 8px;
  }

  #content {
    padding: 5px 5px;
  }

  #company_news_list {
    max-height: 50vh;
    overflow: auto;
  }

  #right_side {
    margin-right: 5px;
  }
</style>

<div class="columns" id="container">
  <div class="column is-12">
    <!-- 面板 -->
    <nav class="panel">
      <!-- 内容 -->
      <div id="content">
        <div class="tile is-ancestor">
          <div class="tile is-vertical is-8">
            <div class="tile is-vertical ">
              <!-- 股票股价图 -->
              <div class="tile is-parent">
                <article class="tile is-child notification">
                  <p class="title" id="symbol_title"></p>
                  <p class="subtitle" id="price_stock_graph">
                    some description about the stock and the Chart
                  </p>
                  <div>
                    <nav class="panel">
                      <canvas id="myChart"></canvas>
                    </nav>
                  </div>
                </article>
              </div>

              <!-- recommendation index -->
              <div class="tile is-parent">
                <article class="tile is-child notification is-danger">
                  <p class="title"> Latest Recommendation Index </p>
                  <p class="subtitle" id="TODAY_DATE"></p>
                  <nav class="level is-mobile is-multiline">
                    <div class="level-item ">
                      <div>
                        <p class="heading">StrongBuy</p>
                        <p class="title" id="TODAY_SB"></p>
                      </div>
                    </div>
                    <div class="level-item has-text-centered">
                      <div>
                        <p class="heading">Buy</p>
                        <p class="title" id="TODAY_B"></p>
                      </div>
                    </div>
                    <div class="level-item has-text-centered">
                      <div>
                        <p class="heading">Hold</p>
                        <p class="title" id="TODAY_H"></p>
                      </div>
                    </div>
                    <div class="level-item has-text-centered">
                      <div>
                        <p class="heading">Sell</p>
                        <p class="title" id="TODAY_SL"></p>
                      </div>
                    </div>
                    <div class="level-item has-text-centered">
                      <div>
                        <p class="heading">StrongSell</p>
                        <p class="title" id="TODAY_SS"></p>
                      </div>
                    </div>
                  </nav>
                  <article class="tile is-child notification is-danger">
                    <button class="button is-warning is-large modal-button" data-target="modal-ter" aria-haspopup="true"
                      onclick="activateRcmd()">Show Me</button>
                  </article>

                </article>
              </div>

            </div>
          </div>

          <div class="tile is-vertical" id="right_side">
            <!-- 股票基本信息 -->
            <div class="tile is-parent is-10">
              <article class="tile is-child notification is-success">
                <div class="content">
                  <p class="title" id="symbol_name"></p>
                  <p class="subtitle" id="symbol_ipo"></p>
                  <img src="https://bulma.io/images/placeholders/640x480.png" id="symbol_logo" />
                  <p class="subtitle" id="symbol_country"></p>
                  <div class="content">
                    <!-- Content -->
                    <!-- 股票交易按钮 -->
                    <div class="columns">
                      <div class="column is-mobile">
                        <% if (req.session.role=='member' ) { %>
                          <button class="button is-warning is-large modal-button" data-target="modal-buy"
                            aria-haspopup="true" onclick="activateBuy()">Buy</button>
                          <button class="button is-warning is-large modal-button" data-target="modal-sell"
                            aria-haspopup="true" onclick="activateSell()">Sell</button>
                          <% } %>
                      </div>
                    </div>

                  </div>
                </div>
              </article>
            </div>
            <!-- 股票蜡烛图 -->
            <div class="tile is-parent">
              <article class="tile is-child notification is-warning">
                <p class="title">
                  Candlestick Trend
                </p>
                <div>
                  <nav class="panel">
                    <div id="main" style="width: 500px; height: 500px"></div>
                  </nav>
                </div>
              </article>
            </div>
          </div>
        </div>

        <div class="tile is-ancestor">
          <div class="tile is-vertical notification is-info" id="company_news_list">
            <p class="title" style="padding-left: 40px"><strong>Company News</strong></p>
            <div class="tile is-vertical" id="newsList">
              <!--company news-->
            </div>
          </div>
        </div>

      </div>
    </nav>

    <!-- content show the details of recommendation -->
    <div id='modal-ter' class="modal">
      <div class="modal-background"></div>
      <div class="modal-card" style="width: 900px; height: 800px">
        <header class="modal-card-head">
          <p class="modal-card-title">Recent Six Month Recommendation Index</p>
          <button class="delete" aria-label="close" onclick="deactivateRcmd();"></button>
        </header>
        <section class="modal-card-body">
          <!-- Content ... -->
          <article class="tile is-child notification">
            <p class="title" id="symbol_title_rcmd"></p>
            <div>
              <nav class="panel">
                <div id="main_rcmd" style="width: 700px; height: 600px"></div>
              </nav>
            </div>
          </article>
        </section>
        <footer class="modal-card-foot">
          <button class="button" onclick="deactivateRcmd();">Cancel</button>
        </footer>
      </div>
    </div>


    <!-- 购买页面  -->
    <div id='modal-buy' class="modal">
      <div class="modal-background"></div>
      <div class="modal-card">
        <header class="modal-card-head">
          <p class="modal-card-title">Take the Order</p>
          <button class="delete" aria-label="close" onclick="deactivateBuy();"></button>
        </header>
        <form action="/order/" method="POST" onsubmit="submitOrder(this); return false">
          <section class="modal-card-body">
            <div class="field">
              <label class="label"> Stock Symbol: </label>
              <input class="input" id="buy_name" type="text" name="symbolTitle"> </input>
            </div>
            <div class="field">
              <p class="control">
                <label class="label"> Price: </label>
                <input class="input" type="number" name="price" id="input_price" required>
              </p>
            </div>
            <div class="field">
              <p class="control">
                <label class="label"> Volume: </label>
                <input class="input" type="number" name="volume"
                  oninput="calculateTotal(this.value, document.getElementById('input_price').value);" required>
              </p>
            </div>
            <div class="field">
              <div class="control">
                Subtotal: <input class="input" type="number" name="totalCost" id="subtotal"> </input>
              </div>
            </div>
            <div class="field">
              <div class="control">
                <label class="label"> Category: </label>
                <div class="select is-multiple">
                  <select multiple size="1" name="category" required>
                    <option>buy</option>
                  </select>
                </div>
              </div>
            </div>
          </section>
          <footer class="modal-card-foot">
            <button class="button is-success" type="submit">Purchase</button>
          </footer>
        </form>
      </div>
    </div>

    <!-- 卖出页面  -->
    <div id='modal-sell' class="modal">
      <div class="modal-background"></div>
      <div class="modal-card">
        <header class="modal-card-head">
          <p class="modal-card-title">Sell the Stock</p>
          <button class="delete" aria-label="close" onclick="deactivateSell();"></button>
        </header>
        <form action="/order/" method="POST" onsubmit="submitOrder(this); return false">
          <section class="modal-card-body">
            <div class="field">
              <label class="label"> Stock Symbol: </label>
              <input class="input" id="sell_name" type="text" name="symbolTitle"> </input>
            </div>
            <div class="field">
              <p class="control">
                <label class="label"> Price: </label>
                <input class="input" type="number" name="price" id="input_price_2" required>
              </p>
            </div>
            <div class="field">
              <p class="control">
                <label class="label"> Volume: </label>
                <input class="input" type="number" name="volume"
                  oninput="calculateTotal_2(this.value, document.getElementById('input_price_2').value);" required>
              </p>
            </div>
            <div class="field">
              <div class="control">
                Subtotal: <input class="input" type="number" name="totalRevenue" id="subtotal_sell"> </input>
              </div>
            </div>
            <div class="field">
              <div class="control">
                <label class="label"> Category: </label>
                <div class="select is-multiple">
                  <select multiple size="1" name="category" required>
                    <option>sell</option>
                  </select>
                </div>
              </div>
            </div>
          </section>
          <footer class="modal-card-foot">
            <button class="button is-danger" type="submit">Sell</button>
          </footer>
        </form>
      </div>
    </div>


  </div>
</div>

<script>

  // chart code
  var ctx = document.getElementById("myChart").getContext("2d");
  var current_label = document.getElementById("price_stock_graph");
  var myChart = new Chart(ctx, {
    type: "line",
    backgroundColor: "rgb(255, 99, 132)",
    data: {
      datasets: [
        {
          type: "line",
          label: "price",
          backgroundColor: "red",
          borderColor: "red",
          data: [],
          borderWidth: 1,
        },
      ],
    },
    options: {
      responsive: true,
      scales: {
        xAxes: {
          type: "timeseries",
          display: true,
        },
        yAxes: {
          beginAtZero: false,
        },
      },
    },
  });

  //candlestick chart
  var chartDom = document.getElementById("main");
  var myChart_candlestick = echarts.init(chartDom);
  var option;
  option = {

    xAxis: {
      //time
      data: [],
    },
    yAxis: {
      scale: true,
    },
    series: [
      {
        type: "k",
        //open,close,low,high
        data: [],
      },
    ],

  };

  var chartDom_rcmd = document.getElementById("main_rcmd");
  var myChart_rcmd = echarts.init(chartDom_rcmd);
  var option_rcmd;
  //recommendation graph option
  option_rcmd = {
    legend: {},
    tooltip: {},
    dataset: {
      source: [],
    },
    xAxis: { type: "category" },
    yAxis: {},
    // Declare several bar series, each will be mapped
    // to a column of dataset.source by default.
    series: [
      { type: "bar" },
      { type: "bar" },
      { type: "bar" },
      { type: "bar" },
      { type: "bar" },
    ],
  };

  // basic information about the stock company
  var text = "<%= stockSymbol %>";

  // the title of the company
  var obj = document.getElementById("symbol_title");
  obj.innerHTML = text;
  var obj_rcmd = document.getElementById('symbol_title_rcmd');
  obj_rcmd.innerHTML = text;
  var obj_buy_name = document.getElementById('buy_name');
  obj_buy_name.value = text;
  var obj_sell_name = document.getElementById('sell_name');
  obj_sell_name.value = text;


  // stock company profile
  async function stockProfile(symbol) {

    var response = await fetch("https://finnhub.io/api/v1/stock/profile2?symbol=" + symbol + "&token=c0ro5sv48v6voi2d8ndg");

    if (response.ok) {
      let data = await response.json();

      //name
      var sym_name = data.name;
      var profile_name = document.getElementById("symbol_name");
      profile_name.innerHTML = "Stock Name:<br><strong>" + sym_name + "<strong>";
      //ipo
      var sym_ipo = data.ipo;
      var profile_ipo = document.getElementById("symbol_ipo");
      profile_ipo.innerHTML = "Stock IPO Date:<br>" + sym_ipo;
      //logo
      var sym_logo = data.logo;
      var profile_logo = document.getElementById("symbol_logo");
      profile_logo.src = sym_logo;
      //country
      var sym_country = data.country;
      var profile_country = document.getElementById("symbol_country");
      profile_country.innerHTML = "Country:<br>" + sym_country;
    } else {
      alert(response.statusText);
    }


    // console.log(data);
  }

  //candlestick data
  async function fetchCandleData(symbol) {
    // var echarts = require("echarts");

    //adding datetime data
    var today = new Date();
    var day_7 = new Array();
    for (i = 0; i < 7; i++) {
      let d = today.getTime() - i * 24 * 60 * 60 * 1000;
      let d_date = new Date(d);
      // day_7.push(d_date.toLocaleDateString());
      option.xAxis.data.push(d_date.toLocaleDateString());
    }
    // console.log(day_7);

    let f = Math.round(new Date().getTime() / 1000 - 3600 * 24 * 7);
    let t = Math.round(new Date().getTime() / 1000);

    var response = await fetch(
      "https://finnhub.io/api/v1/stock/candle?symbol=" +
      symbol +
      "&resolution=D&from=" +
      f +
      "&to=" +
      t +
      "&token=c0ro5sv48v6voi2d8ndg"
    );

    if (response.ok) {
      let data = await response.json();
      // console.log(data);

      //**********************************************************************//
      // var y_data = [];
      //// open,close,low,high
      try {
        for (i = 0; i < 7; i++) {
          let y_d = [data.o[i], data.c[i], data.l[i], data.h[i]];
          option.series[0].data.push(y_d);
        }
        // console.log(y_data);
        option && myChart_candlestick.setOption(option);
      } catch (e) {
        //console.log(e.message);
        alert("error candlestick");
      }

    } else {
      alert(response.statusText);
    }

  }

  //获取实时价格数据
  async function fetchRealTimePrice(symbol) {
    //let f = Math.round(new Date().getTime() / 1000 - 3600);
    //let t = Math.round(new Date().getTime() / 1000);

    var response = await fetch(
      "https://finnhub.io/api/v1/quote?symbol=" +
      symbol +
      "&token=c0ro5sv48v6voi2d8ndg"
    );

    if (response.ok) {
      var data_real = await response.json();
      var price_current = data_real.c;
      var last_closed = data_real.pc;
      console.log("current: "+price_current);
      console.log("last"+last_closed);

    } else {
      alert(response.statusText);
    }
  }

  setInterval(function () {
    fetchRealTimePrice("<%= stockSymbol %>");
  }, 2000);



  //recommendation data
  async function fetchRcmData(symbol) {
    const response = await fetch(
      "https://finnhub.io/api/v1/stock/recommendation?symbol=" +
      symbol +
      "&token=c0ro5sv48v6voi2d8ndg"
    );

    if (response.ok) {
      var data = await response.json();

      try {
        console.log(data);

        var rcmd_index = [
          "recommandation",
          "strongBuy",
          "buy",
          "hold",
          "sell",
          "strongSell",
        ];
        option_rcmd.dataset.source.push(rcmd_index);

        var group_data = [];
        for (let i = 0; i < 6; i++) {
          let data_i = [
            data[i].period,
            data[i].strongBuy,
            data[i].buy,
            data[i].hold,
            data[i].sell,
            data[i].strongSell,
          ];
          option_rcmd.dataset.source.push(data_i);
        }

        var today_obj1 = document.getElementById('TODAY_SB');
        var today_obj2 = document.getElementById('TODAY_B');
        var today_obj3 = document.getElementById('TODAY_H');
        var today_obj4 = document.getElementById('TODAY_SL');
        var today_obj5 = document.getElementById('TODAY_SS');
        var today_obj6 = document.getElementById('TODAY_DATE')

        today_obj1.innerHTML = data[0].strongBuy;
        today_obj2.innerHTML = data[0].buy;
        today_obj3.innerHTML = data[0].hold;
        today_obj4.innerHTML = data[0].sell;
        today_obj5.innerHTML = data[0].strongSell;
        today_obj6.innerHTML = "Date: " + data[0].period;

        // console.log(group_data);
        //console.log(option.dataset.source);
        option_rcmd && myChart_rcmd.setOption(option_rcmd);
        //   console.log(strongBuy_index);
        //   ok
        //   strongBuy_index.reverse();
        //   strongBuy_index.unshift(data[5].period);
        //   console.log(strongBuy_index);
      } catch (e) {
        alert("error rcmd");
      }


    } else {
      alert(response.statusText);
    }
  }

  //convert date into yyyy-mm-dd
  function formatDate(date) {
    var d = new Date(date),
      month = '' + (d.getMonth() + 1),
      day = '' + d.getDate(),
      year = d.getFullYear();

    if (month.length < 2)
      month = '0' + month;
    if (day.length < 2)
      day = '0' + day;

    return [year, month, day].join('-');
  }

  //convert date into yyyy-mm-dd hour:min:seconds
  function formatDate_2(date) {
    var d = new Date(date),
      month = '' + (d.getMonth() + 1),
      day = '' + d.getDate(),
      year = d.getFullYear(),
      hour = '' + d.getHours(),
      min = '' + d.getMinutes(),
      sec = '' + d.getSeconds();

    if (month.length < 2) {
      month = '0' + month;
    }
    if (day.length < 2) {
      day = '0' + day;
    }
    if (hour.length < 2)
      hour = '0' + hour;
    if (min.length < 2)
      min = '0' + min;
    if (sec.length < 2)
      sec = '0' + sec;

    var date_format = [year, month, day].join('-');
    var time_format = [hour, min, sec].join(':');
    return [date_format, time_format].join(' ');
  }

  //company news
  async function fetchCompanyNews(symbol) {

    var today = new Date();
    let d = today.getTime() - (30 * 6) * 24 * 60 * 60 * 1000;
    let f = new Date(d); //before half of year
    let t = new Date(); //today time
    var newsList_obj = document.getElementById("newsList");

    var url_link = "https://finnhub.io/api/v1/company-news?symbol=" + symbol + "&from=" + formatDate(f) +
      "&to=" + formatDate(t) + "&token=c0ro5sv48v6voi2d8ndg";

    // fetch the new from f to t
    var response = await fetch(url_link);

    if (response.ok) {
      let data = await response.json();

      console.log(data);

      var dynamicCode = "";
      data.forEach(function (news) {

        //show the specific news
        dynamicCode += '<div class="tile is-parent">' + '<article class="media is-child">' + '<figure class="media-left">' +
          '<p class="image is-64x64">' + '<img src="' + news.image + '"></p>' + '</figure>' +
          '<div class="media-content">' +
          '<div class="content">' + '<p class="title">' + '<a href="' + news.url + '">' + news.headline + '</a>' + '</p>' +
          '<p class="subtitle">' + new Date(news.datetime * 1000).toLocaleDateString() + '</p>' +
          '<p class="subtitle">Related: ' + news.related + '</p>' +
          '<p class="subtitle">' + news.summary + '</p>' +
          '<p class="subtitle">' + news.source + '</p>' +
          '</div>' +
          '</div>' +
          '</article>' +
          '</div>'
      });

      newsList_obj.innerHTML = dynamicCode;

    } else {
      alert(response.statusText);
    }

  }

  //activate window to show the details of recommendation index
  function activateRcmd() {
    document.getElementById("modal-ter").className = "modal is-active";
  }

  //cancel the window
  function deactivateRcmd() {
    document.getElementById("modal-ter").className = "modal";
  }

  //activate window of buying stock
  function activateBuy() {
    document.getElementById("modal-buy").className = "modal is-active";
  }

  //cancel the window of stock buying
  function deactivateBuy() {
    document.getElementById("modal-buy").className = "modal";
  }
  //activate window of buying stock
  function activateSell() {
    document.getElementById("modal-sell").className = "modal is-active";
  }

  //cancel the window of stock buying
  function deactivateSell() {
    document.getElementById("modal-sell").className = "modal";
  }

  //calculate the total price of buy
  function calculateTotal(v, p) {

    var obj_total = document.getElementById('subtotal');
    if (v.length > 0 && p.length > 0) {

      var sum = p * v;
      obj_total.value = sum;

    }
  }

  //calculate the total price of sell
  function calculateTotal_2(v, p) {

    var obj_total = document.getElementById('subtotal_sell');
    if (v.length > 0 && p.length > 0) {

      var sum = p * v;
      obj_total.value = sum;

    }
  }

  /*
  buy function 

  用户余额大于25000， 交易状态为1 （表示账户可进行交易）  无限次T+0交易
  用户余额小于25000， 交易状态为1 （表示账户可进行交易） 可进行4次T+0交易
  用户余额小于25000， 交易状态为0 ， 账户被冻结，无法购买股票， 只能减仓

  sell function

  持有大于卖出， 记录收入，价格，数量再持有股票记录当中
  持有 == 卖出， 计入收入，价格，数量并将其valid变量设为1表示该持有股票订单作废。

  */
  async function submitOrder(formElem) {

    //datetime
    var today = formatDate_2(new Date());
    var data_form = new FormData(formElem);
    data_form.append("datetime", today);

    //create the stock order
    var response = await fetch(formElem.action, {
      method: formElem.method,
      body: data_form,
    });

    if (response.ok) {

      var user = await response.json();

      alert(user);
      location.assign('/user/clients');

    } else if (response.status == 404) {

      alert(response.json());

    } else {

      alert(response.statusText);

    }
  };

  stockProfile("<%= stockSymbol %>");
  fetchCandleData("<%= stockSymbol %>");
  fetchRcmData("<%= stockSymbol %>");
  fetchCompanyNews("<%= stockSymbol %>");

  //
  // websocket code
  //
  let wSocket;

  if (wSocket) {
    wSocket.close();
  }
  wSocket = new WebSocket("wss://ws.finnhub.io?token=c0ro5sv48v6voi2d8ndg");

  wSocket.onopen = function () {
    wSocket.send(`{"type":"subscribe","symbol":"${text}"}`);
  };

  wSocket.onmessage = function (event) {
    console.log(event);
    if (event.type == "message" && JSON.parse(event.data).data) {
      let d = JSON.parse(event.data).data[0];
      if (d) {
        // console.log(d);
        let volumeData = myChart.data.datasets[0].data;
        volumeData.push({ x: d.t, y: d.p });
        current_label.innerHTML = d.p;
        myChart.update();
      }
    }
  };



  //setInterval(() => {
  //  sendMessage();
  //}, 2000);

  /*
  s Symbol.
  p Last price.
  t UNIX milliseconds timestamp.
  v Volume.
  c List of trade conditions.
  */

  //
  // candlestick chart
  //
</script>