<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'">IR 등록</h3>
          <h3 v-else>IR 수정</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-text-field
                        v-model="form.formValue1"
                        class="custom-input mini"
                        placeholder="제목을 입력해주세요."
                        :rules="[useValid.required('제목')]"
                      ></v-text-field>
                    </td>
                  </tr>
                  <tr>
                    <th>노출여부</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-text-field
                        v-model="form.formValue7"
                        style="max-width: 400px"
                        class="custom-input mini"
                        placeholder="공고날짜를 입력해주세요. 예) 2024.12.25"
                        :rules="[useValid.required('날짜')]"
                      ></v-text-field>
                    </td>
                  </tr>

                  <tr>
                    <th>다운로드용 문서<span class="bul">*</span></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 align-start 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"
                          :rules="[useValid.requiredFile(form.formValue6)]"
                          @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-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="fnUpdEvt"
            ><i class="ico"></i>수정</v-btn
          >
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import useAxios from "@/composables/useAxios";
import useValid from "@/composables/useValid";

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

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

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

const index = ref(null);
const imageIndex = ref(0);
const items = ref([]);
const quillEditor = ref(null);
const imgTemp = ref(null);
const rowId = ref();
const addForm = ref(null);
const form = ref({
  formValue0: "KR",
  formValue1: "",
  formValue2: "Y",
  formValue3: "",
  formValue4: null,
  formValue5: "",
  formValue6: null,
  formValue7: "",
  fileResponse: null,
});

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

const pageType = ref("");

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

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

const editorOptions = ref({
  modules: {
    toolbar: {
      handlers: {
        image: () => {
          // DOM 요소로 input[type="file"]을 생성하여 이미지 파일을 선택하게 한다.
          const input = document.createElement("input");
          input.setAttribute("type", "file");
          input.setAttribute("accept", "image/*");
          input.click(); // 파일 선택 창 열기

          input.onchange = async () => {
            const file = input.files[0];
            if (file) {
              const formDataEdt = new FormData();
              formDataEdt.append("fileObj", file);

              try {
                // const response = await this.$api.post("/file/upload", formDataEdt, {
                //   headers: { "Content-Type": "multipart/form-data" },
                // }); // 서버에 이미지 업로드
                const response = useAxios()
                  .post("/file/upload", formDataEdt, {
                    headers: { "Content-Type": "multipart/form-data" },
                  })
                  .then((res) => {})
                  .catch((error) => {
                    //$log.debug("[equipMgmtReg][fnGetTenantList][error]");
                    //useErrorHandler().fnSetCommErrorHandle(error, fnGetTenantList);
                  })
                  .finally(() => {
                    //$log.debug("[equipMgmtReg][fnGetTenantList][finished]");
                    //objSlt.value.tenantNameList = _cloneDeep(temp);
                  });
                const quill = this.$refs.quillEditor.quill;
                const range = quill.getSelection(); // 현재 커서 위치 가져오기

                const fileData = response.data.list; // 예: { "ic_army.png": "20241010183735636" }
                const fileName = Object.keys(fileData)[0]; // 파일 이름 (예: "ic_army.png")
                const fileId = fileData[fileName]; // ID (예: "20241010183735636")

                quill.insertEmbed(
                  range.index,
                  "image",
                  process.env.API_URL + "/file/download/" + fileId
                );
              } catch (error) {
                console.error("Image upload failed:", error);
              }
            }
          };
        },
      },
    },
  },
});

/**
 * 첨부파일 다운로드
 */
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 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 fnOpenCommPop = (__TEXT) => {
  let param = {
    id: pageId,
    title: "알림",
    content: __TEXT,
    yes: {
      text: "확인",
      isProc: false,
    },
    no: {
      text: "취소",
      isProc: false,
    },
  };
  $eventBus.emit("OPEN_CONFIRM_POP_UP", param);
};

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

const fnRegCheck = () => {
  nextTick(() => {
    if (addForm.value && typeof addForm.value.validate === "function") {
      addForm.value
        .validate()
        .then((isValid) => {
          if (isValid.valid) {
            fnRegEvt();
          } 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 = () => {
  // 공고날짜 체크
  const datePattern = /^\d{4}\.\d{2}\.\d{2}$/;
  if (!datePattern.test(form.value.formValue7)) {
    let param = {
      id: pageId,
      title: "공고사항",
      content: "날짜를 올바른 형식(YYYY.MM.DD)으로 입력해주세요",
      yes: {
        text: "확인",
        isProc: false,
      },
      no: {
        text: "취소",
        isProc: false,
      },
    };
    $eventBus.emit("OPEN_CONFIRM_POP_UP", param);
    return false;
  } else {
    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({
    wter: wterGet,
    brd_cd: "BR02",
    brd_lang: form.value.formValue0,
    show_yn: form.value.formValue2,
    title: form.value.formValue1,
    cmd_date: form.value.formValue7,
  });

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

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

const fnUpdEvt = () => {
  // 제목 필수체크
  if(!form.value.formValue1){
    let param = {
      id: pageId,
      title: "공고사항",
      content: "제목을 입력해주세요.",
      yes: {
        text: "확인",
        isProc: false,
      },
      no: {
        text: "취소",
        isProc: false,
      },
    };
    $eventBus.emit("OPEN_CONFIRM_POP_UP", param);
    return false;
  }
  // 공고날짜 체크
  const datePattern = /^\d{4}\.\d{2}\.\d{2}$/;
  if (!datePattern.test(form.value.formValue7)) {
    let param = {
      id: pageId,
      title: "공고사항",
      content: "날짜를 올바른 형식(YYYY.MM.DD)으로 입력해주세요",
      yes: {
        text: "확인",
        isProc: false,
      },
      no: {
        text: "취소",
        isProc: false,
      },
    };
    $eventBus.emit("OPEN_CONFIRM_POP_UP", param);
    return false;
  } else {
    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,
    wter: wterGet,
    brd_cd: "BR02",
    brd_lang: form.value.formValue0,
    show_yn: form.value.formValue2,
    title: form.value.formValue1,
    cmd_date: form.value.formValue7,
  });

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

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

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

const fnDetail = () => {
  //console.log(useDtStore.boardInfo.seq);
  let req = {
    seq: useDtStore.boardInfo.seq,
  };
  useAxios()
    .post("/brd/detail", req)
    .then((res) => {
      console.log(res);
      form.value.formValue0 = res.data.brd_lang;
      form.value.formValue2 = res.data.show_yn;
      form.value.formValue1 = res.data.title;
      form.value.formValue3 = res.data.fix_yn;
      form.value.formValue7 = res.data.cmd_date;
      //if(result.files) this.uploadFiles = result.files

      uploadFiles.value[0].file_name = res.data.file_title;
      uploadFiles.value[0].ogn_name = res.data.ogn_f_title;
    })
    .catch((error) => {
      //$log.debug("[equipMgmtReg][fnGetTenantList][error]");
      //useErrorHandler().fnSetCommErrorHandle(error, fnGetTenantList);
    })
    .finally(() => {
      //$log.debug("[equipMgmtReg][fnGetTenantList][finished]");
      //objSlt.value.tenantNameList = _cloneDeep(temp);
    });
};

const validateDate = () => {};

/************************************************************************
|    팝업 이벤트버스 정의
************************************************************************/
$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
************************************************************************/
const observer = new MutationObserver((mutations) => {
  mutations.forEach((mutation) => {
    if (mutation.type === "childList") {
      if (quillEditor.value) {
        const quill = quillEditor.value.quill;
        if (quill) {
          quill
            .getModule("toolbar")
            .addHandler("image", editorOptions.value.modules.toolbar.handlers.image);
        }
      }
    }
  });
});
observer.observe(document.body, { childList: true, subtree: true });
</script>
