<template>
  <div>
    <div class="inner--headers">
      <h2>{{ pageId }}</h2>
      <div class="bread--crumbs--wrap">
        <span>홈</span>
        <span>미디어 관리</span>
        <span>{{ pageId }}</span>
      </div>
    </div>

    <div class="view-wrap mt--45">
      <div class="view-box">
        <div class="view-box-top">
          <h3 v-if="pageType == 'I'">뉴스룸 등록</h3>
          <h3 v-else>뉴스룸 수정</h3>
        </div>
        <div class="view-box-btm">
          <div class="form-style1">
            <v-form ref="addForm">
              <table>
                <colgroup>
                  <col style="width: 12.5rem" />
                  <col />
                </colgroup>
                <tbody>
                  <tr>
                    <th>언어</th>
                    <td>
                      <v-radio-group
                        v-model="form.formValue0"
                        inline
                        hide-details
                        class="radio--group"
                      >
                        <v-radio label="Korean" value="KR"></v-radio>
                        <v-radio label="English" value="EN"></v-radio>
                        <v-radio label="Chinese" value="CN"></v-radio>
                        <v-radio label="Japanese" value="JP"></v-radio>
                      </v-radio-group>
                    </td>
                  </tr>
                  <tr>
                    <th>노출여부<span class="bul">*</span></th>
                    <td>
                      <v-radio-group
                        class="radio--group"
                        v-model="form.formValue2"
                        inline
                        hide-details
                      >
                        <v-radio label="노출" value="Y"></v-radio>
                        <v-radio label="비노출" value="N"></v-radio>
                      </v-radio-group>
                    </td>
                  </tr>
                  <tr>
                    <th>고정여부<span class="bul">*</span></th>
                    <td>
                      <v-radio-group
                        class="radio--group"
                        v-model="form.formValue3"
                        inline
                        hide-details
                      >
                        <v-radio label="고정 " value="Y"></v-radio>
                        <v-radio label="비고정" value="N"></v-radio>
                      </v-radio-group>
                    </td>
                  </tr>
                  <tr>
                    <th>제목<span class="bul">*</span></th>
                    <td>
                      <v-text-field
                        v-model="form.formValue1"
                        class="custom-input mini"
                        placeholder="제목을 입력해주세요."
                        :rules="[useValid.required('제목')]"
                      ></v-text-field>
                    </td>
                  </tr>
                  <tr>
                    <th>해시태그<span class="bul">*</span></th>
                    <td>
                      <v-text-field
                        v-model="form.formValue7"
                        class="custom-input mini"
                        placeholder="해시태그를 입력해주세요. 예) 태그, 태그 형태로 여러개 입력시 ,를 이용하여 입력해주세요"
                        :rules="[useValid.required('해시태그')]"
                      ></v-text-field>
                    </td>
                  </tr>

                  <tr>
                    <th>썸네일 이미지<span class="bul">*</span></th>
                    <td>
                      <div class="equip--image--wrap">
                        <!--이미지가 없을 때-->
                        <div class="equip--image" v-show="!form.formValue4">
                          <img src="/assets/img/ic_no_img.svg" />
                        </div>
                        <!--이미지 첨부했을 때-->
                        <div class="equip--image" v-show="form.formValue4">
                          <CoolLightBox
                            v-if="items.length > 0"
                            :items="items"
                            :index="index"
                            @close="index = null"
                          />

                          <div class="images-wrapper">
                            <div
                              class="image"
                              :key="imageIndex"
                              @click="index = imageIndex"
                            >
                              <img id="preview_image" :src="imgTemp" />
                            </div>
                          </div>
                        </div>
                        <div class="equip--image--select">
                          <div class="form--group">
                            <label
                              for="fileUpload_pic"
                              class="file--btn"
                              @click="fnPicFileUploadOpen()"
                              >파일 선택</label
                            >
                            <v-file-input
                              v-model="form.formValue4"
                              id="fileUpload_pic"
                              ref="fileupload_pic"
                              accept=".jpg, .jpeg, .png, .gif"
                              variant="plain"
                              hide-details
                              placeholder="선택된 파일 없음"
                              prepend-icon=""
                              class="custom-input"
                              style="max-width: 400px"
                              height="33px"
                              :clearable="false"
                              @change="fnUploadPicFileCheck()"
                            >
                              <template #append>
                                <div class="v-input__icon v-input__icon--clear">
                                  <button
                                    @click="clearFile"
                                    type="button"
                                    aria-label="clear icon"
                                    tabindex="-1"
                                    class="v-icon notranslate v-icon--link mdi mdi-close"
                                  ></button>
                                </div>
                              </template>
                            </v-file-input>
                          </div>
                          <p class="equip--image--desc">
                            (권장 이미지 : 1024 x 768 / gif, jpg, jpeg, png)
                          </p>
                        </div>
                      </div>
                    </td>
                  </tr>
                  <tr>
                    <th>내용<span class="bul">*</span></th>
                    <td>
                      <SunEditorWrapper
                        ref="sunEditorWrapper"
                        :initialContent="editorContentReq"
                      />
                    </td>
                  </tr>
                  <!--
                  <tr>
                    <th>첨부 파일</th>
                    <td>
                      <div
                        class="form--group--inner"
                        v-if="pageType == 'U' && uploadFiles[0].file_name"
                      >
                        <div @click="fnFileDownload(uploadFiles[0])" class="text--box">
                          {{ uploadFiles[0].ogn_name }}
                        </div>                       
                      </div>
                      <div class="form--group flex--type max--w320">
                        <v-file-input
                          v-model="form.formValue6"
                          id="fileupload"
                          ref="fileupload"
                          accept=".jpg, .jpeg, .png, .zip, .pdf, .ppt, .xls, .pptx, .xlsx, .hwp, .doc, .docx"
                          placeholder=""
                          class="custom-input mini"
                          prepend-icon=""
                          label=""
                          variant="outlined"
                          hide-details
                          @change="fnUploadFileCheck()"
                        ></v-file-input>
                        <v-btn class="file--btn" elevation="0" @click="fnFileUploadOpen()"
                          >첨부하기</v-btn
                        >
                      </div>
                    </td>
                  </tr>-->
                </tbody>
              </table>
            </v-form>
          </div>
        </div>
      </div>

      <div class="view-btm-btn">
        <div class="btn-l">
          <v-btn class="custom-btn btn-list" @click="listLocated"
            ><i class="ico"></i>목록</v-btn
          >
          <v-btn v-show="pageType == 'U'" class="custom-btn btn-del" @click="fnDelEvt"
            ><i class="ico"></i>삭제</v-btn
          >
        </div>
        <div class="btn-r">
          <v-btn v-if="pageType == 'I'" class="custom-btn btn-blue2" @click="fnBtnEvt"
            ><i class="ico"></i>저장</v-btn
          >
          <v-btn v-else class="custom-btn btn-blue2" @click="fnBtnEvt"
            ><i class="ico"></i>수정</v-btn
          >
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import useAxios from "@/composables/useAxios";
import useUtil from "@/composables/useUtil";
import useErrorHandler from "@/composables/useErrorHandler";
import SunEditorWrapper from "@/components/sunEdt.vue";

/************************************************************************
|    레이아웃
************************************************************************/
definePageMeta({
  layout: "default",
});

/************************************************************************
|    스토어
 ************************************************************************/
const useDtStore = useDetailStore();

/************************************************************************
|    전역
 ************************************************************************/
const { $toast, $log, $dayjs, $eventBus } = useNuxtApp();
const router = useRouter();
const pageId = ref("NEWS ROOM");

const sunEditorWrapper = ref(null); //에디터용 전역
const updatedContent = ref(null); //에디터용 전역
const editorContentReq = ref(); //에디터용 전역
const addForm = ref(null);
const index = ref(null);
const imageIndex = ref(0);
const items = ref([]);
const quillEditor = ref(null);
const imgTemp = ref(null);
const rowId = ref();
const form = ref({
  formValue0: "KR",
  formValue1: "",
  formValue2: "Y",
  formValue3: "N",
  formValue4: null,
  formValue5: "",
  formValue6: null,
  formValue7: null,
  fileResponse: null,
});
const apiUrl = ref("");

apiUrl.value = import.meta.env.VITE_APP_API_URL;

const fileUpload = ref(null);
const uploadFiles = ref([
  {
    file_name: "",
    ogn_name: "",
  },
]);

const uploadPicFiles = ref([
  {
    file_name: "",
    ogn_name: "-",
  },
]);

const deleteFile = ref("");
const objProc = ref({
  validErrorMessage: "",
});

const pageType = ref("");

/************************************************************************
|    함수(METHODS)
************************************************************************/

const listLocated = () => {
  router.push({
    path: "/view/media/newsList",
  });
};

/**
 * 첨부파일 다운로드
 */
const fnFileDownload = (objFile) => {
  let reqData = { file_name: objFile.file_name };
  useAxios()
    .post("/file/download", reqData, { responseType: "blob" })
    .then((res) => {
      const contentType = res.headers["content-type"] || "application/octet-stream"; // 기본값

      const blob = new Blob([res.data], { type: contentType });
      let fileUrl = window.URL.createObjectURL(blob);
      let link = document.createElement("a");
      link.href = fileUrl;
      link.style.display = "none";
      console.log(objFile.ogn_name);
      link.download = objFile.ogn_name;
      document.body.appendChild(link);
      link.click();
      link.remove();
      window.URL.revokeObjectURL(fileUrl);
    })
    .catch((error) => {})
    .finally(() => {});
};

const fnPicFileUploadOpen = () => {
  let fileUpload = document.getElementById("fileupload_pic");
  if (fileUpload != null) {
    fileUpload.click();
  }
};

const fnFileUploadOpen = () => {
  let fileUpload = document.getElementById("fileupload");
  if (fileUpload != null) {
    fileUpload.click();
  }
};
/**
 * 첨부 파일 등록
 */
const fnUploadFileCheck = () => {
  if (form.value.formValue6) {
    // 10Mb 이상은 업로드 불가
    if (form.value.formValue6.size > 10 * 1024 * 1024) {
      fnOpenCommPop("10mb 이상은 업로드가 불가합니다.");
      form.value.formValue6 = null;
      return;
    }
    // 이미지 파일 형식 체크
    let extension = form.value.formValue6.name.split(".").pop().toLowerCase();
    if (
      extension != "jpg" &&
      extension != "jpeg" &&
      extension != "png" &&
      extension != "gif" &&
      extension != "zip" &&
      extension != "ppt" &&
      extension != "pptx" &&
      extension != "pdf" &&
      extension != "xls" &&
      extension != "xlsx" &&
      extension != "hwp" &&
      extension != "doc" &&
      extension != "docx"
    ) {
      fnOpenCommPop("파일 형식 또는 확장자가 올바르지 않습니다.");
      form.value.formValue6 = null;
      return;
    }
  }
};
/**
 * 이미지 다운로드
 */
const fnPicFileDownload = (objFile) => {
  let local = this;
  let reqData = { file_name: objFile.file_name };

  useAxios()
    .post("/picInfo/download", reqData)
    .then((res) => {
      let reader = new FileReader();
      reader.readAsDataURL(res.data);
      reader.onloadend = function () {
        // File 객체 생성
        let blob = new Blob([res.data]);
        let file = new File([blob], objFile.ogn_name);
        local.form.formValue4 = file;

        // 화면 랜더링
        local.items[0] = reader.result;
        console.log(reader.result);

        $("#preview_image").attr("src", reader.result);
      };
    })
    .catch((err) => {
      this.$log.debug("[unitEquipmentAdd][fnPicFileDownload][error]");
    })
    .finally(() => {
      this.$log.debug("[unitEquipmentAdd][fnPicFileDownload][finally]");
    });
};
const fnUploadPicFileCheck = () => {
  if (form.value.formValue4) {
    // 10Mb 이상은 업로드 불가
    if (form.value.formValue4.size > 10 * 1024 * 1024) {
      fnOpenCommPop("10mb 이상은 업로드가 불가합니다.");
      form.value.formValue4 = null;
      return;
    }
    // 이미지 파일 형식 체크
    let extension = form.value.formValue4.name.split(".").pop().toLowerCase();
    if (
      extension != "jpg" &&
      extension != "jpeg" &&
      extension != "png" &&
      extension != "gif"
    ) {
      fnOpenCommPop("파일 형식 또는 확장자가 올바르지 않습니다.");
      form.value.formValue4 = null;
      return;
    }

    objProc.validErrorMessage = "";

    // 이미지 미리보기
    let previewImage = new Image();
    let tempImageUrl = window.URL.createObjectURL(form.value.formValue4);

    console.log(tempImageUrl);

    previewImage.src = tempImageUrl;
    items.value[0] = tempImageUrl;
    imgTemp.value = tempImageUrl;
  }
};
const clearFile = () => {
  form.value.formValue4 = null;
};

/*======================================================================
|    작성 시퀀스
| 1. 작성 컨펌
| 2. 버튼 체크
| 3. 등록시 -> 등록 API 호출
======================================================================*/

const fnBtnEvt = async () => {
  await editorContent();

  nextTick(() => {
    if (addForm.value && typeof addForm.value.validate === "function") {
      addForm.value
        .validate()
        .then((isValid) => {
          if (
            isValid.valid &&
            updatedContent.value != undefined &&
            updatedContent.value != null &&
            updatedContent.value != "<p><br></p>" &&
            form.value.formValue4 != null
          ) {
            if (pageType.value == "I") fnRegEvt();
            else fnUpdEvt();
          } else {
            let param = {
              id: pageId,
              title: "뉴스 룸",
              content: "필수항목을 입력해주세요.",
              yes: {
                text: "확인",
                isProc: false,
              },
              no: {
                text: "취소",
                isProc: false,
              },
            };
            $eventBus.emit("OPEN_CONFIRM_POP_UP", param);
          }
        })
        .catch((err) => {
          console.error("벨리데이션 에러", err);
        });
    } else {
      console.error("항목 누락체크[fnRegCheck]]");
    }
  });
};

const fnRegCheck = () => {};
const fnOpenCommPop = (__TEXT) => {
  let param = {
    id: pageId,
    title: "알림",
    content: __TEXT,
    yes: {
      text: "확인",
      isProc: false,
    },
  };
  $eventBus.emit("OPEN_CONFIRM_POP_UP", param);
};

const fnRegEvt = () => {
  let param = {
    id: pageId,
    title: "뉴스룸 등록",
    content: "등록하시겠습니까?",
    yes: {
      text: "등록",
      isProc: true,
      event: "FN_INSERT",
      param: "",
    },
    no: {
      text: "취소",
      isProc: false,
    },
  };
  $eventBus.emit("OPEN_CONFIRM_POP_UP", param);
};

const fnUpdEvt = () => {
  let param = {
    id: pageId,
    title: "뉴스룸 수정",
    content: "수정하시겠습니까?",
    yes: {
      text: "확인",
      isProc: true,
      event: "FN_UPDATE",
      param: "",
    },
    no: {
      text: "취소",
      isProc: false,
    },
  };
  $eventBus.emit("OPEN_CONFIRM_POP_UP", param);
};

const fnInsert = async () => {
  // //BASE64에서 실제 파일서버에 파일 전성후 내용 컨텐츠 REAL주소로 변경
  // await editorContent();

  let frm = new FormData();
  let wterGet = localStorage.getItem("tempAccess");
  let params = JSON.stringify({
    //seq: useDtStore.boardInfo.seq,
    //seq: "",
    brd_cd: "BR00",
    brd_lang: form.value.formValue0,
    show_yn: form.value.formValue2,
    hash_tag: form.value.formValue7,
    title: form.value.formValue1,
    content: updatedContent.value,
    wter: wterGet,
    fix_yn: form.value.formValue3,
  });

  frm.append("params", params);
  frm.append("picObj", form.value.formValue4);
  //frm.append("fileObj", form.value.formValue6);

  useAxios()
    .post("/brd/ins", frm, { headers: { "Content-Type": "multipart/form-data" } })
    .then((res) => {
      router.push("/view/media/newsList");
    })
    .catch((error) => {
      let param = {
        id: pageId,
        title: "뉴스룸 등록",
        content: "고정여부값은 4건 초과 등록할 수 없습니다",
        yes: {
          text: "확인",
          isProc: true,
        },
        no: {
          text: "취소",
          isProc: false,
        },
      };
      $eventBus.emit("OPEN_CONFIRM_POP_UP", param);
    })
    .finally(() => {
      //$log.debug("[equipMgmtReg][fnGetTenantList][finished]");
      //objSlt.value.tenantNameList = _cloneDeep(temp);
    });
};

const fnUpdate = async () => {
  //BASE64에서 실제 파일서버에 파일 전성후 내용 컨텐츠 REAL주소로 변경

  let frm = new FormData();
  let wterGet = localStorage.getItem("tempAccess");
  let params = JSON.stringify({
    seq: useDtStore.boardInfo.seq,
    brd_cd: "BR00",
    brd_lang: form.value.formValue0,
    show_yn: form.value.formValue2,
    title: form.value.formValue1,
    content: updatedContent.value,
    hash_tag: form.value.formValue7,
    wter: wterGet,
    fix_yn: form.value.formValue3,
    url_link: "", //?
  });

  frm.append("params", params);
  frm.append("picObj", form.value.formValue4);
  //frm.append("fileObj", form.value.formValue6);

  useAxios()
    .post("/brd/upd", frm, { headers: { "Content-Type": "multipart/form-data" } })
    .then((res) => {
      router.push("/view/media/newsList");
    })
    .catch((error) => {
      //$log.debug("[equipMgmtReg][fnGetTenantList][error]");
      //useErrorHandler().fnSetCommErrorHandle(error, fnGetTenantList);
    })
    .finally(() => {
      //$log.debug("[equipMgmtReg][fnGetTenantList][finished]");
      //objSlt.value.tenantNameList = _cloneDeep(temp);
    });
};

const fnDelEvt = () => {
  let param = {
    id: pageId,
    title: "뉴스룸",
    content: "삭제하시겠습니까?",
    yes: {
      text: "확인",
      isProc: true,
      event: "FN_DELETE",
      param: "",
    },
    no: {
      text: "취소",
      isProc: false,
    },
  };
  $eventBus.emit("OPEN_CONFIRM_POP_UP", param);
};

const fnDelete = () => {
  let wterGet = localStorage.getItem("tempAccess");
  let req = {
    brd_cd: "BR00",
    seq: useDtStore.boardInfo.seq,
    wter: wterGet,
  };

  useAxios()
    .post("/brd/del", req)
    .then((res) => {
      router.push("/view/media/newsList");
    })
    .catch((error) => {
      //$log.debug("[equipMgmtReg][fnGetTenantList][error]");
      //useErrorHandler().fnSetCommErrorHandle(error, fnGetTenantList);
    })
    .finally(() => {
      //$log.debug("[equipMgmtReg][fnGetTenantList][finished]");
      //objSlt.value.tenantNameList = _cloneDeep(temp);
    });
};

const fnDetail = () => {
  let req = {
    seq: useDtStore.boardInfo.seq,
  };
  useAxios()
    .post("/brd/detail", req)
    .then((res) => {
      const resData = res.data;

      form.value.formValue0 = resData.brd_lang;
      form.value.formValue2 = resData.show_yn;
      form.value.formValue1 = resData.title;
      form.value.formValue3 = resData.fix_yn;
      form.value.formValue7 = resData.hash_tag;

      //에디터에 컨텐츠 전달
      editorContentReq.value = resData.content;

      uploadFiles.value[0].file_name = resData.file_title;
      uploadFiles.value[0].ogn_name = resData.ogn_f_title;

      form.value.formValue4 = resData.file_title_pic;

      uploadPicFiles.value[0].file_name = resData.file_title_pic;
      uploadPicFiles.value[0].ogn_name = resData.ogn_f_title_pic;
      imgTemp.value =
        apiUrl.value +
        "/images/" +
        res.data.path.replace(/.*\/files\//, "") +
        "/" +
        res.data.file_title_pic;
    })
    .catch((error) => {
      //$log.debug("[equipMgmtReg][fnGetTenantList][error]");
      //useErrorHandler().fnSetCommErrorHandle(error, fnGetTenantList);
    })
    .finally(() => {
      //$log.debug("[equipMgmtReg][fnGetTenantList][finished]");
      //objSlt.value.tenantNameList = _cloneDeep(temp);
    });
};

/*=======================================================================
| 최종 에디터 이미지 url치환 : S
/*=======================================================================*/

const editorContent = async () => {
  const content = sunEditorWrapper.value.getEditorContent();
  updatedContent.value = await processEditorContent(content);
  console.log("Updated content:", updatedContent.value);
};

// Base64 데이터를 Blob으로 변환
const base64ToBlob = (base64, mimeType) => {
  const byteString = atob(base64.split(",")[1]);
  const arrayBuffer = new ArrayBuffer(byteString.length);
  const uint8Array = new Uint8Array(arrayBuffer);

  for (let i = 0; i < byteString.length; i++) {
    uint8Array[i] = byteString.charCodeAt(i);
  }

  return new Blob([uint8Array], { type: mimeType });
};

// Base64 데이터를 File 객체로 변환
const base64ToFile = (base64, mimeType, fileName) => {
  const blob = base64ToBlob(base64, mimeType);
  return new File([blob], fileName, { type: mimeType });
};

// 이미지 업로드 처리 (useAxios)
const uploadImage = async (file) => {
  const formDataEdt = new FormData();
  formDataEdt.append("picObj", file);

  return useAxios()
    .post("/pic/upload", formDataEdt, {
      headers: { "Content-Type": "multipart/form-data" },
    })
    .then((res) => {
      const filePath = res.data.ogn_name.path.replace(/.*\/files\//, "");
      const fileName = res.data.ogn_name.file_name;
      return `${apiUrl.value}/images/${filePath}/${fileName}`; // 최종 URL 반환
    })
    .catch((error) => {
      console.error("Image upload failed:", error);
      return null;
    });
};

// 에디터 내용 처리 및 이미지 업로드
const processEditorContent = async (content) => {
  const parser = new DOMParser();
  const doc = parser.parseFromString(content, "text/html");
  const images = doc.querySelectorAll("img");

  for (let i = 0; i < images.length; i++) {
    const img = images[i];
    const src = img.src;

    if (src.startsWith("data:image")) {
      // MIME 타입과 파일 이름 추출
      const mimeType = src.split(";")[0].split(":")[1];
      const extension = mimeType.split("/")[1];
      const fileName = `image-${i + 1}.${extension}`;

      // Base64 데이터를 File 객체로 변환
      const file = base64ToFile(src, mimeType, fileName);

      // 이미지 업로드 및 URL 반환
      const finalUrl = await uploadImage(file);
      if (finalUrl) {
        img.src = finalUrl; // 이미지 src 업데이트
      }
    }
  }

  return doc.body.innerHTML; // 최종 수정된 HTML 반환
};

/*=======================================================================
| 최종 에디터 이미지 url치환 : E
/*=======================================================================*/

/************************************************************************
|    팝업 이벤트버스 정의
************************************************************************/
$eventBus.off("FN_INSERT");
$eventBus.on("FN_INSERT", () => {
  fnInsert();
});

$eventBus.off("FN_UPDATE");
$eventBus.on("FN_UPDATE", () => {
  fnUpdate();
});

$eventBus.off("FN_DELETE");
$eventBus.on("FN_DELETE", () => {
  fnDelete();
});

/************************************************************************
|    라이프사이클
************************************************************************/
onMounted(() => {
  pageType.value = useDtStore.boardInfo.pageType;

  //상세 등록 아니 리스트 클릭시 상세 정보로 접근
  if (pageType.value == "U") {
    fnDetail();
  }
});

/************************************************************************
|    WATCH
************************************************************************/
</script>
