{% extends "layout.html" %}
{% block main %}
<script type="text/javascript" src="{{url_for('static', filename='config.js')}}"></script>
<script type="text/javascript" src="/static/js/yo.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<script type="text/javascript" src="/static/js/jquery.richtext.min.js"></script>
<link rel="stylesheet" href="/static/styles/richtext.min.css">
<script src="https://code.jquery.com/ui/1.13.0/jquery-ui.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.13.0/themes/base/jquery-ui.css">

<div class="faq-content">
  <div class="row px-0 mx-0">
    <div class="col-lg-6">
      <h1 class="h3"><i class="fas fa-pen mr-3 mb-3"></i>{{ title }}</h1>

      <input id="curl" type="text" style="display: none;" />
      <div>
        <div>
          <ul id='qaData1'></ul>
        </div>
        <div class="text-center">

          <button style="border: none; background: none; outline: none;" onclick="addQa();"><i
              class="addfaq fas fa-plus-circle"></i></button>
        </div>
      </div>
    </div>
    <div class="col-lg-6">
      <div class="card faq-editor p-3">
        <div class="text-right mb-3">
          <i class="close_edit_faq fas fa-times"></i>
        </div>
        <input type="text" class="form-control mb-3 w-100" id="input_q" placeholder="EX:小寶優居的規劃師服務和一般的室內設計有什麼不同嗎？" />
        <div><textarea id='input_a'></textarea></div>
        <div class="mt-4 d-flex justify-content-end">
          <div>
            <!-- <button class="btn faq-btn" onclick="addQa();">新增</button> -->
            <!-- <button class="btn faq-btn" onclick="saveQa();">修改項目</button> -->
            <button class="btn faq-btn" onclick="removeQa();">移除項目</button>
            <button class="btn faq-btn" onclick="writeAllQa();">完成儲存</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>


<style>
  .addfaq {
    color: #ADB5BD;
    font-size: 32px;
    cursor: pointer;
    transition: all 0.3s;

  }

  .addfaq:hover {
    color: grey;

  }

  .close_edit_faq {
    font-size: 24px;
    cursor: pointer;
  }

  .faq-editor {
    position: sticky !important;
    top: 21px;
  }

  #qaData1 li {
    vertical-align: center;
    list-style-type: none;
  }

  ul {
    padding-inline-start: 0px !important;
  }

  #qaData1 tr {
    border: inset 2px
  }

  #qaData1 td {
    vertical-align: top;
    padding: 0.475rem 0.475rem;
    border: 1px solid #ced4da;
    border-radius: 0.25rem;
    font-size: 1rem;
    /* border-collapse: unset; */
    cursor: pointer;
  }

  table {
    border-collapse: unset;
    width: 100%;
  }

  .faq-btn {
    background-color: rgb(179, 179, 179);
    color: white;
    transition: all 0.3s;
    margin-right: 5px;
  }

  .faq-btn:hover {
    background-color: grey;
  }
</style>
<script>

  var editor, targetItem, faqContent;
  qa = [];
  $(function () {
    editor = $("#input_a").richText();
    axios.get(contentApiUrl + '/frequently_asked_questions').then(({ data }) => {
      parseMd(data[0]['content']);
      faqContent = $.parseHTML(contentMatters.join(''));
      //處理圖片
      if ($("[id='myAccordion']", faqContent).length > 0) {
        fnodes = $("[id='myAccordion']", faqContent)[0].childNodes;
        for (i = 0; i < fnodes.length; i++) {
          if (fnodes[i].nodeName == "SECTION") {
            //qa.push({ q: fnodes[i].childNodes[1].innerText.trim(), a: fnodes[i].childNodes[3].innerHTML.trim() });
            k = 0;
            for (j = 0; j < fnodes[i].childNodes.length; j++) {
              if (fnodes[i].childNodes[j].nodeName == "DIV") {
                if (k == 0) {
                  if (fnodes[i].childNodes[j].childNodes[j].childNodes[j].childNodes[j].nodeName == "SPAN") {
                    qa.push({ q: fnodes[i].childNodes[j].childNodes[j].childNodes[j].childNodes[j].innerText.trim() });
                    k++;
                  }
                  // qa.push({ q: fnodes[i].childNodes[j].innerText.trim() });
                  // k++;
                }
                else {
                  qa[qa.length - 1].a = fnodes[i].childNodes[j].childNodes[1].innerHTML.trim();
                }
                /* if (fnodes[i].childNodes[j].className == "question") {
                    //alert(fnodes[i].childNodes[j].childNodes[1].nodeValue.trim());
                    qa.push({ q: fnodes[i].childNodes[j].childNodes[1].nodeValue.trim() });
                } */
              }
            }
          }
        }
        //alert(qa.length);
        for (i = 0; i < qa.length; i++) {
          //$('#qaData').append("<tr><td>" + qa[i].q + "</td><td>" + qa[i].a + "</td></tr>");
          $('#qaData1').append("<li class='mb-1' data-si='" + i + "''><table><tr class='qa_q'><td>" + qa[i].q + "</td></tr><tr class='qa_a'><td>" + qa[i].a + "</td></tr></table></li>");

        }
        $('.qa_a').hide();
        $('.qa_q').click(setTarget);
        /* $('.qa_q').dblclick(function () {
            //alert($(this).next()[0].childNodes[0].innerHTML);
            //$('#editorjs')[0].innerHTML = "";
            //$('.qa_a').hide();
            //$(this).next().toggle();
            $('.qa_q').css("background-color", "white");
            $(this).css("background-color", "lightpink");
            targetItem = $(this);
            $("#input_q").val($(this).children().html());
            $("#input_a").val($(this).next().children().html()).trigger('change');
            $('html, body').animate({ scrollTop: '0px' }, 300);
            //$("#editor")[0].outerHTML = "<textarea id='editor'></textarea>";
            //$("#editor").val($(this).next()[0].childNodes[0].innerHTML);
            //editor = $("#editor").richText();
            //$(this).next().append("<div id='editorjs'></div>");
        }); */

        //editor = $("textarea").richText();
        fromIdx = 0;
        $('#qaData1').sortable(/* {
          start: function (event, ui) {
              fromIdx = ui.item.index();
          },
          stop: function (event, ui) {
              //toIndex = ui.item.attr("data-si");
              var element = qa[fromIdx];
              qa.splice(fromIdx, 1);
              qa.splice(ui.item.index(), 0, element);
              //alert(fromIdx + ',' + ui.item.index());
          },
          } */
        );
      }
    });

  });
  $(".faq-editor").hide();

  function setTarget() {
    $(".faq-editor").fadeIn();
    $('.qa_q').css("background-color", "white");
    $(this).css("background-color", "lightpink");
    targetItem = $(this);
    $("#input_q").val($(this).children().html());
    $("#input_a").val($(this).next().children().html()).trigger('change');
    // $('html, body').animate({ scrollTop: '0px' }, 300);
  }

  $(".close_edit_faq").click(function () {
    $(".faq-editor").fadeOut();
  });

  function addQa() {
    var a = $("ul li:last-child").find('td').text();

    if (a == "") {
      // alert('1');
      alert("請輸入問題");
      $("#input_q").focus();

      return
    }

    $('#qaData1').append("<li data-si='" + i + "''><table><tr class='qa_q'><td></td></tr><tr class='qa_a'><td></td></tr></table></li>");
    $('.qa_a').hide();
    $('.qa_q').click(setTarget);
    $(".qa_q").trigger("click");
    $("#input_q").focus();

    // QaItem.lastChild.innerHTML.triggerHandler('click');

  };

  function saveQa() {
    targetItem.children().html($("#input_q").val());
    targetItem.next().children().html($("#input_a").val());
  };

  function removeQa() {
    // targetItem.parent().parent().parent().remove()
    var r = confirm("確定要刪除此作品?");
    if (r == true) {
      targetItem.parent().parent().parent().remove();
      writeAllQa();
      $(".faq-editor").fadeOut();
    }
  };


  function writeAllQa() {

    targetItem.children().html($("#input_q").val());
    targetItem.next().children().html($("#input_a").val());

    if ($('#input_q').val() == "") {
      alert("請輸入問題");
      $("#input_q").focus();

      return
    }

    qa = [];
    for (i = 0; i < $('#qaData1 .qa_q').length; i++) {
      qa.push({ q: $('#qaData1 .qa_q')[i].childNodes[0].innerHTML, a: $('#qaData1 .qa_a')[i].childNodes[0].innerHTML });
      let test = document.querySelectorAll('#qaData1 .qa_a');
    }
    newFaqItemContent = "";
    for (i = 0; i < qa.length; i++) {
      newFaqItemContent += `
      <section class="accordion-item">
        <div class="accordion-header" id="panelsStayOpen-${i}">
          <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse"
            data-bs-target="#question-${i}" aria-expanded="false" aria-controls="question-${i}">
            <p class="pe-2 title m-0">Q${i + 1}
              <span>${qa[i].q}</span>  
            </p>
          </button>
        </div>
        <div id="question-${i}" class="accordion-collapse collapse" aria-labelledby="panelsStayOpen-${i}">
          <div class="accordion-body">
            ${qa[i].a}
          </div>
        </div>
      </section>`;
    }
    $("[id='myAccordion']", faqContent).html(newFaqItemContent);
    mdContent = frontMatters.join('\n') + '\n' + faqContent[0].outerHTML;
    postData = {
      content: mdContent,
      url: $('#curl').val()
    };
    axios.post(contentApiUrl + $('#curl').val(), json = postData).then(({ data }) => {
      alert('作品資料已儲存');
    });
    //alert(faqContent.outerHTML);
  }

</script>
{% endblock main %}