<template>
  <div>
    <div class="inner--headers">
      <h2>{{ pageId }}</h2>
      <div class="bread--crumbs--wrap">
        <span>홈</span>
        <span>{{ pageId }}</span>
      </div>
    </div>

    <div class="search--modules type2">
      <div class="search--inner">
        <div class="form--cont--filter">
          <v-select
            v-model="filter"
            :items="filderArr"
            variant="outlined"
            class="custom-select"
          >
          </v-select>
        </div>
        <div class="form--cont--text">
          <v-text-field
            v-model="searchModel"
            class="custom-input mini"
            style="width: 100%"
            placeholder="검색어를 입력하세요"
          ></v-text-field>
        </div>
      </div>
      <div class="search--inner">
        <div class="calendar-wrap ml--0">
          <div class="calendar">
            <VueDatePicker
              :format="datePickerFormat"
              v-model="searchStartDate"
              placeholder="날짜를 선택하세요"
              :auto-apply="true"
              week-start="0"
            ></VueDatePicker>
          </div>
          <span class="text">~</span>
          <div class="calendar">
            <VueDatePicker
              v-model="searchEndDate"
              :format="datePickerFormat"
              placeholder="날짜를 선택하세요"
              :auto-apply="true"
              week-start="0"
            ></VueDatePicker>
          </div>
          <div class="month--selector">
            <v-btn
              v-for="option in dateOptions"
              :key="option.value"
              :class="{ actv: selectedRange === option.value }"
              @click="setDateRange(option.value)"
              elevation="0"
            >
              {{ option.label }}
            </v-btn>
          </div>
        </div>
      </div>
      <v-btn
        class="custom-btn btn-blue mini sch--btn"
        @click="fnSearch(searchModel, filter)"
        >검색</v-btn
      >
    </div>

    <div class="data--list--wrap">
      <div class="btn--actions--wrap">
        <div class="left--sections">
          <v-btn class="custom-btn btn-pink bdrs--10"
            ><i class="ico"></i>개별 배송</v-btn
          >
          <v-btn class="custom-btn bdrs--10 btn-white" @click="deliLocated()"
            ><i class="ico"></i>공동구매 배송</v-btn
          >
        </div>
        <div class="right--sections">
          <div class="status-filter">
            <v-select
              v-model="statusFilter"
              :items="statusOptions"
              variant="outlined"
              class="custom-select mini"
              style="width: 120px; margin-right: 8px;"
              @update:modelValue="applyStatusFilter"
            >
            </v-select>
          </div>
        </div>
      </div>
      <div class="tbl-wrapper">
        <div class="tbl-wrap">
          <!-- ag grid -->
          <ag-grid-vue
            style="width: 100%; height: calc(10 * 2.94rem)"
            class="ag-theme-quartz"
            :gridOptions="gridOptions"
            :rowData="tblItems"
            rowSelection="multiple"
            :paginationPageSize="pageObj.pageSize"
            :suppressPaginationPanel="true"
            @grid-ready="onGridReady"
            @rowClicked="detailLocated"
          >
          </ag-grid-vue>

          <!-- 페이징 -->
          <div class="ag-grid-custom-pagenations">
            <pagination @chg_page="chgPage" :pageObj="pageObj"></pagination>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import VueDatePicker from "@vuepic/vue-datepicker";
import "@vuepic/vue-datepicker/dist/main.css";
import { AgGridVue } from "ag-grid-vue3";
import dayjs from 'dayjs';
import pagination from "../components/common/pagination.vue";
  /************************************************************************
|    레이아웃
************************************************************************/
  definePageMeta({
    layout: "default",
  });
  /************************************************************************
|   PROPS
 ************************************************************************/
  const props = defineProps({
    propsData: {
      type: Object,
      default: () => {},
    },
  });
  /************************************************************************
|    스토어
 ************************************************************************/
  const useDtStore = useDetailStore();
  const useAtStore = useAuthStore();
  /************************************************************************
   |    전역
   ************************************************************************/
  const memberType = useAtStore.auth.memberType;
  const memberSeq = useAtStore.auth.seq;
  const searchModel = ref("");
  const selectedRange = ref('all');
  const itemStartDate = ref("");
  const searchStartDate = ref("");
  const searchEndDate = ref("");
  const datePickerFormat = "yyyy-MM-dd";
  const dateOptions = [
    { label: '오늘', value: 'today' },
    { label: '7일', value: '7d' },
    { label: '1개월', value: '1m' },
    { label: '3개월', value: '3m' },
    { label: '전체', value: 'all' },
  ]
  const filter = ref("");
  const filderArr = ref([
    { title: "전체", value: "" },
    { title: "제품명", value: "name" },
  ]);
  const statusFilter = ref("ALL");
  const statusOptions = ref([
    { title: "전체", value: "ALL" },
    { title: "신규", value: "NEW" },
    { title: "대기", value: "PENDING" },
    { title: "완료", value: "COMPLETE" }
  ]);
  const originalTblItems = ref([]); // 원본 데이터 저장용
  const { $toast, $log, $dayjs, $eventBus } = useNuxtApp();
  const router = useRouter();
  const pageId = ref("배송 관리");
  let pageObj = ref({
    page: 1, // 현재 페이지
    pageMaxNumSize: 10, // 페이지 숫자 최대 표현 개수
    pageSize: 10, // 테이블 조회 데이터 개수
    totalCnt: 0, // 전체 페이지
  });
  const tblItems = ref([]); // stat 데이터

  /* eslint-disable */
  /* prettier-ignore */

  pageObj.value.totalCnt = tblItems.value.length;

  const remToPx = () => parseFloat(getComputedStyle(document.documentElement).fontSize);
  const rowHeightRem = 2.65; // 원하는 rem 값
  const rowHeightPx = rowHeightRem * remToPx();
  const gridApi = shallowRef();

  // gridOption
  const gridOptions = {
    columnDefs: [
      //{ checkboxSelection: true, headerCheckboxSelection: true, width: 0 },
      {
        headerName: "No",
        valueGetter: (params) => params.api.getDisplayedRowCount() - params.node.rowIndex,
        sortable: false,
        width: 70,
      },
      // { headerName: "번호", field: "NO", sortable: false },
      {
        headerName: "제품명",
        field: "NAME",
        //sortable: useAuthStore().getCompanyId == "0-000000" ? true : false,
        cellRenderer: (params) => {
          const status = params.data.status || 'NEW';
          const productName = params.value || '';
          const isVendor = memberType !== 'INFLUENCER';
          
          if (isVendor && status === 'NEW') {
            return `
              <div style="display: flex; align-items: center; gap: 8px; justify-content: space-between; width: 100%;">
                <span style="flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">${productName}</span>
                <span class="custom-new-badge" style="
                  background: #f44336 !important;
                  color: white;
                  font-size: 10px;
                  padding: 2px 6px;
                  border-radius: 12px;
                  min-width: 30px;
                  height: 18px;
                  display: inline-flex;
                  align-items: center;
                  justify-content: center;
                  font-weight: bold;
                  flex-shrink: 0;
                ">NEW</span>
              </div>
            `;
          }
          return productName;
        }
      },
      {
        headerName: "제품 총수량",
        field: "sum_qty",
        width: 140,
        cellRenderer: (params) => {
          return Number(params.value).toLocaleString();
        },
      },
      {
        headerName: "총 주문금액",
        field: "sum_total",
        width: 140,
        cellRenderer: (params) => {
          return Number(params.value).toLocaleString();
        },
      },
      {
        headerName: "주문일",
        field: "latest_reg_date",
        width: 140,
      },
      {
        headerName: "상태",
        field: "status",
        width: 120,
        cellRenderer: (params) => {
          const status = params.value || 'NEW';
          const statusMap = {
            'NEW': { text: '신규', color: 'primary', variant: 'elevated' },
            'PENDING': { text: '대기', color: 'warning', variant: 'elevated' },
            'COMPLETE': { text: '완료', color: 'success', variant: 'elevated' }
          };
          const config = statusMap[status] || statusMap['NEW'];
          
          return `<span class="v-chip v-chip--density-default v-chip--size-default v-chip--variant-${config.variant} bg-${config.color}" style="font-size: 12px; padding: 4px 8px;">${config.text}</span>`;
        }
      },
    ],
    rowData: tblItems.value, // 테이블 데이터
    autoSizeStrategy: {
      type: "fitGridWidth", // width맞춤
    },
    suppressMovableColumns: true,
    headerHeight: rowHeightPx,
    rowHeight: rowHeightPx,
    pagination: true,
    suppressPaginationPanel: true, // 하단 default 페이징 컨트롤 숨김
    //rowSelection: {
    // checkboxes: true,
    // headerCheckbox: true,
    // enableClickSelection: false,
    // mode: "multiRow",
    //},
  };

  /************************************************************************
|    함수(METHODS)
************************************************************************/
  const deliLocated = () => {
    router.push({
      path: "/view/common/deli/index2",
    });
  };

  const setDateRange = (range) => {
    const today = dayjs();

    switch(range) {
      case 'today' :
        searchStartDate.value = today.format('YYYY-MM-DD');
        searchEndDate.value = today.format('YYYY-MM-DD');
        selectedRange.value = 'today';
        break;
      case '7d':
        searchStartDate.value = today.subtract(7, 'day').format('YYYY-MM-DD');
        searchEndDate.value = today.format('YYYY-MM-DD');
        selectedRange.value = '7d';
        break;
      case '1m':
        searchStartDate.value = today.subtract(1, 'month').format('YYYY-MM-DD');
        searchEndDate.value = today.format('YYYY-MM-DD');
        selectedRange.value = '1m';
        break;
      case '3m':
        searchStartDate.value = today.subtract(3, 'month').format('YYYY-MM-DD');
        searchEndDate.value = today.format('YYYY-MM-DD');
        selectedRange.value = '3m';
        break;
      case 'all':
        searchStartDate.value = itemStartDate.value;
        searchEndDate.value = today.format('YYYY-MM-DD');
        selectedRange.value = 'all';
        break
    }
  }

  const onGridReady = (__PARAMS) => {
    gridApi.value = __PARAMS.api;
  };

  const chgPage = (__PAGE) => {
    pageObj.value.page = __PAGE;
    gridApi.value.paginationGoToPage(__PAGE - 1);
  };

  const detailLocated = (__EVENT) => {
    router.push({
      path: "/view/common/deli/detail",
    });
    useDtStore.boardInfo.seq = __EVENT.data.SEQ;
  };

  const itemListGet = async () => {
    let _req = {
      MEMBER_TYPE: memberType,
      TYPE: "E"
    };

    if (memberType === "INFLUENCER") {
      _req.INF_SEQ = memberSeq;
    } else if (memberType === "VENDOR") {
      _req.COMPANY_NUMBER = useAtStore.auth.companyNumber || "1";
    }

    useAxios()
      .post("/deli/itemlist", _req)
      .then((res) => {
        originalTblItems.value = res.data;
        applyStatusFilter();

        if (res.data.length > 0) {
          itemStartDate.value = res.data[res.data.length-1].UDPDATE;
          searchStartDate.value = itemStartDate.value;
          searchEndDate.value = dayjs();
        }
      });
  };

  const fnSearch = (__KEYWORD, __FILTER) => {
    let _req = {
      filter: __FILTER,
      keyword: __KEYWORD,
      startDate: searchStartDate.value,
      endDate: searchEndDate.value,
    };

    useAxios()
      .post("/item/search", _req)
      .then((res) => {
        originalTblItems.value = res.data;
        applyStatusFilter();
      })
      .catch((error) => {});
  };

  const applyStatusFilter = () => {
    let filteredData = originalTblItems.value;
    
    if (statusFilter.value !== "ALL") {
      filteredData = originalTblItems.value.filter(item => {
        const itemStatus = item.status || 'NEW';
        return itemStatus === statusFilter.value;
      });
    }
    
    tblItems.value = filteredData;
    pageObj.value.totalCnt = tblItems.value.length;
    
    // ag-grid 데이터 갱신
    if (gridApi.value) {
      gridApi.value.setGridOption('rowData', tblItems.value);
    }
  };
  /************************************************************************
|    팝업 이벤트버스 정의
************************************************************************/
  /************************************************************************
|    WATCH
************************************************************************/

  watch(
    () => props,
    () => {
      searchObj.value = props.propsData;
      fnGetStat();
    },
    { deep: true }
  );

  onMounted(() => {
    itemListGet();
    
    // 업로드 상태 확인 및 사용자 피드백
    const route = useRoute();
    if (route.query.uploadStatus === 'success') {
      const recordCount = route.query.recordCount || '0';
      const itemId = route.query.itemId;
      
      $toast.success(`송장 정보가 성공적으로 등록되었습니다. (${recordCount}건)`);
      
      // URL에서 쿼리 파라미터 제거
      router.replace({ path: '/view/common/deli' });
    }

    // 실시간 이벤트 리스너 등록
    $eventBus.on('DELIVERY_STATUS_CHANGED', handleDeliveryStatusChange);
    $eventBus.on('NEW_ORDER_RECEIVED', handleNewOrderReceived);
  });

  onUnmounted(() => {
    // 이벤트 리스너 제거
    $eventBus.off('DELIVERY_STATUS_CHANGED', handleDeliveryStatusChange);
    $eventBus.off('NEW_ORDER_RECEIVED', handleNewOrderReceived);
  });

  const handleDeliveryStatusChange = (data) => {
    // 해당 아이템의 상태 업데이트
    const itemIndex = originalTblItems.value.findIndex(item => item.SEQ == data.itemId);
    if (itemIndex !== -1) {
      originalTblItems.value[itemIndex].status = data.status;
      
      // 필터 재적용
      applyStatusFilter();
      
      console.log('배송 상태 업데이트됨:', data);
    }
  };

  const handleNewOrderReceived = (data) => {
    // 새 주문 데이터를 리스트에 추가
    const newOrder = {
      SEQ: data.itemId,
      NAME: data.itemName,
      sum_qty: data.totalQty || 0,
      sum_total: data.totalAmount || 0,
      latest_reg_date: data.orderDate,
      status: 'NEW'
    };
    
    originalTblItems.value.unshift(newOrder);
    applyStatusFilter();
    
    console.log('새 주문 추가됨:', data);
  };
</script>

<style scoped>
.status-filter {
  display: flex;
  align-items: center;
}

.btn--actions--wrap .right--sections {
  display: flex;
  align-items: center;
}
</style>
