<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'">CURATION 등록</h3>
          <h3 v-else>CURATION 수정</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>노출여부<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.formValue9"
                        inline
                        hide-details
                        :rules="[useValid.required('구분')]"
                      >
                        <v-radio label="유튜브" value="Y"></v-radio>
                        <v-radio label="링크드인" value="L"></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 class="">
                      <SunEditorWrapper
                        ref="sunEditorWrapper"
                        :initialContent="editorContentReq"
                      />
                    </td>
                  </tr>
                  <tr>
                    <th>썸네일 이미지<span class="bul">*</span></th>
                    <td>
                      <div class="equip--image--wrap">
                        <!--이미지가 없을 때-->
                        <div class="equip--image" v-show="!form.formValue7">
                          <img src="/assets/img/ic_no_img.svg" />
                        </div>
                        <!--이미지 첨부했을 때-->
                        <div class="equip--image" v-show="form.formValue7">
                          <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.formValue7"
                              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"
                              :rules="[useValid.required('썸네일 이미지')]"
                              :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 class="div_error_text">{{ objProc.validErrorMessage }}</div>
                      </div>
                    </td>
                  </tr>
                  <tr>
                    <th>URL<span class="bul">*</span></th>
                    <td>
                      <v-text-field
                        v-model="form.formValue5"
                        class="custom-input mini"
                        placeholder="URL 링크를 입력해주세요"
                        :rules="[useValid.required('URL')]"
                      ></v-text-field>
                    </td>
                  </tr>
                  <tr>
                    <th>팔로워<span class="bul">*</span></th>
                    <td>
                      <v-text-field
                        v-model="form.formValue8"
                        class="custom-input mini"
                        placeholder="팔로워 및 구독자수를 입력해주세요"
                        :rules="[useValid.required('팔로워')]"
                      ></v-text-field>
                    </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-if="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="fnRegCheck"
            ><i class="ico"></i>저장</v-btn
          >
          <v-btn v-else class="custom-btn btn-blue2" @click="fnRegCheck"
            ><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("CURATION");

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 customToolbar = ref([["image"]]); // 에디터에서 이미지 첨부만 가능하게끔
const imgTemp = ref(null);
const rowId = ref();
const form = ref({
  formValue0: "KR",
  formValue1: "",
  formValue2: "Y",
  // formValue3: "",
  formValue4: "",
  formValue5: "",
  formValue6: "",
  formValue7: null,
  formValue8: "",
  formValue9: "",
  // fileResponse: null,
});
const fileUpload = ref(null);
const uploadFiles = ref([
  {
    file_name: "",
    ogn_name: "",
  },
]);

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

const pageType = ref("");
const apiUrl = ref("");
apiUrl.value = import.meta.env.VITE_APP_API_URL;
const objProc = ref({
  validErrorMessage: "",
});

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

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

/*======================================================================
|    작성 시퀀스
| 1. 작성 컨펌
| 2. 버튼 체크
| 3. 등록시 -> 등록 API 호출
======================================================================*/
const fnRegCheck = async () => {
  //BASE64에서 실제 파일서버에 파일 전성후 내용 컨텐츠 REAL주소로 변경
  await editorContent();

  nextTick(() => {
    if (addForm.value && typeof addForm.value.validate === "function") {
      addForm.value
        .validate()
        .then((isValid) => {
          if (
            isValid.valid &&
            form.value.formValue7 != null &&
            updatedContent.value != undefined &&
            updatedContent.value != "<p><br></p>" &&
            updatedContent.value != 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 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 fnInsert = () => {
  let frm = new FormData();
  let wterGet = localStorage.getItem("tempAccess");
  let params = JSON.stringify({
    seq: "",
    url_link: form.value.formValue5,
    fol_cnt: Number(form.value.formValue8),
    wter: wterGet,
    brd_cd: "BR03",
    brd_lang: "KR",
    title: form.value.formValue1,
    show_yn: form.value.formValue2,
    content: updatedContent.value,
    ul_type: form.value.formValue9,
    fix_yn: "N",
  });

  frm.append("params", params);
  frm.append("picObj", form.value.formValue7);

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

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 fnUpdate = () => {
  let frm = new FormData();
  let wterGet = localStorage.getItem("tempAccess");
  let params = JSON.stringify({
    seq: useDtStore.boardInfo.seq,
    url_link: form.value.formValue5,
    fol_cnt: Number(form.value.formValue8),
    wter: wterGet,
    brd_cd: "BR03",
    brd_lang: "KR",
    title: form.value.formValue1,
    show_yn: form.value.formValue2,
    content: updatedContent.value,
    ul_type: form.value.formValue9,
    fix_yn: "N",
  });

  frm.append("params", params);
  frm.append("picObj", form.value.formValue7);

  useAxios()
    .post("/brd/upd", frm, { headers: { "Content-Type": "multipart/form-data" } })
    .then((res) => {
      router.push("/view/media/curationList");
    })
    .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: "BR03",
    seq: useDtStore.boardInfo.seq,
    wter: wterGet,
  };

  useAxios()
    .post("/brd/del", req)
    .then((res) => {
      router.push("/view/media/curationList");
    })
    .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) => {
      form.value.formValue0 = res.data.brd_lang;
      form.value.formValue1 = res.data.title;
      form.value.formValue2 = res.data.show_yn;

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

      form.value.formValue5 = res.data.url_link;
      form.value.formValue8 = res.data.fol_cnt;
      form.value.formValue9 = res.data.ul_type;
      form.value.formValue7 = res.data.file_title_pic;
      uploadPicFiles.value[0].file_name = res.data.file_title_pic;
      uploadPicFiles.value[0].ogn_name = res.data.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);
    });
};

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

const fnUploadPicFileCheck = () => {
  if (form.value.formValue7) {
    // 10Mb 이상은 업로드 불가
    if (form.value.formValue7.size > 10 * 1024 * 1024) {
      fnOpenCommPop("10mb 이상은 업로드가 불가합니다.");
      form.value.formValue7 = null;
      return;
    }
    // 이미지 파일 형식 체크
    let extension = form.value.formValue7.name.split(".").pop().toLowerCase();
    if (
      extension != "jpg" &&
      extension != "jpeg" &&
      extension != "png" &&
      extension != "gif"
    ) {
      fnOpenCommPop("파일 형식 또는 확장자가 올바르지 않습니다.");
      form.value.formValue7 = null;
      return;
    }

    objProc.validErrorMessage = "";

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

    previewImage.src = tempImageUrl;
    items.value[0] = tempImageUrl;
    imgTemp.value = tempImageUrl;
  }
};
const clearFile = () => {
  form.value.formValue7 = null;
};
const fnOpenCommPop = (__TEXT) => {
  let param = {
    id: pageId,
    title: "알림",
    content: __TEXT,
    yes: {
      text: "확인",
      isProc: false,
    },
    no: {
      text: "취소",
      isProc: false,
    },
  };
  $eventBus.emit("OPEN_CONFIRM_POP_UP", param);
};

/*=======================================================================
| 최종 에디터 이미지 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_DELETE");
$eventBus.on("FN_DELETE", () => {
  fnDelete();
});

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

$eventBus.off("FN_CONFIRM");
$eventBus.on("FN_CONFIRM");

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

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