<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-group group--2">
              <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>
                    {{ contact_inf_nickName || "닉네임 없음" }} ({{ contact_inf_name || "이름 없음" }})
                  </div>
                </div>
              </div>
              <div class="form-field">
                <label class="field-label">연락처</label>
                <div class="field-content">
                  <div  class="display-value date-range">
                    <i class="mdi mdi-phone"></i>
                    {{ contact_inf_phone || "연락처 없음" }}
                  </div>
                </div>
              </div>
            </div>

            <div class="form-field">
              <div class="field-content">
                <div class="btn--actions--wrap pb--rem">
                  <div class="left--sections">
                    <label class="mb--0 field-label">공동구매 주문 내역</label>
                  </div>
                </div>
                <div class="tbl-wrapper">
                  <div class="tbl-wrap">
                    <!-- ag grid -->
                    <ag-grid-vue
                      :style="{ width: '100%', height: gridHeight }"
                      class="ag-theme-quartz order--table"
                      :gridOptions="gridOptions"
                      rowSelection="multiple"
                      :rowData="tblItems"
                      :paginationPageSize="pageObj.pageSize"
                      :suppressPaginationPanel="true"
                      @grid-ready="onGridReady"
                    >
                    </ag-grid-vue>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </v-form>
      </div>

      <!-- 액션 버튼 -->
      <div class="action-buttons">
        <div class="button-group left">
          <v-btn
            class="action-btn secondary"
            variant="outlined"
            @click="fnBtnEvt()"
          >
            <i class="mdi mdi-format-list-bulleted"></i>
            목록으로
          </v-btn>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import useAxios from "@/composables/useAxios";
import "@vuepic/vue-datepicker/dist/main.css";
import { AgGridVue } from "ag-grid-vue3";
/************************************************************************
|    레이아웃
************************************************************************/
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("");
let pageObj = ref({
  page: 1, // 현재 페이지
  pageMaxNumSize: 10, // 페이지 숫자 최대 표현 개수
  pageSize: 10, // 테이블 조회 데이터 개수
  totalCnt: 0, // 전체 페이지
});
const apiUrl = ref("");
apiUrl.value = import.meta.env.VITE_APP_API_URL;
const contact_inf_nickName = ref("");
const contact_inf_name = ref("");
const contact_inf_phone = ref("");

const pageType = ref("");

// ag-grid 관련 변수
const tblItems = ref([]);
const gridApi = ref(null);
const gridOptions = ref({
  columnDefs: [
    {
      headerName: "No",
      valueGetter: (params) => params.api.getDisplayedRowCount() - params.node.rowIndex,
      sortable: false,
      filter: false,
      width: 10,
    },
    {
      headerName: "제품명",
      field: "NAME",
    },
    {
      headerName: "주문 건수",
      field: "ORDER_COUNT",
      width: 10,
      valueFormatter: (params) => {
        return params.value ? Number(params.value).toLocaleString() : '0';
      }
    },
    {
      headerName: "공동구매 기간",
      field: "ORDER_START_DATE",
      width: 60,
      valueFormatter: (params) => {
        const startDate = params.data.ORDER_START_DATE ? params.data.ORDER_START_DATE.slice(0, 10) : '';
        const endDate = params.data.ORDER_END_DATE ? params.data.ORDER_END_DATE.slice(0, 10) : '';
        return startDate && endDate ? `${startDate} ~ ${endDate}` : '';
      }
    },
  ],
  autoSizeStrategy: {
    type: "fitGridWidth", // width맞춤
  },
  suppressHorizontalScroll: true, // 가로 스크롤 제거
  defaultColDef: {
    sortable: false,
    filter: false,
    resizable: false,
  },
  suppressMovableColumns: true,
  suppressPaginationPanel: true, // 하단 default 페이징 컨트롤 숨김
  localeText: {
    noRowsToShow: '공동구매 주문 내역이 없습니다.'
  }
});

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

 // 동적 높이 계산
const gridHeight = computed(() => {
  const rowCount = tblItems.value.length;
  const minRows = 8; // 최소 5줄 높이
  const maxRows = 10; // 최대 15줄 높이 (스크롤 시작점)
  const rowHeight = 2.94; // rem 단위
  
  if (rowCount <= minRows) {
    return `calc(${minRows} * ${rowHeight}rem)`;
  } else if (rowCount > maxRows) {
    return `calc(${maxRows} * ${rowHeight}rem)`;
  } else {
    return `calc(${rowCount} * ${rowHeight}rem)`;
  }
});

// 인플루언서 이름 조회
const getInfName = async () => {
  try {
    const response = await useAxios().get(`/user/getInfName/${useDtStore.boardInfo.seq}`);

    contact_inf_nickName.value = response.data.data.NICK_NAME;
    contact_inf_name.value = response.data.data.NAME;
    contact_inf_phone.value = response.data.data.PHONE;

  } catch (error) {
    return null;
  }
};

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

const fnBtnEvt = () => {
  router.push({
      path: "/view/common/dashboard/contact",
    });
};

// ag-grid 관련 함수들
const onGridReady = (params) => {
  gridApi.value = params.api;
};

const fnDetail = async () => {
  let _req = {
    // Y : 노출, N : 비노출
    SHOW_YN: "Y",
    TYPE: "G",
    CONTACT_INF: useDtStore.boardInfo.seq,
    MEMBER_TYPE: memberType,
    MEMBER_SEQ: useAtStore.auth.seq,
    COMPANY_NUMBER: useAtStore.auth.companyNumber || "1"
  };
  
  await useAxios()
  .post("/dashboard/influencerOrderDetail", _req)
  .then((res) => {
      //console.error(res.data.data)
      tblItems.value = res.data.data;
    });
};

/************************************************************************
|    라이프사이클
************************************************************************/
onMounted(() => {
  pageId.value = "인플루언서 상세"
  fnDetail();
  getInfName();
});

</script>