contentApiUrl = `${PORTAL_SERVER}contents?url=`;
frontMatters = [];
contentMatters = [];
tagOptionIds = ["chousetype", "csize", "cbudgetr", "cbednum"];
testImg = [];

var SwfType = {};
if (location.pathname.indexOf("system_furniture") >= 0) {
  SwfType = {
    custom_made_system_cabinet: "客製模組系統櫃",
    system_cabinet: "模組系統櫃單品",
  };
} else {
  SwfType = {
    sofa: "沙發",
    cabinet: "電視櫃",
    desk: "書桌/工作桌",
    dining_chair: "餐椅/中島椅",
    dining_table: "餐桌",
    mattress: "床組",
    other_furniture: "其他單品設計",
    side_cabinet: "邊櫃/邊几",
    side_table: "茶几",
    wardrobe: "衣櫃/收納櫃/中島",
  };
}

// document.ready
$(function () {
  $("#dialog-form").hide();
  if ($("#editorjs").length > 0)
    editor = new EditorJS({
      readOnly: false,
      holder: "editorjs",
    });
  /* if ($('#editorjs1').length > 0)
        editor1 = new EditorJS({
            readOnly: false,
            holder: 'editorjs1',
        }); */
});

let ownerimgShow = true;

$(document).ready(function () {
  $("#removeOwnerImg").click(function () {
    ownerimgShow = false;
    document.getElementById("cnewownerimg").value = "";
  });
});

var editorslider;
function getHeader(url) {
  axios.get(contentApiUrl + url).then(({ data }) => {
    frontMatters = [];
    contentMatters = [];
    editTarget = url;
    mdType = url.split("/")[1];
    aa = data[0]["content"];
    for (var toi of tagOptionIds) {
      $("#" + toi).val("");
    }
    //const content = _.get(data, '0.content', '');
    blocks = parseMd(aa);
    oTitle = $("#ctitle").val();
    // $("#dialog-form").dialog();
    if ($("#ctype").val() == "collection") {
      $("#scat").hide();
    } else if ($("#ctype").val() == "blog" || $("#ctype").val() == "blog") {
      $("#sdesc").hide();
    } else if ($("#ctype").val() == "news") {
      $("#sdesc").hide();
      $("#scat").hide();
      $("#simg").hide();
    } else {
      ParseProductSection(contentMatters.join(""));
    }
    $("#myModal").modal();
  });
}

function toggleDraft(obj, url) {
  axios.get(contentApiUrl + url).then(({ data }) => {
    frontMatters = [];
    contentMatters = [];
    aa = data[0]["content"];
    const content = _.get(data, "0.content", "");
    blocks = parseMd(aa);
    editTarget = url;
    $("#cdraft").removeAttr("checked");
    $("#cdraft").prop("checked", obj.checked);
    updateHeader();
    oTitle = "";
  });
}

function toggleDisplay(obj, url) {
  let checkedList = document.querySelectorAll('.display_state:checked');
  for (let i = 0; i < checkedList.length; i++) {
    if (checkedList.length == 2) {
      alert('首頁顯示僅能選擇一筆');
      obj.checked = false;
      return;
    }
  }

  axios.get(contentApiUrl + url).then(({ data }) => {
    frontMatters = [];
    contentMatters = [];
    aa = data[0]["content"];
    const content = _.get(data, "0.content", "");
    blocks = parseMd(aa);
    editTarget = url;
    
    $("#cdisplay").removeAttr("checked");
    $("#cdisplay").prop("checked", obj.checked);
    updateHeader();
    oTitle = "";
  });
}

function updateHeader() {
  /* if (oTitle != $('#ctitle').val() && $('#ctitle').val() != "" && oTitle != "") {
      axios.get('/backstage/modTitle/' + oTitle + '/' + $('#ctitle').val()).then(({ data }) => {
        if (data.success == "0") {
          alert('已有重複的標題，請重新設定');
          return;
        }
        else {
          writeMd();
        }
      });
    }
    else {
      writeMd();
    } */
  $("#uptbtn").attr("disabled", true);
  writeMd();
  // location.reload();
}

// 新增都是create的Py
// 修改都是writeMd

// mdContent = GetMdHeader(frontMatters);
// writeMd 修改
function writeMd() {
  axios
    .get("/backstage/utils?trantext=" + $("#ccategories").val())
    .then(({ data }) => {
      $("#ccol1").val(data);
    })
    .finally(() => {
      mdContent = GetMdHeader(frontMatters);
      mdContent += contentMatters.join("\n");
      var formData = new FormData();

      var imagefile = document.querySelector("#cfile");

      if ($("#ctype").val() == "collection") {
        var offset1 = 0; //in case we dont have complete images, we have to offset
        var offset2 = 0;
        var offset3 = 0;
        var imagefil2 = document.querySelector("#cnewcoverimg");
        var imagefil3 = document.querySelector("#cnewcomment");
        var imagefil4 = document.querySelector("#cnewownerimg");
        var imgcount = 1;

        if ($("#cfile").val() == "" || $("#cfile").val() == undefined) {
          offset1 = 1;
        } else {
          formData.append("image" + imgcount.toString(), imagefile.files[0]);
          imgcount++;
        }

        if (
          $("#cnewcoverimg").val() == "" ||
          $("#cnewcoverimg").val() == undefined
        ) {
          offset2 = 1;
        } else {
          formData.append("image" + imgcount.toString(), imagefil2.files[0]);
          imgcount++;
        }

        if (
          $("#cnewcomment").val() == "" ||
          $("#cnewcomment").val() == undefined
        ) {
          offset3 = 1;
        } else {
          formData.append("image" + imgcount.toString(), imagefil3.files[0]);
          imgcount++;
        }

        formData.append("image" + imgcount.toString(), imagefil4.files[0]);

        axios
          .post("/backstage/multiupload/title", formData, {
            headers: {
              "Content-Type": "multipart/form-data",
            },
          })
          .then(({ data }) => {
            if (data.success == "1") {
              var imglinks = data.fileurl.split(";;;");
              if ($("#cfile").val() == "" || $("#cfile").val() == undefined) {
                //do nothing
              } else {
                alert("Replacing header image");
                mdContent = mdContent.replace(
                  $("#cfile").val(),
                  "/img/title/" + imglinks[0]
                );
              }
              if (
                $("#cnewcoverimg").val() == "" ||
                $("#cnewcoverimg").val() == undefined
              ) {
                //do nothing
              } else {
                alert("Replacing cover image");
                mdContent = mdContent.replace(
                  $("#cnewcoverimg").val(),
                  "/img/title/" + imglinks[1 - offset1]
                );
              }
              if (
                $("#cnewcomment").val() == "" ||
                $("#cnewcomment").val() == undefined
              ) {
                //do nothing
              } else {
                alert("Replacing comment image");
                mdContent = mdContent.replace(
                  $("#cnewcomment").val(),
                  "/img/title/" + imglinks[2 - offset1 - offset2]
                );
              }
              if (
                $("#cnewownerimg").val() == "" ||
                $("#cnewownerimg").val() == undefined
              ) {
                //do nothing
              } else {
                alert("Replacing owner image");
                mdContent = mdContent.replace(
                  $("#cnewownerimg").val(),
                  "/img/title/" + imglinks[3 - offset1 - offset2 - offset3]
                );
              }
            } else {
              console.log("skipped");
            }

            postData = {
              content: mdContent,
              url: editTarget,
            };

            axios
              .post(contentApiUrl + editTarget, (json = postData))
              .then(({ data }) => {});
          })
          .finally(() => {
            alert("資料已更新"); // test
            location.reload();
          });
      } else {
        formData.append("image", imagefile.files[0]);
        axios
          .post("/backstage/upload/title", formData, {
            headers: {
              "Content-Type": "multipart/form-data",
            },
          })
          .then(({ data }) => {
            if (data.success == "1") {
              mdContent = mdContent.replace(
                $("#cfile").val(),
                "/img/title/" +
                  data.file.url.substring(data.file.url.lastIndexOf("/") + 1)
              );
            }

            postData = {
              content: mdContent,
              url: editTarget,
            };

            axios
              .post(contentApiUrl + editTarget, (json = postData))
              .then(({ data }) => {});
          })
          .finally(() => {
            alert("資料已更新"); // test
            location.reload();
          });
      }
    });
}
// md 的內容解出來
function parseMd(content) {
  //var frontMatters = [];
  var blockCount;
  var preDataIndex;
  var parseBlockDiv;
  var preImgObject = { image: {} };
  var isNotFrontMatterCount = 0;
  var isAmpImgRange = false;
  var result = [];

  var rblocks = new Array();
  lineIdx = 1;
  foundImg = false;
  foundYT = false;
  foundTBL = false;
  crossLine = "";

  for (var line of content.split("\n")) {
    lineIdx++;
    if (isNotFrontMatterCount < 2) {
      frontMatters.push(line);

      if (line.includes("meta_title: ")) {
        $("#cmetattl").val(
          line.replace("meta_title: ", "").replaceAll('"', "")
        );
      } else if (line.includes("title: ")) {
        $("#ctitle").val(line.replace("title: ", "").replaceAll('"', ""));
      }
      if (line.includes("date: ")) {
        $("#cdate").val(line.replace("date: ", "").replaceAll('"', ""));
      }
      if (line.includes("draft: ")) {
        $("#cdraft").val(line.replace("draft: ", "").replaceAll('"', ""));
        $("#cdraft").removeAttr("checked");
        if ($("#cdraft").val() == "false") $("#cdraft").prop("checked", true);
      }
      if (line.includes("display: ")) {
        $("#cdisplay").val(line.replace("display: ", "").replaceAll('"', ""));
        $("#cdisplay").removeAttr("checked");
        if ($("#cdisplay").val() == "true") $("#cdisplay").prop("checked", true);
      }
      if (line.includes("type: ")) {
        $("#ctype").val(line.replace("type: ", "").replaceAll('"', ""));
      }
      if (line.includes("url: ")) {
        $("#curl").val(line.replace("url: ", "").replaceAll('"', ""));
      }
      if (line.includes("image: ")) {
        $("#cimage").val(line.replace("image: ", "").replaceAll('"', ""));
      }
      if (line.includes("cover_img: ")) {
        $("#ccoverimg").val(
          line.replace("cover_img: ", "").replaceAll('"', "")
        );
      }
      if (line.includes("meta_description: ")) {
        $("#cmetadsc").val(
          line.replace("meta_description: ", "").replaceAll('"', "")
        );
      } else if (line.includes("collection_description: ")) {
        $("#ccolldesc").val(
          line
            .replace("collection_description: ", "")
            .replaceAll('"', "")
            .replaceAll("<br>", "\r\n")
        );
      } else if (line.includes("description: ")) {
        $("#cdescription").val(
          line
            .replace("description: ", "")
            .replaceAll('"', "")
            .replaceAll("<br>", "\r\n")
        );
      }
      if (line.includes("weight: ")) {
        $("#cweight").val(line.replace("weight: ", "").replaceAll('"', ""));
      }
      if (line.includes("tag: ")) {
        $("#ctag").val(line.replace("tag: ", "").replaceAll('"', ""));
      }
      if (line.includes("tags: ")) {
        if ($("#ctags").length > 0) {
          $("#ctags").val(line.replace("tags: ", "").replaceAll('"', ""));
          tags = $("#ctags").val().split(",");
          for (var tag of tags) {
            for (var toi of tagOptionIds) {
              $("#" + toi + " option").each(function () {
                if (this.value == tag) this.selected = true;
              });
            }
          }
        }
      }
      if (line.includes("categories: ")) {
        $("#ccategories").val(
          line
            .replace("categories: ", "")
            .replace("categories: ", "")
            .replace(/\[|]/g, "")
            .replace(/\"/g, "")
        );
      }
      if (line.includes("col1: ")) {
        $("#ccol1").val(line.replace("col1: ", "").replaceAll('"', ""));
      }
      if (line.includes("col2: ")) {
        $("#ccol2").val(line.replace("col2: ", "").replaceAll('"', ""));
      }

      //for blogs
      if (line.includes("introduction: ")) {
        $("#cintroduction").val(
          line
            .replace("introduction: ", "")
            .replaceAll('"', "")
            .replaceAll("<br>", "\r\n")
        );
      }

      if (line.includes("question_box_intro: ")) {
        $("#cquestionboxintro").val(
          line.replace("question_box_intro: ", "").replaceAll('"', "")
        );
      }

      if (line.includes("blog_tag: ")) {
        $("#cblogtags").val(
          line.replace("blog_tag: ", "").replaceAll('[', "").replaceAll(']', "")
        );
      }

      if (line.includes("readmore_ttl: ")) {
        var titles = line.replace("readmore_ttl: ", "").replaceAll('[', "").replaceAll(']', "").replaceAll('"', "").split(",");

        try
        {
          var inserted = 0;
          $("#data00").val(titles[0]); inserted = 1; 
          $("#data10").val(titles[1]); inserted = 2;
          $("#data20").val(titles[2]); inserted = 3;
          $("#data30").val(titles[3]); inserted = 4;
          $("#data40").val(titles[4]); inserted = 5;
        }
        catch(err)
        {
          console.log("Less than 5 articles");
        }
        console.log("Total articles inserted: " + inserted);
      }

      if (line.includes("readmore_lnk: ")) {
        var links = line.replace("readmore_lnk: ", "").replaceAll('[', "").replaceAll(']', "").replaceAll('"', "").split(",");

        try
        {
          var inserted = 0;
          $("#data01").val(links[0]); inserted = 1; 
          $("#data11").val(links[1]); inserted = 2;
          $("#data21").val(links[2]); inserted = 3;
          $("#data31").val(links[3]); inserted = 4;
          $("#data41").val(links[4]); inserted = 5;
        }
        catch(err)
        {
          console.log("Less than 5 links");
        }
        console.log("Total links inserted: " + inserted);
      }

      // for collections
      if (line.includes("banner_img_text: ")) {
        $("#ccoverimgtxt").val(
          line.replace("banner_img_text: ", "").replaceAll('"', "")
        );
      }

      if (line.includes("homeowner: ")) {
        $("#chomeowner").val(
          line.replace("homeowner: ", "").replaceAll('"', "")
        );
      }

      if (line.includes("owner_img: ")) {
        $("#cownerimg").val(
          line.replace("owner_img: ", "").replaceAll('"', "")
        );
      }

      if (line.includes("house_size: ")) {
        $("#chousesize").val(
          line.replace("house_size: ", "").replaceAll('"', "")
        );
      } else if (line.includes("size: ")) {
        $("#csize").val(line.replace("size: ", "").replaceAll('"', ""));
      }

      if (line.includes("bed_num: ")) {
        $("#cbednum").val(line.replace("bed_num: ", "").replaceAll('"', ""));
      }

      if (line.includes("room_count: ")) {
        $("#croomcount").val(
          line.replace("room_count: ", "").replaceAll('"', "")
        );
      }

      if (line.includes("house_cat: ")) {
        $("#chousetype").val(
          line.replace("house_cat: ", "").replaceAll('"', "")
        );
      }

      if (line.includes("designer: ")) {
        $("#cdesigner").val(line.replace("designer: ", "").replaceAll('"', ""));
      }

      if (line.includes("space: ")) {
        $("#cspace").val(line.replace("space: ", "").replaceAll('"', ""));
      }

      if (line.includes("loc: ")) {
        $("#cloc").val(line.replace("loc: ", "").replaceAll('"', ""));
      }

      if (line.includes("budget_range: ")) {
        $("#cbudgetr").val(
          line.replace("budget_range: ", "").replaceAll('"', "")
        );
      }

      if (line.includes("budget: ")) {
        $("#cbudget").val(line.replace("budget: ", "").replaceAll('"', ""));
      }

      if (line.includes("construction: ")) {
        $("#cconstruction").val(
          line.replace("construction: ", "").replaceAll('"', "")
        );
      }

      if (line.includes("collection_name: ")) {
        $("#ccollname").val(
          line.replace("collection_name: ", "").replaceAll('"', "")
        );
      }

      if (line.includes("collection_slider: ")) {
        let slider = $("#ccollslider").val(
          line.replace("collection_slider: ", "").replaceAll('"', "")
        );

        // 將字串內的陣列括號移除
        let left = slider[0].value.lastIndexOf("[");
        let right = slider[0].value.lastIndexOf("]");
        let stringList = slider[0].value.substr(left + 1, right - 1);
        let stringArr = stringList.split(",");
        let imgArr = [];
        let textArr = [];

        // 擷取字串後存入陣列
        stringArr.map((e) => {
          if (e.includes("slide_img")) {
            e = e.substr(11);
            imgArr.push(e);
          } else {
            e = e.substr(11);
            e = e.substring(0, e.length - 1);
            textArr.push(e);
          }
        });

        if (document.getElementById("url")) {
          // 點擊編輯時將 Image 及 Caption 存進 editorslider
          for (let index = 0; index < imgArr.length; index++) {
            const element = imgArr[index];
            captionValue = textArr[index];

            tmpsrcImg =
              BHOUSE_SERVER +
              JSON.parse(document.getElementById("url").textContent).url +
              "/" +
              element;

            editorBlocks1.push({
              type: "image",
              data: {
                file: {
                  url: tmpsrcImg,
                },
                caption: captionValue,
              },
            });
          }
        }
        //$('#ccollslider').val(line.replace('collection_slider: ', '').replaceAll('\"', ''));
      }

      if (line.includes("comment: ")) {
        $("#ccomment").val(line.replace("comment: ", "").replaceAll('"', ""));
      }

      // back to normal
      if (line.includes("---")) {
        isNotFrontMatterCount += 1;
      }
      continue;
    }
    contentMatters.push(line);

    if (line.includes("---")) {
      rblocks.push({ type: "mt5", text: line });
      continue;
    }

    /* header start */
    if ((line.match(/#/g) || []).length === 1) {
      line = line.replaceAll("#", "");
      rblocks.push({ type: "header1", text: line });
      continue;
    } 

    if ((line.match(/#/g) || []).length === 2) {
      line = line.replaceAll("##", "");
      rblocks.push({ type: "title", text: line });
      continue;
    } 
    
    if ((line.match(/#/g) || []).length === 3) {
      line = line.replaceAll("###", "");
      rblocks.push({ type: "header3", text: line });
      continue;
    }

    if ((line.match(/#/g) || []).length === 4) {
      line = line.replaceAll("####", "");
      rblocks.push({ type: "header4", text: line });
      continue;
    }

    if ((line.match(/#/g) || []).length === 5) {
      line = line.replaceAll("#####", "");
      rblocks.push({ type: "header5", text: line });
      continue;
    }

    if ((line.match(/#/g) || []).length === 6) {
      line = line.replaceAll("######", "");
      rblocks.push({ type: "header6", text: line });
      continue;
    }
    /* header end */

    if (line.includes('{{% chuz-div class="mt-5" %}}')) {
      rblocks.push({ type: "mt5", text: line });
      continue;
    }

    if (line.includes("<img") || foundImg) {
      crossLine += line;
      foundImg = true;
      if (line.includes("</img>")) {
        rblocks.push({ type: "img", text: crossLine });
        foundImg = false;
        crossLine = "";
      }
      continue;
    }

    if (line.includes("<iframe") || foundYT) {
      crossLine += line;
      foundYT = true;
      if (line.includes("</iframe>")) {
        rblocks.push({ type: "youtube", text: crossLine });
        foundYT = false;
        crossLine = "";
      }
      continue;
    }

    if (line.includes("<table") || foundTBL) {
      crossLine += line;
      foundTBL = true;
      if (line.includes("</table>")) {
        rblocks.push({ type: "table", text: crossLine });
        foundTBL = false;
        crossLine = "";
      }
      continue;
    }

    if (line != "<p></p>" && line != "") {
      rblocks.push({ type: "para", text: line });
    } else {
      console.log("Empty paragraph -- skipped.");
    }
  }
  console.log("frontMatters", frontMatters);
  return rblocks;
}

function GetMdHeader(result = []) {
  rContent = "";
  rContent += "---\n";
  rContent += 'meta_title: "' + $("#cmetattl").val() + '"\n';
  rContent += 'meta_description: "' + $("#cmetadsc").val() + '"\n';
  rContent += 'title: "' + $("#ctitle").val() + '"\n';
  rContent += "date: " + $("#cdate").val() + "\n";
  // rContent += "draft: " + !$("#cdraft").is(":checked") + "\n";

  // 點擊編輯完成後勾選顯示
  if (result === "editorSave" || result !== []) {
    rContent += "draft: " + false + "\n";
  } else {
    rContent += "draft: " + !$("#cdraft").is(":checked") + "\n";
  }

  if ($("#ctype").val() == "news") {
    rContent += 'display: ' + $("#cdisplay").is(":checked") + '\n';
  }

  rContent += 'type: "' + $("#ctype").val() + '"\n';
  rContent += 'url: "' + $("#curl").val() + '"\n';
  //mdContent += 'url: "' + $('#curl').val() + '"\n';

  if ($("#cfile").val() != "" && $("#cfile").val() != undefined) {
    rContent += 'image: "' + $("#cfile").val() + '"\n';
  } else {
    rContent += 'image: "' + $("#cimage").val() + '"\n';
  }

  if ($("#ctype").val() == "collection") {
    if (
      $("#cnewcoverimg").val() != "" &&
      $("#cnewcoverimg").val() != undefined
    ) {
      rContent += 'cover_img: "' + $("#cnewcoverimg").val() + '"\n';
    } else {
      rContent += 'cover_img: "' + $("#ccoverimg").val() + '"\n';
    }

    rContent += 'collection_name: "' + $("#ccollname").val() + '"\n';
    rContent +=
      'description: "' +
      $("#cdescription").val().replace(/\r?\n/g, "<br>") +
      '"\n';
    //rContent += 'weight: ' + ($('#cweight').val() == 'undefined' ? "" : $('#cweight').val()) + '\n';
    tags = [];
    for (var toi of tagOptionIds) {
      if ($("#" + toi).val() != "") tags.push($("#" + toi).val());
    }
    rContent += "tags: [" + tags.join(",") + "]\n";
    //rContent += 'tags: "' + ($('#ctags').val() == 'undefined' ? "" : $('#ctags').val()) + '"\n';
    // rContent += 'collection_slider: ['+collection_slider_img+']\n';
    rContent += 'banner_img_text: "' + $("#ccoverimgtxt").val() + '"\n';
    rContent += 'homeowner: "' + $("#chomeowner").val() + '"\n';

    if (!ownerimgShow) {
      rContent += 'owner_img: ""\n';
    } else {
      if (
        $("#cnewownerimg").val() != "" &&
        $("#cnewownerimg").val() != undefined
      ) {
        rContent += 'owner_img: "' + $("#cnewownerimg").val() + '"\n';
      } else {
        rContent += 'owner_img: "' + $("#cownerimg").val() + '"\n';
      }
    }

    // if (
    //   $("#cnewownerimg").val() != "" &&
    //   $("#cnewownerimg").val() != undefined
    // ) {
    //   rContent += 'owner_img: "' + $("#cnewownerimg").val() + '"\n';
    // } else {
    //   rContent += 'owner_img: "' + $("#cownerimg").val() + '"\n';
    // }
    rContent += 'size: "' + $("#csize").val() + '"\n';
    rContent += 'house_size: "' + $("#chousesize").val() + '"\n';
    rContent += 'bed_num: "' + $("#cbednum").val() + '"\n';
    rContent += 'room_count: "' + $("#croomcount").val() + '"\n';
    rContent += 'house_cat: "' + $("#chousetype").val() + '"\n';
    rContent += 'designer: "' + $("#cdesigner").val() + '"\n';
    rContent += 'space: "' + $("#cspace").val() + '"\n';
    rContent += 'loc: "' + $("#cloc").val() + '"\n';
    rContent += 'budget_range: "' + $("#cbudgetr").val() + '"\n';
    rContent += 'budget: "' + $("#cbudget").val() + '"\n';
    rContent += 'construction: "' + $("#cconstruction").val() + '"\n';
    rContent +=
      'collection_description: "' +
      $("#ccolldesc").val().replace(/\r?\n/g, "<br>") +
      '"\n';
    // rContent += 'collection_description: "' + $("#ccolldesc").val() + '"\n';
    // rContent += 'collection_slider: "' + $('#ccollslider').val() + '"\n';
    // rContent += 'collection_slider: []\n';
    if ($("#cnewcomment").val() != "" && $("#cnewcomment").val() != undefined) {
      rContent += 'comment: "' + $("#cnewcomment").val() + '"\n';
    } else {
      rContent += 'comment: "' + $("#ccomment").val() + '"\n';
    }

    if (result.length !== 0 && result.blocks) {
      let collection_slider_img = [];
      let sliderList = [];
      for (i = 0; i < result.blocks.length; i++) {
        block = result.blocks[i];
        if (block.type == "image") {
          iurl = block.data.file.url.split("/");
          collection_slider_img.push(`img/${iurl[iurl.length - 1]}`);

          let sliderItem = {};
          sliderItem.slide_img = `img/${iurl[iurl.length - 1]}`;
          sliderItem.slide_text = block.data.caption;
          sliderList.push(sliderItem);
        }
      }
      if (sliderList.length === result.blocks.length) {
        rContent += "collection_slider: " + JSON.stringify(sliderList) + "\n";
      }
    } else {
      // 主資訊編輯時使用 frontMatters 作為參數 (result)
      let collection_slider_value = result.filter((e) =>
        e.match("collection_slider")
      );
      rContent += `${collection_slider_value[0]}\n`;
    }

  } else if (
    $("#ctype").val() == "blog" ||
    $("#ctype").val() == "maincategories"
  ) {
    rContent += 'categories: "' + $("#ccategories").val() + '"\n';
    //rContent += 'caturl: "' + $('#ccaturl').val() + '"\n';
    //rContent += 'description: "' + $('#cdescription').val().replace(/\r?\n/g, '<br>') + '"\n';
    rContent +=
      'description: "' +
      $("#cdescription").val().replace(/\r?\n/g, "<br>") +
      '"\n';
    rContent +=
      'col1: "' +
      ($("#ccol1").val() == "undefined" ? "" : $("#ccol1").val()) +
      '"\n';
    rContent +=
      'col2: "' +
      ($("#ccol2").val() == "undefined" ? "" : $("#ccol2").val()) +
      '"\n';
    rContent +=
      'introduction: "' +
      $("#cintroduction").val().replace(/\r?\n/g, "<br>") +
      '"\n';
      rContent += 'question_box_intro: "' + $("#cquestionboxintro").val() + '"\n';
      // rContent += 'blog_tag: [' + $("#cblogtags").val() + ']\n';
      if ($("#cblogtags").val()) {
        let tagVal= $("#cblogtags").val();
        rContent += 'blog_tag: [' + tagVal.replaceAll("，", ",") + ']\n';
      }
    axios.get('/backstage/edit_blog_editfurther?data01=' + $('#data01').val() + '&data11=' + $('#data11').val() + '&data21=' + $('#data21').val() + '&data31=' + $('#data31').val() + '&data41=' + $('#data41').val()).then(({data}) => {
      console.log(data);
      $('#data00').val(data.data[0][0]);
      $('#data10').val(data.data[1][0]);
      $('#data20').val(data.data[2][0]);
      $('#data30').val(data.data[3][0]);
      $('#data40').val(data.data[4][0]);
      $('#data01').val(data.data[0][1]);
      $('#data11').val(data.data[1][1]);
      $('#data21').val(data.data[2][1]);
      $('#data31').val(data.data[3][1]);
      $('#data41').val(data.data[4][1]);
    });
    console.log($('#data00').val());
    rContent += 'readmore_ttl: ["' + $('#data00').val() + '","' + $('#data10').val() + '","' + $('#data20').val() + '","' + $('#data30').val() + '","' + $('#data40').val() + '"]\n';
    rContent += 'readmore_lnk: ["' + $('#data01').val() + '","' + $('#data11').val() + '","' + $('#data21').val() + '","' + $('#data31').val() + '","' + $('#data41').val() + '"]\n';
   }
  rContent += "---\n";
  console.log("rContent", rContent);
  return rContent;
}

const parseTitle = (line) => {
  var title = "";
  title = line.replace("### **", "");
  title = title.replace("**", "");
  if (title.includes("敘述")) {
    title = title.replace("<!-- ", "");
    title = title.replace("-->", "");
  }
  return title;
};

const parseAmpImg = (line) => {
  if (line.includes("alt")) {
    const altParameter = line.replace(/ |alt=|"/g, "");
    return { alt: altParameter };
  } else if (line.includes("src")) {
    const srcParameter = line.replace(/ |src=|"/g, "");
    return { src: srcParameter };
  } else if (line.includes("height")) {
    const heightParameter = line.replace(/ |height=|"/g, "");
    return { height: heightParameter };
  } else if (line.includes("width")) {
    const widthParameter = line.replace(/ |width=|"/g, "");
    return { width: widthParameter };
  } else if (line.includes("layout")) {
    const layoutParameter = line.replace(/ |layout=|"|>/g, "");
  }
};

function tableTextToArray(tableHtml) {
  tbl = document.createElement("table");
  tbl.innerHTML = tableHtml.replace("<table>", "").replace("</table>", "");
  var tableInfo = Array.prototype.map.call(
    tbl.querySelectorAll("tr"),
    function (tr) {
      return Array.prototype.map.call(tr.querySelectorAll("td"), function (td) {
        return td.innerHTML;
      });
    }
  );
  return tableInfo;
}

function tableArrayToHtml(tableArray) {
  tbl = document.createElement("table");
  for (j = 0; j < tableArray.length; j++) {
    tr = document.createElement("tr");
    for (k = 0; k < tableArray[j].length; k++) {
      td = document.createElement("td");
      if (k == 0) td.style.width = "25%";
      td.innerHTML = tableArray[j][k];
      tr.appendChild(td);
    }
    tbl.appendChild(tr);
  }
  return tbl.outerHTML.toString();
}

function GenSwfDD(obj) {
  Object.entries(SwfType).forEach(([key, value]) => {
    op = document.createElement("option");
    op.value = key;
    op.text = value;
    obj.appendChild(op);
  });
}

function ReplaceSwfType(inContent) {
  Object.entries(SwfType).forEach(([key, value]) => {
    inContent = inContent.replaceAll("[" + key + "]", "[" + value + "]");
  });
  return inContent;
}

var editor;
var editor1;
editorBlocks = [];
editorBlocks1 = [];
function ParseProductSection(inContent) {
  editorBlocks = [];
  editorBlocks1 = [];
  var aa = $.parseHTML(inContent.trim());
  //處理圖片
  if ($("[id='carousel-with-preview']", aa).length > 0) {
    imgnodes = $("[id='carousel-with-preview']", aa)[0].children[0].childNodes;

    for (
      let i = 0;
      i < $("[id='carousel-with-preview']", aa)[0].children.length;
      i++
    ) {
      const element = $("[id='carousel-with-preview']", aa)[0].children[i];
      let imgnodeItem = element.childNodes;

      var tmpsrc, tmpw, tmph, ampimg;
      if (imgnodeItem[0].nodeName == "IMG") {
        ampimg = imgnodeItem[0].outerHTML;
        tmpsrc = ampimg.substr(
          ampimg.indexOf('src="') + 5,
          ampimg.indexOf('"', ampimg.indexOf('src="') + 5) -
            ampimg.indexOf('src="') -
            5
        );
        tmpw = ampimg.substr(
          ampimg.indexOf('width="') + 7,
          ampimg.indexOf('"', ampimg.indexOf('width="') + 7) -
            ampimg.indexOf('width="') -
            7
        );
        tmph = ampimg.substr(
          ampimg.indexOf('height="') + 8,
          ampimg.indexOf('"', ampimg.indexOf('height="') + 8) -
            ampimg.indexOf('height="') -
            8
        );
        //tmph = ampimg.substr(ampimg.indexOf("width=\"") + 7, ampimg.indexOf("\"", ampimg.indexOf("width=\"") + 7) - ampimg.indexOf("width=\"") - 7);
        editorBlocks.push({
          type: "image",
          data: {
            file: {
              url: BHOUSE_SERVER + editTarget + "/" + tmpsrc,
              width: parseInt(tmpw),
              height: parseInt(tmph),
            },
            caption: "小寶優居 | " + $("#ctitle").val(),
          },
        });
      }
    }

    // for (i = 0; i < imgnodes.length; i++) {
    //   var tmpsrc, tmpw, tmph, ampimg;
    //   if (imgnodes[i].nodeName == "IMG") {
    //     ampimg = imgnodes[i].outerHTML;
    //     console.log('ampimg',ampimg);
    //     tmpsrc = ampimg.substr(
    //       ampimg.indexOf('src="') + 5,
    //       ampimg.indexOf('"', ampimg.indexOf('src="') + 5) -
    //         ampimg.indexOf('src="') -
    //         5
    //     );
    //     tmpw = ampimg.substr(
    //       ampimg.indexOf('width="') + 7,
    //       ampimg.indexOf('"', ampimg.indexOf('width="') + 7) -
    //         ampimg.indexOf('width="') -
    //         7
    //     );
    //     tmph = ampimg.substr(
    //       ampimg.indexOf('height="') + 8,
    //       ampimg.indexOf('"', ampimg.indexOf('height="') + 8) -
    //         ampimg.indexOf('height="') -
    //         8
    //     );
    //     //tmph = ampimg.substr(ampimg.indexOf("width=\"") + 7, ampimg.indexOf("\"", ampimg.indexOf("width=\"") + 7) - ampimg.indexOf("width=\"") - 7);
    //     editorBlocks.push({
    //       type: "image",
    //       data: {
    //         file: {
    //           url: BHOUSE_SERVER + editTarget + "/" + tmpsrc,
    //           width: parseInt(tmpw),
    //           height: parseInt(tmph),
    //         },
    //         caption: "小寶優居 | " + $("#ctitle").val(),
    //       },
    //     });
    //     console.log('editorBlocks',editorBlocks);
    //   }
    // }
  }
  /*     else {
          editorBlocks.push({
              type: "image", data: {
                  file: {
                      url: 'https://bhouse.com.tw/img/logo2.png',
                      width: 300,
                      height: 300,
                  },
                  caption: "小寶優居 | " + $('#ctitle').val(),
              }
          });
      } */
  //editor.api.blocks.render(editorBlocks);
  $("#editorjs")[0].innerHTML = "";
  //alert(editorBlocks);
  editor = new EditorJS({
    readOnly: false,
    holder: "editorjs",
    tools: {
      paragraph: { inlineToolbar: false },
      image: {
        class: ImageTool,
        config: {
          endpoints: {
            byFile: "/backstage/upload" + $("#curl").val(),
            byUrl: "/backstage/getimage" + $("#curl").val(),
          },
        },
      },
    },
    data: { blocks: editorBlocks },
    onReady: function () {
      //alert(editor.blocks.getBlocksCount());
      //saveButton.click();
    },
    onChange: function (api, block) {
      //$('#cimage')[0].val();
      //console.log('something changed', block);
    },
  });

  //類別
  Object.entries(SwfType).forEach(([key, value]) => {
    if ($("#ctype").val() == key) {
      //alert($("#ctype").val());
      $("#swfDropdown").val($("#ctype").val());
    }
  });

  //敘述
  $("#swfDesc").val("");
  if ($("[class='description mb-5']", aa).length > 0) {
    $("#swfDesc").val(
      $(".description", aa)[0]
        .innerHTML.trim()
        .replaceAll("<b>", "")
        .replaceAll("</b>", "")
    );
  }

  //其他
  $("#swfPrice").val("");
  $("#swfColor").val("");
  $("#swfSize").val("");
  $("#swfMat").val("");
  $("#swfMemo").val("");
  if ($("[class='detail']", aa).length > 0) {
    onodes = $("[class='detail']", aa)[0].childNodes;
    for (i = 0; i < onodes.length; i++) {
      for (j = 0; j < onodes[i].childNodes.length; j++) {
        onodes2 = onodes[i].childNodes[j].className;
        if (onodes[i].childNodes[j].nodeName != "#text") {
          if (onodes2 == "pdprice tw-85") {
            $("#swfPrice").val(onodes[i].childNodes[j].innerHTML);
          }
          if (onodes2 == "pdcolor tw-85") {
            $("#swfColor").val(onodes[i].childNodes[j].innerHTML);
          }
          if (onodes2 == "pdsize tw-85") {
            $("#swfSize").val(onodes[i].childNodes[j].innerHTML);
          }
          if (onodes2 == "pmat tw-85") {
            $("#swfMat").val(onodes[i].childNodes[j].innerHTML);
          }
          if (onodes2 == "pdmark tw-85") {
            $("#swfMemo").val(onodes[i].childNodes[j].innerHTML);
          }
        }
      }
      // if (onodes[i].nodeName != "#text") {
      //     if (onodes[i].innerHTML.trim().indexOf("定價 ： ") >= 0)
      //         $("#swfPrice").val(onodes[i].innerHTML.replace("定價 ： ", "").trim());
      //     if (onodes[i].innerHTML.trim().indexOf("顏色 ： ") >= 0)
      //         $("#swfColor").val(onodes[i].innerHTML.replace("顏色 ： ", "").trim());
      //     if (onodes[i].innerHTML.trim().indexOf("尺寸(mm) ： ") >= 0)
      //         $("#swfSize").val(onodes[i].innerHTML.replace("尺寸(mm) ： ", "").trim());
      //     if (onodes[i].innerHTML.trim().indexOf("材質 ： ") >= 0)
      //         $("#swfMat").val(onodes[i].innerHTML.replace("材質 ： ", "").trim());
      //     if (onodes[i].innerHTML.trim().indexOf("備註 ： ") >= 0)
      //         $("#swfMemo").val(onodes[i].innerHTML.replace("備註 ： ", "").trim());
      //     //alert(nodes[i].innerHTML);
      // }
    }
  }

  //處理規格圖片
  if ($("[class='spec']", aa).length > 0) {
    snodes = $("[class='spec']", aa)[0].childNodes;
    //alert(snodes[0].innerHTML);
    for (i = 0; i < snodes.length; i++) {
      var tmpsrc, tmpw, tmph, ampimg;
      if (snodes[i].nodeName == "IMG") {
        ampimg = snodes[i].outerHTML;
        tmpsrc = ampimg.substr(
          ampimg.indexOf('src="') + 5,
          ampimg.indexOf('"', ampimg.indexOf('src="') + 5) -
            ampimg.indexOf('src="') -
            5
        );
        tmpw = ampimg.substr(
          ampimg.indexOf('width="') + 7,
          ampimg.indexOf('"', ampimg.indexOf('width="') + 7) -
            ampimg.indexOf('width="') -
            7
        );
        tmph = ampimg.substr(
          ampimg.indexOf('height="') + 8,
          ampimg.indexOf('"', ampimg.indexOf('height="') + 8) -
            ampimg.indexOf('height="') -
            8
        );
        //tmph = ampimg.substr(ampimg.indexOf("width=\"") + 7, ampimg.indexOf("\"", ampimg.indexOf("width=\"") + 7) - ampimg.indexOf("width=\"") - 7);
        editorBlocks1.push({
          type: "image",
          data: {
            file: {
              url: BHOUSE_SERVER + editTarget + "/" + tmpsrc,
              width: parseInt(tmpw),
              height: parseInt(tmph),
            },
            caption: "小寶優居 | " + $("#ctitle").val(),
          },
        });
      }
    }
  }
  /* else {
      editorBlocks1.push({
          type: "image", data: {
              file: {
                  url: 'https://bhouse.com.tw/img/logo2.png',
                  width: 300,
                  height: 300,
              },
              caption: "小寶優居 | " + $('#ctitle').val(),
          }
      });
  } */
  $("#editorjs1")[0].innerHTML = "";
  editor1 = new EditorJS({
    readOnly: false,
    holder: "editorjs1",
    tools: {
      paragraph: { inlineToolbar: false },
      image: {
        class: ImageTool,
        config: {
          endpoints: {
            byFile: "/backstage/upload" + $("#curl").val(),
            byUrl: "/backstage/getimage" + $("#curl").val(),
          },
        },
      },
    },

    data: { blocks: editorBlocks1 },
    onReady: function () {
      //saveButton.click();
    },
    onChange: function (api, block) {
      //console.log('something changed', block);
    },
  });
  //$('.image-tool__caption').css('display', 'none');
}

function GenProductSection(mimg, specimg) {
  section = document.createElement("div");
  tmpstr = `<div class="furniture-design">
  {{< furniture_design >}}
  <div class="furniture_design_content">
      <div class="sub-tab-content" id="pills-tabContent">
          <div class="container px-0 design-container">
              <div class="d-flex flex-column flex-md-row align-items-md-start align-items-center b-bottom pb-3 mb-5">
                  <div class="slider-box">
                      <div class="slider slider-for slider-design" id='carousel-with-preview'>
                          ##AMP-IMG##
                      </div>
                      <div class="slider slider-nav mt-2" id='carousel-with-preview'>
                          ##PREV-IMG##
                      </div>
                  </div>
                  <div class="ms-2 fw-bold w-100">
                      <h3 class="mt-4">##ctitle##</h3>
                      <p class="description mb-5"><b>##swfDesc##</b></p>
                      <div class="detail">
                          ##swfPrice##
                          ##swfColor##
                          ##swfSize##
                          ##swfMat##
                          ##swfMemo##
                       </div>   
                  </div>
                  </div> 
                  <div>
                      ##SPEC-IMG##
                      <h6 class="mt-4">說明</h6>
                      <ul>
                          <li>1. 商品顏色因拍攝、螢幕差異略有不同，實際顏色請依照門市實際顏色為主。</li>
                          <li>2. 部分商品因應空間大小，保有客製尺寸服務。詳細尺寸資訊，請預約門市諮詢訂購。</li>
                      </ul>
                   </div> 
                   <div class="b-bottom mt-5"></div>  
                  <div class="mb-5">
                      <a href="/furniture_design/other_furniture/">
                          <p class="readMore text-center">
                              <span style="font-size: 18px;" class="fw-normal me-2">&lt;</span>回到其他設計單品
                          </p>
                      </a>
                  </div>  
          </div>
      </div>
  </div>
  </div>`;

  tmpstr = tmpstr.replaceAll("##ctitle##", $("#ctitle").val());
  tmpstr = tmpstr.replaceAll("##ctype##", $("#ctype").val());
  tmpstr = tmpstr.replaceAll("##curl##", $("#curl").val());
  Object.entries(SwfType).forEach(([key, value]) => {
    if ($("#ctype").val() == key)
      tmpstr = tmpstr.replaceAll("##ctypec##", value);
  });
  tmpstr = tmpstr.replaceAll("##swfDesc##", $("#swfDesc").val());
  if ($("#swfPrice").val() != "")
    tmpstr = tmpstr.replaceAll(
      "##swfPrice##",
      "<div class='me-3 my-2 d-flex'><div class='tw-15 fw-bold'>定價</div>" +
        "<div class='pdprice tw-85'>" +
        $("#swfPrice").val() +
        "</div></div>"
    );
  else tmpstr = tmpstr.replaceAll("##swfPrice##", "<span></span>");
  if ($("#swfColor").val() != "")
    tmpstr = tmpstr.replaceAll(
      "##swfColor##",
      "<div class='my-2 d-flex'><div class='tw-15 fw-bold'>顏色</div>" +
        "<div class='pdcolor tw-85'>" +
        $("#swfColor").val() +
        "</div></div>"
    );
  else tmpstr = tmpstr.replaceAll("##swfColor##", "<span></span>");
  if ($("#swfSize").val() != "")
    tmpstr = tmpstr.replaceAll(
      "##swfSize##",
      "<div class='my-2 d-flex'><div class='tw-15 fw-bold'>尺寸</div>" +
        "<div class='pdsize tw-85'>" +
        $("#swfSize").val() +
        "</div></div>"
    );
  else tmpstr = tmpstr.replaceAll("##swfSize##", "<span></span>");
  if ($("#swfMat").val() != "")
    tmpstr = tmpstr.replaceAll(
      "##swfMat##",
      "<div class='my-2 d-flex'><div class='tw-15 fw-bold'>材質</div>" +
        "<div class='pmat tw-85'>" +
        $("#swfMat").val() +
        "</div></div>"
    );
  else tmpstr = tmpstr.replaceAll("##swfMat##", "<span></span>");
  if ($("#swfMemo").val() != "")
    tmpstr = tmpstr.replaceAll(
      "##swfMemo##",
      "<div class='my-2 d-flex'><div class='tw-15 fw-bold'>備註</div> " +
        "<div class='pdmark tw-85'>" +
        $("#swfMemo").val() +
        "</div></div>"
    );
  else tmpstr = tmpstr.replaceAll("##swfMemo##", "<span></span>");

  mimgstr = "";
  firstimg = true;
  for (i = 0; i < mimg.blocks.length; i++) {
    block = mimg.blocks[i];

    if (block.type == "image") {
      iurl = block.data.file.url.split("/");

      if (iurl[iurl.length - 1] != "logo2.png") {
        if (firstimg) {
          $("#cimage").val($("#curl").val() + "/img/" + iurl[iurl.length - 1]);
          firstimg = false;
        }
        mimgstr +=
          '<div class="design-img"><img\n  alt="小寶優居 | ' +
          $("#ctitle").val() +
          '"\n  src="img/' +
          iurl[iurl.length - 1] +
          '"\n  height="auto"\n  width="' +
          block.data.file.width +
          '"\n  layout="responsive">\n</img></div>';
      }
    }
  }
  tmpstr = tmpstr.replaceAll("##AMP-IMG##", mimgstr == "" ? "" : mimgstr);

  previmgstr = "";
  for (i = 0; i < mimg.blocks.length; i++) {
    //alert(block.type);
    block = mimg.blocks[i];
    if (block.type == "image") {
      iurl = block.data.file.url.split("/");
      if (iurl[iurl.length - 1] != "logo2.png") {
        previmgstr +=
          (previmgstr == "" ? "" : "\n") +
          ` <div class="middle-item">
          <img
            src="img/` +
          iurl[iurl.length - 1] +
          `"
            width="40"
            height="auto"
            alt="` +
          block.data.caption +
          `"
          ></img>
        </div>`;
      }
    }
  }
  tmpstr = tmpstr.replaceAll(
    "##PREV-IMG##",
    previmgstr == "" ? "" : previmgstr
  );

  specimgstr = "";

  if (specimg.blocks.length === 0) {
    specimgstr = "";
  } else {
    specimgstr += "<h6>尺寸規格</h6>";
    for (i = 0; i < specimg.blocks.length; i++) {
      //alert(block.type);
      block = specimg.blocks[i];
      if (block.type == "image") {
        iurl = block.data.file.url.split("/");
        if (iurl[iurl.length - 1] != "logo2.png") {
          specimgstr +=
            '<img\n class="w-100 h-100" alt="小寶優居 | ' +
            $("#ctitle").val() +
            '"\n  src="img/' +
            iurl[iurl.length - 1] +
            '"\n >\n</img>';
        }
      }
    }
  }
  if (specimgstr === "") {
    specimgstr += "<div></div>";
  }

  tmpstr = tmpstr.replaceAll(
    "##SPEC-IMG##",
    specimgstr == "" ? "" : '<div class="spec">' + specimgstr + "</div>"
  );

  console.log(tmpstr);

  return tmpstr;
}

class MDParser {
  constructor(MDtext) {
    this.headerText = "";
    this.contentText = "";
    this.title = "";
    this.date = new Date();
    this.draft = true;
    this.type = "";
    this.url = "";
    this.image = "";
    this.description = "";
    this.weight = 1;
    this.tag = [];
  }
}
