<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>
      </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 
            v-if="memberType === 'VENDOR'"
            class="custom-btn btn-blue mini"
            @click="markAsDelivered"
            :disabled="selectedItems.length === 0"
          >
            <i class="ico"></i>배송완료 처리
          </v-btn>
        </div>
        <div class="right--sections">
          <span class="total-count">총 {{ tblItems.length }}건</span>
        </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="memberType === 'VENDOR' ? 'multiple' : 'single'"
            :paginationPageSize="pageObj.pageSize"
            :suppressPaginationPanel="true"
            @grid-ready="onGridReady"
            @selection-changed="onSelectionChanged"
          >
          </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",
});

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 searchStartDate = ref("");
const searchEndDate = ref("");
const datePickerFormat = "yyyy-MM-dd";
const filter = ref("");
const filderArr = ref([
  { title: "전체", value: "" },
  { title: "제품명", value: "name" },
  { title: "구매자명", value: "buyer" },
]);
const selectedItems = 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([]);

const remToPx = () => parseFloat(getComputedStyle(document.documentElement).fontSize);
const rowHeightRem = 2.65;
const rowHeightPx = rowHeightRem * remToPx();
const gridApi = shallowRef();

// gridOption
const gridOptions = {
  columnDefs: [
    ...(memberType === 'VENDOR' ? [{ checkboxSelection: true, headerCheckboxSelection: true, width: 50 }] : []),
    {
      headerName: "No",
      valueGetter: (params) => params.api.getDisplayedRowCount() - params.node.rowIndex,
      sortable: false,
      width: 70,
    },
    {
      headerName: "제품명",
      field: "ITEM_NAME",
      width: 200,
    },
    {
      headerName: "구매자명",
      field: "BUYER_NAME",
      width: 120,
    },
    {
      headerName: "연락처",
      field: "PHONE",
      width: 140,
    },
    {
      headerName: "주소",
      field: "ADDRESS",
      width: 250,
    },
    {
      headerName: "수량",
      field: "QTY",
      width: 80,
      cellRenderer: (params) => {
        return Number(params.value).toLocaleString();
      },
    },
    {
      headerName: "금액",
      field: "TOTAL",
      width: 120,
      cellRenderer: (params) => {
        return Number(params.value).toLocaleString() + '원';
      },
    },
    {
      headerName: "배송업체",
      field: "DELI_COMP",
      width: 120,
    },
    {
      headerName: "송장번호",
      field: "DELI_NUMB",
      width: 150,
    },
    {
      headerName: "배송시작일",
      field: "SHIPPING_DATE",
      width: 140,
      cellRenderer: (params) => {
        return params.value ? dayjs(params.value).format('YYYY-MM-DD') : '';
      },
    },
  ],
  rowData: tblItems.value,
  autoSizeStrategy: {
    type: "fitGridWidth",
  },
  suppressMovableColumns: true,
  headerHeight: rowHeightPx,
  rowHeight: rowHeightPx,
  pagination: true,
  suppressPaginationPanel: true,
  ...(memberType === 'VENDOR' ? {
    rowSelection: {
      checkboxes: true,
      headerCheckbox: true,
      enableClickSelection: false,
      mode: "multiRow",
    }
  } : {}),
};

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

const onSelectionChanged = () => {
  if (memberType === 'VENDOR') {
    selectedItems.value = gridApi.value.getSelectedRows();
  }
};

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

const getShippingList = async () => {
  let _req = {
    MEMBER_TYPE: memberType
  };

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

  console.log('배송중 리스트 API 요청:', _req);

  await useAxios()
    .post("/deli/shipping", _req)
    .then((res) => {
      console.log('배송중 리스트 API 응답:', res.data);
      console.log('응답 데이터 개수:', res.data?.length || 0);
      
      tblItems.value = res.data;
      pageObj.value.totalCnt = res.data.length;
      
      // ag-grid 데이터 갱신
      if (gridApi.value) {
        gridApi.value.setGridOption('rowData', tblItems.value);
      }
    })
    .catch((error) => {
      console.error('배송중 리스트 API 오류:', error);
      $toast.error('배송중 리스트를 불러오는 중 오류가 발생했습니다.');
    });
};

const fnSearch = (__KEYWORD, __FILTER) => {
  // 검색 로직 구현
  let filteredData = tblItems.value;
  
  if (__KEYWORD && __KEYWORD.trim() !== '') {
    filteredData = tblItems.value.filter(item => {
      if (__FILTER === 'name') {
        return item.ITEM_NAME && item.ITEM_NAME.toLowerCase().includes(__KEYWORD.toLowerCase());
      } else if (__FILTER === 'buyer') {
        return item.BUYER_NAME && item.BUYER_NAME.toLowerCase().includes(__KEYWORD.toLowerCase());
      } else {
        // 전체 검색
        return (item.ITEM_NAME && item.ITEM_NAME.toLowerCase().includes(__KEYWORD.toLowerCase())) ||
               (item.BUYER_NAME && item.BUYER_NAME.toLowerCase().includes(__KEYWORD.toLowerCase()));
      }
    });
  }
  
  if (gridApi.value) {
    gridApi.value.setGridOption('rowData', filteredData);
  }
};

const markAsDelivered = async () => {
  if (selectedItems.value.length === 0) {
    $toast.error('배송완료 처리할 항목을 선택해주세요.');
    return;
  }

  const orderIds = selectedItems.value.map(item => item.SEQ);
  
  await useAxios()
    .post("/deli/markDelivered", { order_ids: orderIds })
    .then((res) => {
      $toast.success('배송완료 처리되었습니다.');
      getShippingList(); // 리스트 새로고침
      selectedItems.value = []; // 선택 초기화
    })
    .catch((error) => {
      $toast.error('배송완료 처리 중 오류가 발생했습니다.');
    });
};

onMounted(() => {
  getShippingList();
  
  // 날짜 초기화
  const today = dayjs();
  searchStartDate.value = today.subtract(30, 'day').format('YYYY-MM-DD');
  searchEndDate.value = today.format('YYYY-MM-DD');
});
</script>

<style scoped>
.total-count {
  font-size: 14px;
  color: #666;
  margin-left: 10px;
}

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