<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="data--list--wrap">
      <div class="table--wrap">
        <v-form ref="addForm">
          <table>
            <colgroup>
              <col width="20%" />
              <col width="80%" />
            </colgroup>
            <tbody>
              <tr>
                <th class="bg le">제품명<span v-if="pageType !== 'D'" class="bul">*</span></th>
                <td v-if="pageType == 'D'">
                  {{ form.formValue1 }}
                </td>
                <td v-else>
                  <div class="input--wrap">
                      <v-text-field
                      maxlength="50"
                      v-model="form.formValue1"
                      :rules="[useValid.required('제품명')]"
                      class="custom-input mini left"
                      placeholder="제품명을 입력하세요"
                    ></v-text-field>
                  </div>
                </td>
              </tr>
              <tr>
                <th class="bg le">공급가<span v-if="pageType !== 'D'" class="bul">*</span></th>
                  <td v-if="pageType == 'D'">
                    {{ Number(form.formValue2).toLocaleString() }}
                  </td>
                  <td v-else>
                  <div class="input--wrap">
                      <v-text-field
                      maxlength="50"
                      v-model="form.formValue2"
                      style="width: 20%"
                      :rules="[useValid.required('공급가')]"
                      class="custom-input mini left"
                      placeholder="공급가를 입력하세요"
                    ></v-text-field>
                  </div>
                </td>
              </tr>
              <tr>
                <th class="bg le">판매가<span v-if="pageType !== 'D'" class="bul">*</span></th>
                <td v-if="pageType == 'D'">
                  {{ Number(form.formValue3).toLocaleString() }}
                </td>
                <td v-else>
                  <div class="input--wrap">
                      <v-text-field
                      maxlength="50"
                      v-model="form.formValue3"
                      style="width: 20%"
                      :rules="[useValid.required('판매가')]"
                      class="custom-input mini left"
                      placeholder="판매가를 입력하세요"
                    ></v-text-field>
                  </div>
                </td>
              </tr>
              <tr>
                <th class="bg le">배송비<span v-if="pageType !== 'D'" class="bul">*</span></th>
                <td v-if="pageType == 'D'">
                  {{ form.formValue4 }}
                </td>
                <td v-else>
                  <div class="input--wrap">
                    <v-textarea
                    v-model="form.formValue4"
                    class="custom-textarea"
                    no-resize=""
                    placeholder="배송비를 입력해주세요"
                    :rules="[useValid.required('배송비')]"
                    ></v-textarea>
                  </div>
                </td>
              </tr>
              <tr>
                <th class="bg le">썸네일 이미지</th>
                <td>
                  <div class="equip--image--wrap">
                    <!--이미지가 없을 때-->
                    <div class="equip--image" v-show="!form.formValue5">
                      <img src="/assets/img/ic_no_img.svg" />
                    </div>
                    <!--이미지 첨부했을 때-->
                    <div class="equip--image" v-show="form.formValue5">
                      <div class="images-wrapper">
                        <img id="preview_image" :src="imgTemp" />
                      </div>
                    </div>
                    <div class="equip--image--select" v-if="pageType !== 'D'">
                      <div class="form--group">
                        <label
                          for="fileUpload_pic"
                          class="file--btn"
                          @click="fnPicFileUploadOpen()"
                          >파일 선택</label
                        >
                        <v-file-input
                          v-model="form.formValue5"
                          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">
                        (권장 이미지 : gif, jpg, jpeg, png)
                      </p>
                    </div>
                  </div>
                </td>
              </tr>
              <tr>
                <th class="bg le">소타이틀<span v-if="pageType !== 'D'" class="bul">*</span></th>
                <td v-if="pageType == 'D'">
                  {{ form.formValue6 }}
                </td>
                <td v-else>
                  <div class="input--wrap">
                    <v-text-field
                    v-model="form.formValue6"
                    class="custom-input mini"
                    placeholder="소타이틀을 입력해주세요"
                    :rules="[useValid.required('소타이틀')]"
                    ></v-text-field>
                  </div>
                </td>
              </tr>
              <tr>
                <th class="bg le">상세 다운로드</th>
                <td>
                  <div class="input--wrap" style="width: 50%">
                    <v-file-input
                      v-if="pageType !== 'D'"
                      v-model="form.formValue7"
                      label="파일은 압축(zip)해서 첨부해 주세요."
                      accept=".zip"
                      variant="outlined"
                      hide-details=""
                      density="comfortable"
                    ></v-file-input>
                    <div class="down--file" @click="fnDownloadFile()">
                      <span>{{ zipInfo.original_name }}</span>
                    </div>
                  </div>
                </td>
              </tr>
              <tr>
                <th class="bg le">상세 내용<span v-if="pageType !== 'D'" class="bul">*</span></th>
                <td v-if="pageType == 'D'">
                  <div v-html="editorContentReq"></div>
                </td>
                <td v-else>
                  <SunEditorWrapper
                    ref="sunEditorWrapper"
                    :initialContent="editorContentReq"
                  />
                </td>
              </tr>
              <tr>
                <th class="bg le">상태<span v-if="pageType !== 'D'" class="bul">*</span></th>
                <td v-if="pageType == 'D'">
                  {{ form.formValue8 == '0' ? '판매중' : '품절' }}
                </td>
                <td v-else>
                  <div class="input--wrap" style="width: 20%">
                    <v-select
                      variant="outlined"
                      class="custom-select"
                      v-model="form.formValue8"
                      :items="form.formValue8Arr"
                    >
                    </v-select>
                  </div>
                </td>
              </tr>
              <tr v-if="pageType !== 'D'">
                <th class="bg le">노출 상태<span v-if="pageType !== 'D'" class="bul">*</span></th>
                <td>
                  <div class="input--wrap" style="width: 20%">
                    <v-select
                      variant="outlined"
                      style="width: 20%"
                      class="custom-select"
                      v-model="form.formValue9"
                      :items="form.formValue9Arr"
                    >
                    </v-select>
                  </div>
                </td>
              </tr>
              <tr>
                <th class="bg le">업데이트 내역</th>
                <td v-if="pageType == 'D'">
                  {{ form.formValue10 }}
                </td>
                <td v-else>
                  <div class="input--wrap">
                    <v-textarea
                    v-model="form.formValue10"
                    class="custom-textarea"
                    no-resize=""
                    placeholder="업데이트 내역을 입력해주세요"
                    ></v-textarea>
                  </div>
                </td>
              </tr>
            </tbody>
          </table>
        </v-form>
      </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 !== 'D'" class="custom-btn btn-blue2" @click="fnBtnEvt"
            ><i class="ico"></i>저장</v-btn
          >
        </div>
      </div>
    </div>
  </div>
</template>

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

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

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

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

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("");
const zipInfo = ref({
  file_path: "",
  original_name: ""
})
const rowId = ref();
const form = ref({
  formValue1: "",
  formValue2: "",
  formValue3: "",
  formValue4: "",
  formValue5: null,
  formValue6: "",
  formValue7: null,
  formValue8: "0",
  formValue8Arr: [
    { title: "판매중", value: "0" },
    { title: "품절", value: "1" },
  ],
  formValue9: "Y",
  formValue9Arr: [
    { title: "노출", value: "Y" },
    { title: "비노출", value: "N" },
  ],
  formValue10: "",
});
const apiUrl = ref("");

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

const pageType = ref("");

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

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

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

    objProc.validErrorMessage = "";

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

    //console.log(tempImageUrl);

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

const fnDownloadFile = () => {
  window.location.href = `https://shopdeli.mycafe24.com/item/download/${zipInfo.value.file_path}`;
}

/*======================================================================
|    작성 시퀀스
| 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: pageId,
              content: "필수항목을 입력해주세요.",
              yes: {
                text: "확인",
                isProc: false,
              }
            };
            $eventBus.emit("OPEN_CONFIRM_POP_UP", param);
          }
        })
        .catch((err) => {
        });
    } else {
    }
  });
};

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: pageId,
    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: pageId,
    content: "수정하시겠습니까?",
    yes: {
      text: "확인",
      isProc: true,
      event: "FN_UPDATE",
      param: "",
    },
    no: {
      text: "취소",
      isProc: false,
    },
  };
  $eventBus.emit("OPEN_CONFIRM_POP_UP", param);
};

const fnInsert = async () => {
  const formData = new FormData();
  formData.append('name', form.value.formValue1);
  formData.append('price1', form.value.formValue2);
  formData.append('price2', form.value.formValue3);
  formData.append('deli_fee', form.value.formValue4);
  formData.append('thumb_file', form.value.formValue5);
  formData.append('sub_title', form.value.formValue6);
  formData.append('detail', updatedContent.value);
  formData.append('zip_file', form.value.formValue7);
  formData.append('status', form.value.formValue8);
  formData.append('show_yn', form.value.formValue9);
  formData.append('add_info', form.value.formValue10);
  formData.append('company_number', "1");

  useAxios()
    .post('/item/reg', formData, {
      headers: {'Content-Type': 'multipart/form-data'},
    })
    .then((res) => {
      router.push("/view/common/item");
    })
    .catch((error) => {
    })
    .finally(() => {
    });
};

const fnUpdate = async () => {
  let req = {
    seq: useDtStore.boardInfo.seq,
  };
  const formData = new FormData();

  formData.append('name', form.value.formValue1);
  formData.append('price1', form.value.formValue2);
  formData.append('price2', form.value.formValue3);
  formData.append('deli_fee', form.value.formValue4);
  if (form.value.formValue5 instanceof File) {
    formData.append('thumb_file', form.value.formValue5);
  }
  formData.append('sub_title', form.value.formValue6);
  formData.append('detail', updatedContent.value);
  if (form.value.formValue7 instanceof File) {
    formData.append('zip_file', form.value.formValue7);
  }
  formData.append('status', form.value.formValue8);
  formData.append('show_yn', form.value.formValue9);
  formData.append('add_info', form.value.formValue10);
  formData.append('company_number', "1");

  try {
    const res = await useAxios().post(`/item/update/${req.seq}`, formData, {
      headers: { 'Content-Type': 'multipart/form-data' },
    });
    router.push("/view/common/item");
  } catch (error) {
  }
};

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

const fnDelete = () => {
  let req = {
    seq: useDtStore.boardInfo.seq,
  };

  useAxios()
    .post(`/item/delete/${req.seq}`)
    .then((res) => {
      //router.push("/view/common/item");
    })
    .catch((error) => {
    })
    .finally(() => {
    });
};

const fnDetail = () => {
  let req = {
    seq: useDtStore.boardInfo.seq,
  };
  useAxios()
    .get(`/item/detail/${req.seq}`)
    .then((res) => {
      form.value.formValue1 = res.data.NAME;
      form.value.formValue2 = res.data.PRICE1;
      form.value.formValue3 = res.data.PRICE2;
      form.value.formValue4 = res.data.DELI_FEE;
      form.value.formValue5 = res.data.THUMB_FILE;
      form.value.formValue6 = res.data.SUB_TITLE;
      zipInfo.value.file_path = res.data.ZIP_FILE;
      zipInfo.value.original_name = res.data.ZIP_FILE_ORIGIN;
      //에디터에 컨텐츠 전달
      editorContentReq.value = res.data.DETAIL;
      form.value.formValue8 = res.data.STATUS;
      form.value.formValue9 = res.data.SHOW_YN;
      form.value.formValue10 = res.data.ADD_INFO;
      //썸네일 파일이 있으면 넣어줌
      if(form.value.formValue5){
        imgTemp.value = `https://shopdeli.mycafe24.com/writable/uploads/item/thumb/${form.value.formValue5}`;
      }
    })
    .catch((error) => {
    })
    .finally(() => {
    });
};

/*=======================================================================
| 최종 에디터 이미지 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 == "I"){
    pageId.value = "제품 등록"
  } else if(pageType.value == "U"){
    pageId.value = "제품 수정"
  } else  {
    pageId.value = "제품 상세"
  }

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

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