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

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',
        }); */
});
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();
    //console.log($("#ctype").val());
    // $("#dialog-form").dialog();
    if ($("#ctype").val() == "collection") {
      $("#scat").hide();
      console.log($("#ctype").val());
      editorslider = 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(),
              },
            },
          },
        },
      });
      console.log("editorslider", editorslider);
    } else if (
      $("#ctype").val() == "maincategories" ||
      $("#ctype").val() == "blog"
    ) {
      $("#sdesc").hide();
    } else if ($("#ctype").val() == "news") {
      $("#sdesc").hide();
      $("#scat").hide();
      $("#simg").hide();
    } else {
      ParseProductSection(contentMatters.join(""));
    }
    $("#myModal").modal();

    //console.log(frontMatters);
    //alert($('#cimage').val());
  });
}

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 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

// writeMd 修改
function writeMd() {
  axios
    .get("/backstage/utils?trantext=" + $("#ccategories").val())
    .then(({ data }) => {
      $("#ccol1").val(data);
    })
    .finally(() => {
      console.log("ctype", $("#ctype").val());
      if (window.location.pathname == "/backstage/collections") {
        mdContent = setContent();
        // console.log('call setContent()');
      } else {
        mdContent = GetMdHeader();
        // console.log('call GetMdHeader()');
      }
      // mdContent = GetMdHeader();
      mdContent += contentMatters.join("\n");
      var formData = new FormData();
      var imagefile = document.querySelector("#cfile");
      console.log(imagefile.files);
      formData.append("image", imagefile.files[0]);
      axios
        .post("/backstage/upload/title", formData, {
          headers: {
            "Content-Type": "multipart/form-data",
          },
        })
        .then(({ data }) => {
          $("#cfile").val("");
          if (data.success == "1") {
            mdContent = mdContent.replace(
              $("#cimage").val(),
              "/img/title/" +
                data.file.url.substring(data.file.url.lastIndexOf("/") + 1)
            );
            //alert(data.file.url.substring(data.file.url.lastIndexOf('/')+1));
          }

          postData = {
            content: mdContent,
            url: editTarget,
          };
          //console.log(mdContent);
          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: ")) {
        //alert(line);
        $("#cmetattl").val(
          line.replace("meta_title: ", "").replaceAll('"', "")
        );
      } else if (line.includes("title: ")) {
        $("#ctitle").val(line.replace("title: ", "").replaceAll('"', ""));
        //console.log($('#ctitle').val());
      }
      if (line.includes("date: ")) {
        //alert(line);
        $("#cdate").val(line.replace("date: ", "").replaceAll('"', ""));
      }
      if (line.includes("draft: ")) {
        //alert(line);
        $("#cdraft").val(line.replace("draft: ", "").replaceAll('"', ""));
        //console.log($('#cdraft').val());
        $("#cdraft").removeAttr("checked");
        if ($("#cdraft").val() == "false") $("#cdraft").prop("checked", true);
        /*
                if($('#cdraft').val() == 'true') 
                    $('#cdraft').removeAttr('checked');
                else
                    $('#cdraft').attr('checked','true');
                    */
      }
      if (line.includes("type: ")) {
        //alert(line);
        $("#ctype").val(line.replace("type: ", "").replaceAll('"', ""));
      }
      if (line.includes("url: ")) {
        //alert(line);
        $("#curl").val(line.replace("url: ", "").replaceAll('"', ""));
      }
      if (line.includes("image: ")) {
        //alert(line);
        $("#cimage").val(line.replace("image: ", "").replaceAll('"', ""));
      }
      if (line.includes("meta_description: ")) {
        //alert(line);
        $("#cmetadsc").val(
          line.replace("meta_description: ", "").replaceAll('"', "")
        );
      } else if (line.includes("collection_description: ")) {
        //collections
        //alert(line);
        $("#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")
        );
        //console.log($('#cdescription').val());
      }
      if (line.includes("weight: ")) {
        //alert(line);
        $("#cweight").val(line.replace("weight: ", "").replaceAll('"', ""));
      }
      if (line.includes("tag: ")) {
        //alert(line);
        $("#ctag").val(line.replace("tag: ", "").replaceAll('"', ""));
      }
      if (line.includes("tags: ")) {
        //alert(line);
        if ($("#ctags").length > 0) {
          $("#ctags").val(line.replace("tags: ", "").replaceAll('"', ""));
          tags = $("#ctags").val().split(",");
          for (var tag of tags) {
            //console.log(tag);
            for (var toi of tagOptionIds) {
              $("#" + toi + " option").each(function () {
                if (this.value == tag) this.selected = true;
              });
            }
          }
        }
      }
      if (line.includes("categories: ")) {
        //alert(line);
        $("#ccategories").val(
          line
            .replace("categories: ", "")
            .replace("categories: ", "")
            .replace(/\[|]/g, "")
            .replace(/\"/g, "")
        );
      }
      /* if (line.includes('caturl: ')) {
                //alert(line);
                $('#ccaturl').val(line.replace('caturl: ', '').replaceAll('\"', ''));
            } */
      if (line.includes("col1: ")) {
        //alert(line);
        $("#ccol1").val(line.replace("col1: ", "").replaceAll('"', ""));
      }
      if (line.includes("col2: ")) {
        //alert(line);
        $("#ccol2").val(line.replace("col2: ", "").replaceAll('"', ""));
      }

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

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

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

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

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

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

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

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

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

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

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

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

      if (line.includes("collection_slider: ")) {
        //$('#ccollslider').val(line.replace('collection_slider: ', '').replaceAll('\"', ''));
      }

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

      // back to normal
      if (line.includes("---")) {
        isNotFrontMatterCount += 1;
      }
      continue;
    }
    contentMatters.push(line);
    /*         if (line.toString().trim() == "") {
                    rblocks.push({ 'type': 'br', 'text': line });
                    continue;
                } */

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

    if (line.includes("##")) {
      line = line.replaceAll("##", "");
      rblocks.push({ type: "title", text: line });
      continue;
    }

    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);
  return rblocks;
}

var testdata = [];

function setContent() {
  editorslider
    .save()
    .then((outputData) => {
      console.log("Article data: ", outputData);
      GetMdHeader(outputData);
    })
    .catch((error) => {
      console.log("Saving failed: ", error);
    });
}

function GetMdHeader(data = []) {
  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";
  rContent += 'type: "' + $("#ctype").val() + '"\n';
  rContent += 'url: "' + $("#curl").val() + '"\n';
  //mdContent += 'url: "' + $('#curl').val() + '"\n';
  rContent += 'image: "' + $("#cimage").val() + '"\n';

  if ($("#ctype").val() == "collection") {
    rContent += 'collection_name: "' + $("#ccollname").val() + '"\n';
    rContent += 'cover_img: "' + $("#ccoverimg").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';
    console.log("outputData", JSON.stringify(data, null, 2));
    for (i = 0; i < data.blocks.length; i++) {
      block = data.blocks[i];
      iurl = block.data.file.url.split("/");
      console.log("img/" + iurl[iurl.length - 1]);
    }
    // rContent += 'collection_slider: ['+collection_slider_img+']\n';
    rContent += 'banner_img_text: "' + $("#ccoverimgtxt").val() + '"\n';
    rContent += 'homeowner: "' + $("#chomeowner").val() + '"\n';
    rContent += 'size: "' + $("#csize").val() + '"\n';
    rContent += 'bed_num: "' + $("#cbednum").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: "' + $("#cbudget").val() + '"\n';
    rContent += 'construction: "' + $("#cconstruction").val() + '"\n';
    rContent += 'collection_description: "' + $("#ccolldesc").val() + '"\n';
    // rContent += 'collection_slider: "' + $('#ccollslider').val() + '"\n';
    // rContent += 'collection_slider: []\n';
    rContent += 'comment: "' + $("#ccomment").val() + '"\n';
    console.log(rContent);
  } 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';
    console.log($("#cdescription").val());
  }
  rContent += "---\n";
  //alert(rContent);
  // rContent.replaceAll('"',"&apos;"); # replace " with '' (two single quotes)

  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);
  }
  //alert(tbl.outerHTML.toString());
  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].childNodes;
    for (i = 0; i < imgnodes.length; i++) {
      var tmpsrc, tmpw, tmph, ampimg;
      if (imgnodes[i].nodeName == "AMP-IMG") {
        //alert(imgnodes[i].nodeName);
        ampimg = imgnodes[i].outerHTML;
        tmpsrc = ampimg.substr(
          ampimg.indexOf('src="') + 5,
          ampimg.indexOf('"', ampimg.indexOf('src="') + 5) -
            ampimg.indexOf('src="') -
            5
        );
        //alert(tmpsrc);
        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(),
          },
        });
      }
    }
  }
  /*     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']", aa).length > 0) {
    $("#swfDesc").val(
      $(".description", aa)[0]
        .innerHTML.trim()
        .replaceAll("<b>", "")
        .replaceAll("</b>", "")
    );
  }
  //alert(editorBlocks);
  //其他
  $("#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++) {
      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 == "AMP-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="mb-5">##swfDesc##</p>
                            ##swfPrice##
                            ##swfColor##
                            ##swfSize##
                            ##swfMat##
                            ##swfMemo##
                    </div>
                    </div> 
                        ##SPEC-IMG##
                        <h6 class="mt-4">說明</h6>
                        <ul>
                            <li>1. 商品顏色因拍攝、螢幕差異略有不同，實際顏色請依照門市實際顏色為主。</li>
                            <li>2. 部分商品因應空間大小，保有客製尺寸服務。詳細尺寸資訊，請預約門市諮詢訂購。</li>
                        </ul>
                    <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'>定價</div>" +
        "<div class='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'>顏色</div>" +
        "<div class='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'>尺寸</div>" +
        "<div class='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'>材質</div>" +
        "<div class='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'>備註</div> " +
        "<div class='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];
    console.log(block.data);

    console.log(block.data.file.url);
    if (block.type == "image") {
      iurl = block.data.file.url.split("/");
      console.log("img/" + iurl[iurl.length - 1]);

      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 = "";
  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>';
      }
    }
  }
  tmpstr = tmpstr.replaceAll(
    "##SPEC-IMG##",
    specimgstr == ""
      ? ""
      : '<div class="b-bottom pb-3 mb-5"><h6>尺寸規格</h6>' +
          specimgstr +
          "</div>"
  );

  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 = [];
    for (var line of MDtext.split("\n")) {
      //console.log(line);
    }
  }
}
