<template>
  <div class="modern-item-add">
    <!-- 메인 컨텐츠 -->
    <div class="main-content">
      <div class="form-container">
        <v-form ref="addForm" class="modern-form">
          <div class="form-section">
            <h3 class="section-title">
              <i class="mdi mdi-package-variant"></i>
              {{ pageId }}
            </h3>
            
            <!-- 제품명 -->
            <div class="form-field">
              <label class="field-label">
                제품명
              </label>
              <div class="field-content">
                <div class="display-value">
                  {{ form.formValue1 }}
                </div>
              </div>
            </div>
            <div class="form-field">
              <label class="field-label">
                판매 기간
              </label>
              <div class="field-content df--type w--50">
                <div class="display-value date-range">
                  <i class="mdi mdi-calendar-range"></i>
                  {{ form.order_start_date?.slice(0, 10) }} ~ {{ form.order_end_date?.slice(0, 10) }}
                </div>
                <v-btn
                  v-if="form.formValue8 == 0 && memberType !== 'INFLUENCER'"
                  class="closed-btn"
                  color="primary"
                  variant="outlined"
                  @click="fnCloseEvt"
                >
                  <i class="mdi mdi-power"></i>
                  마감
                </v-btn>
              </div>
            </div>

            <!-- 인플루언서 (공동구매인 경우) -->
            <div class="form-field-group group--2" v-if="memberType !== 'INFLUENCER'">
              <div class="form-field">
                <label class="field-label">인플루언서</label>
                <div class="field-content">
                  <div class="display-value date-range">
                    <i class="mdi mdi-account-circle"></i>
                    {{ form.contact_inf_display }}
                  </div>
                </div>
              </div>
              <!-- 브랜드사 (공동구매인 경우) -->
              <div v-if="memberType !== 'BRAND'" class="form-field">
                <label class="field-label">브랜드사</label>
                <div class="field-content">
                  <div class="display-value date-range">
                    <i class="mdi mdi-domain"></i>
                    {{ form.contact_brd_display }}
                  </div>
                </div>
              </div>
            </div>


            <div class="form-field" v-if="form.order_link">
              <label class="field-label">구매 링크</label>
              <div class="field-content">
                <div v-if="pageType == 'D'" class="display-value link-display">
                  <a 
                    :href="form.order_link" 
                    target="_blank" 
                    rel="noopener noreferrer"
                    class="external-link"
                  >
                    <i class="mdi mdi-link"></i>
                    {{ form.order_link }}
                    <i class="mdi mdi-open-in-new"></i>
                  </a>
                </div>
                <v-text-field
                  v-else
                  v-model="form.order_link"
                  class="modern-input"
                  variant="outlined"
                  placeholder="공동구매 링크를 입력하세요"
                  maxlength="200"
                  hide-details="auto"
                ></v-text-field>
              </div>
            </div>
          </div>
        </v-form>
      </div>

      <!-- 액션 버튼 -->
      <div class="action-buttons">
        <div class="button-group left">
          <v-btn
            class="action-btn secondary"
            variant="outlined"
            @click="listLocated"
          >
            <i class="mdi mdi-format-list-bulleted"></i>
            목록으로
          </v-btn>
          <v-btn
            v-if="memberType !== 'INFLUENCER'"
            class="action-btn danger"
            variant="outlined"
            color="error"
            @click="fnDelEvt"
          >
            <i class="mdi mdi-delete"></i>
            삭제
          </v-btn>
        </div>
        <div class="button-group right">
          <v-btn
            v-if="memberType !== 'INFLUENCER'"
            class="action-btn primary"
            color="primary"
            @click="fnBtnEvt"
          >
            <i class="mdi mdi-pencil"></i>
            수정하기
          </v-btn>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import useAxios from "@/composables/useAxios";
import "@vuepic/vue-datepicker/dist/main.css";
/************************************************************************
|    레이아웃
************************************************************************/
definePageMeta({
  layout: "default",
});

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

/************************************************************************
|    전역
 ************************************************************************/
const memberType = useAtStore.auth.memberType;
const { $toast, $log, $dayjs, $eventBus } = useNuxtApp();
const router = useRouter();
const pageId = ref("");
const itemType = useDtStore.boardInfo.itemType;
const datePickerFormat = "yyyy-MM-dd";
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: "",
  contact_inf: "", // 실제 전송될 INFLUENCER_SEQ
  contact_inf_display: "", // 화면에 표시될 이름
  contact_brd: "", // 실제 전송될 contact_brd
  contact_brd_display: "", // 화면에 표시될 브랜드명
  order_link: "",
  order_start_date: "",
  order_end_date: "",
});

// 인플루언서 관련 변수
const influencerModal = ref(false);
const influencerList = ref([]);
const filteredInfluencerList = ref([]);
const selectedInfluencer = ref(null);
const influencerSearchQuery = ref("");
const isSearching = ref(false);

// 브랜드사 관련 변수
const brandModal = ref(false);
const brandList = ref([]);
const filteredBrandList = ref([]);
const selectedBrand = ref(null);
const brandSearchQuery = ref("");
const isBrandSearching = ref(false);

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",
  });
  useDtStore.boardInfo.itemType  = itemType;
};

// 인플루언서 이름 조회
const getInfName = async (contact_inf) => {
  try {
    // contact_inf 값이 있을 때만 API 호출
    if (!contact_inf) {
      return null;
    }

    const response = await useAxios().get(`/user/getInfName/${contact_inf}`);
    
    if (response.data?.status === 'success') {
      return response.data.data;
    } else {
      return null;
    }
  } catch (error) {
    return null;
  }
};

// 브랜드사 조회
const getBrdName = async (contact_brd) => {
  try {
    if (!contact_brd) {
      return null;
    }

    const response = await useAxios().get(`/user/getBrdName/${contact_brd}`);
    
    if (response.data?.status === 'success') {
      return response.data.data;
    } else {
      return null;
    }
  } catch (error) {
    return null;
  }
};

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

const fnBtnEvt = () => {
  //await editorContent();
  router.push({
      path: "/view/common/item/add",
    });
    useDtStore.boardInfo.itemType = itemType;
    useDtStore.boardInfo.pageType = "U";
};

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 fnCloseEvt = () => {
  let param = {
    id: pageId,
    title: pageId,
    content: "마감하시겠습니까?",
    yes: {
      text: "확인",
      isProc: true,
      event: "FN_CLOSE",
      param: "",
    },
    no: {
      text: "취소",
      isProc: false,
    },
  };
  $eventBus.emit("OPEN_CONFIRM_POP_UP", param);
};

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

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

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(async (res) => {
      form.value.formValue1 = res.data.NAME;
      form.value.formValue8 = res.data.STATUS;
      form.value.formValue9 = res.data.SHOW_YN;
      form.value.formValue10 = res.data.ADD_INFO;
      form.value.order_link = res.data.ORDER_LINK;
      form.value.order_start_date = res.data.ORDER_START_DATE;
      form.value.order_end_date = res.data.ORDER_END_DATE;
      form.value.contact_inf = res.data.CONTACT_INF;
      form.value.contact_brd = res.data.CONTACT_BRD;
      
      // contact_inf 값이 있으면 인플루언서 이름 조회
      if (res.data.CONTACT_INF) {
        const infData = await getInfName(res.data.CONTACT_INF);
        if (infData) {
          form.value.contact_inf_display = infData.NICK_NAME 
            ? `${infData.NICK_NAME} (${infData.NAME})`
            : infData.NAME;
        }
      }
      if (res.data.CONTACT_BRD) {
        const brdData = await getBrdName(res.data.CONTACT_BRD);
        if (brdData) {
          form.value.contact_brd_display = brdData.NAME;
        }
      }
    })
    .catch((error) => {
    })
    .finally(() => {
    });
};

/************************************************************************
|    팝업 이벤트버스 정의
************************************************************************/

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

$eventBus.off("FN_CLOSE");
$eventBus.on("FN_CLOSE", () => {
  fnClose();
});

/************************************************************************
|    라이프사이클
************************************************************************/
onMounted(() => {
  pageType.value = "D";
  
  if(pageType.value == "I"){
    if(itemType == "G"){
      pageId.value = "공동구매 등록"
    } else {
      pageId.value = "제품 등록"
    }
  } else if(pageType.value == "U"){
    if(itemType == "G"){
      pageId.value = "공동구매 수정"
    } else {
      pageId.value = "제품 수정"
    }
  } else  {
    if(itemType == "G"){
      pageId.value = "공동구매 상세"
    } else {
      pageId.value = "제품 상세"
    }
  }

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

</script>

<style scoped>
.cursor-pointer {
  cursor: pointer;
}

.cursor-pointer:hover {
  background-color: #f5f5f5;
}

.order-link {
  color: #1976d2;
  text-decoration: none;
  display: inline-flex;
  align-items: center;
  transition: color 0.2s;
}

.order-link:hover {
  color: #1565c0;
  text-decoration: underline;
}

.no-link {
  color: #999;
  font-style: italic;
}
</style>
