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

    <!-- 필터링 섹션 -->
    <div class="dashboard--filters">
      <div class="filter--wrap">
        <div class="date--range">
          <VueDatePicker
            v-model="dateRange"
            range
            :format="dateFormat"
            placeholder="기간을 선택하세요"
            :auto-apply="true"
            @update:model-value="onDateRangeChange"
          />
        </div>
        <div class="quick--filters">
          <v-btn
            :class="{ active: selectedPeriod === 'today' }"
            @click="setQuickPeriod('today')"
            size="small"
            elevation="0"
            >오늘</v-btn
          >
          <v-btn
            :class="{ active: selectedPeriod === 'week' }"
            @click="setQuickPeriod('week')"
            size="small"
            elevation="0"
            >7일</v-btn
          >
          <v-btn
            :class="{ active: selectedPeriod === 'month' }"
            @click="setQuickPeriod('month')"
            size="small"
            elevation="0"
            >1개월</v-btn
          >
          <v-btn
            :class="{ active: selectedPeriod === 'quarter' }"
            @click="setQuickPeriod('quarter')"
            size="small"
            elevation="0"
            >3개월</v-btn
          >
        </div>
      </div>
    </div>

    <!-- KPI 카드 섹션 -->
    <div class="dashboard--kpi">
      <div class="kpi--cards">
        <div class="kpi--card">
          <div class="kpi--header">
            <h3>총 매출</h3>
            <i class="icon sales"></i>
          </div>
          <div class="kpi--value">{{ formatCurrency(animatedMetrics.totalSales) }}</div>
          <div
            class="kpi--change"
            :class="{
              positive: metrics.salesChange >= 0,
              negative: metrics.salesChange < 0,
            }"
          >
            {{ metrics.salesChange >= 0 ? "+" : "" }}{{ metrics.salesChange }}% 전월 대비
          </div>
        </div>
        <div class="kpi--card">
          <div class="kpi--header">
            <h3>총 주문</h3>
            <i class="icon orders"></i>
          </div>
          <div class="kpi--value">{{ Math.round(animatedMetrics.totalOrders) }}개</div>
          <div
            class="kpi--change"
            :class="{
              positive: metrics.ordersChange >= 0,
              negative: metrics.ordersChange < 0,
            }"
          >
            {{ metrics.ordersChange >= 0 ? "+" : "" }}{{ metrics.ordersChange }}% 전월
            대비
          </div>
        </div>
        <div class="kpi--card">
          <div class="kpi--header">
            <h3>정산 완료율</h3>
            <i class="icon settlement"></i>
          </div>
          <div class="kpi--value">{{ animatedMetrics.settlementRate.toFixed(1) }}%</div>
          <div
            class="kpi--change"
            :class="{
              positive: metrics.settlementChange >= 0,
              negative: metrics.settlementChange < 0,
            }"
          >
            {{ metrics.settlementChange >= 0 ? "+" : "" }}{{ metrics.settlementChange }}%p
            전월 대비
          </div>
        </div>
        <div class="kpi--card">
          <div class="kpi--header">
            <h3>평균 주문액</h3>
            <i class="icon avg"></i>
          </div>
          <div class="kpi--value">
            {{ formatCurrency(animatedMetrics.avgOrderValue) }}
          </div>
          <div
            class="kpi--change"
            :class="{
              positive: metrics.avgOrderChange >= 0,
              negative: metrics.avgOrderChange < 0,
            }"
          >
            {{ metrics.avgOrderChange >= 0 ? "+" : "" }}{{ metrics.avgOrderChange }}% 전월
            대비
          </div>
        </div>
      </div>
    </div>

    <!-- 차트 섹션 -->
    <div class="dashboard--charts">
      <div class="chart--row">
        <div class="chart--container">
          <div class="chart--header">
            <h3>매출 추이</h3>
            <div class="chart--controls">
              <v-btn-toggle v-model="salesChartType" density="compact">
                <v-btn value="line" size="small">라인</v-btn>
                <v-btn value="bar" size="small">막대</v-btn>
              </v-btn-toggle>
            </div>
          </div>
          <div class="chart--content">
            <canvas ref="salesChart" :key="salesChartKey"></canvas>
          </div>
        </div>
        <div class="chart--container">
          <div class="chart--header">
            <h3>주문 현황</h3>
          </div>
          <div class="chart--content">
            <canvas ref="ordersChart" :key="ordersChartKey"></canvas>
          </div>
        </div>
      </div>
      <div class="chart--row">
        <div class="chart--container">
          <div class="chart--header">
            <h3>정산 현황</h3>
          </div>
          <div class="chart--content">
            <canvas ref="settlementChart" :key="settlementChartKey"></canvas>
          </div>
        </div>
        <div class="chart--container">
          <div class="chart--header">
            <h3>카테고리별 매출</h3>
          </div>
          <div class="chart--content">
            <canvas ref="categoryChart" :key="categoryChartKey"></canvas>
          </div>
        </div>
      </div>
    </div>

    <!-- 신규 주문 내역 (대기중) -->
    <div class="dashboard--table">
      <div class="table--header">
        <h3>신규 주문 내역 (대기중)</h3>
        <v-btn color="warning" size="small" @click="exportPendingData">
          <i class="mdi mdi-download"></i>
          엑셀 다운로드
        </v-btn>
      </div>
      <div class="table--content">
        <div class="tbl-wrapper">
          <div class="tbl-wrap">
            <!-- ag grid -->
            <ag-grid-vue
              style="width: 100%; height: calc(8 * 2.94rem)"
              class="ag-theme-quartz"
              :gridOptions="pendingGridOptions"
              :rowData="pendingOrders"
              :rowSelection="'single'"
              :paginationPageSize="8"
              :suppressPaginationPanel="true"
              @grid-ready="onPendingGridReady"
              @selection-changed="onPendingSelectionChanged"
            >
            </ag-grid-vue>
            <!-- 페이징 -->
            <div class="ag-grid-custom-pagenations">
              <pagination
                @chg_page="chgPendingPage"
                :pageObj="pendingPageObj"
              ></pagination>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 배송중 내역 -->
    <div class="dashboard--table">
      <div class="table--header">
        <h3>배송중 내역</h3>
        <v-btn color="primary" size="small" @click="exportShippingData">
          <i class="mdi mdi-download"></i>
          엑셀 다운로드
        </v-btn>
      </div>
      <div class="table--content">
        <div class="tbl-wrapper">
          <div class="tbl-wrap">
            <!-- ag grid -->
            <ag-grid-vue
              style="width: 100%; height: calc(8 * 2.94rem)"
              class="ag-theme-quartz"
              :gridOptions="shippingGridOptions"
              :rowData="shippingOrders"
              :rowSelection="'single'"
              :paginationPageSize="8"
              :suppressPaginationPanel="true"
              @grid-ready="onShippingGridReady"
              @selection-changed="onShippingSelectionChanged"
            >
            </ag-grid-vue>
            <!-- 페이징 -->
            <div class="ag-grid-custom-pagenations">
              <pagination
                @chg_page="chgShippingPage"
                :pageObj="shippingPageObj"
              ></pagination>
            </div>
          </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 pagination from "../../../components/common/pagination.vue";
  import {
    Chart as ChartJS,
    CategoryScale,
    LinearScale,
    PointElement,
    LineElement,
    BarElement,
    Title,
    Tooltip,
    Legend,
    ArcElement,
    LineController,
    BarController,
    DoughnutController,
    PieController,
  } from "chart.js";

  ChartJS.register(
    CategoryScale,
    LinearScale,
    PointElement,
    LineElement,
    BarElement,
    Title,
    Tooltip,
    Legend,
    ArcElement,
    LineController,
    BarController,
    DoughnutController,
    PieController
  );

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

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

  /************************************************************************
|    전역 변수
 ************************************************************************/
  const { $toast, $log, $dayjs } = useNuxtApp();
  const router = useRouter();
  const pageId = ref("대시보드");
  const dateFormat = "yyyy-MM-dd";
  const loading = ref(false);

  // 필터링 관련
  const dateRange = ref([]);
  const selectedPeriod = ref("month");

  // 차트 관련
  const salesChart = ref(null);
  const ordersChart = ref(null);
  const settlementChart = ref(null);
  const categoryChart = ref(null);
  const salesChartType = ref("line");
  const salesChartKey = ref(0);
  const ordersChartKey = ref(0);
  const settlementChartKey = ref(0);
  const categoryChartKey = ref(0);

  // 차트 인스턴스 저장
  let salesChartInstance = null;
  let ordersChartInstance = null;
  let settlementChartInstance = null;
  let categoryChartInstance = null;

  // 메트릭 데이터 (초기값은 0으로 설정)
  const metrics = ref({
    totalSales: 0,
    salesChange: 0,
    totalOrders: 0,
    ordersChange: 0,
    settlementRate: 0,
    settlementChange: 0,
    avgOrderValue: 0,
    avgOrderChange: 0,
  });

  // 애니메이션용 메트릭 데이터
  const animatedMetrics = ref({
    totalSales: 0,
    totalOrders: 0,
    settlementRate: 0,
    avgOrderValue: 0,
  });

  // ag-grid 관련 - 신규 주문 (대기중)
  const pendingGridApi = ref(null);
  const pendingGridOptions = ref({
    columnDefs: [
      {
        headerName: "주문번호",
        field: "orderNo",
        flex: 1,
        minWidth: 140,
        sortable: true,
        filter: true,
      },
      {
        headerName: "인플루언서",
        field: "influencer",
        flex: 1,
        minWidth: 120,
        sortable: true,
        filter: true,
      },
      {
        headerName: "제품명",
        field: "productName",
        flex: 2,
        minWidth: 200,
        sortable: true,
        filter: true,
      },
      {
        headerName: "주문수량",
        field: "totalQty",
        flex: 1,
        minWidth: 100,
        sortable: true,
        filter: true,
        valueFormatter: (params) => {
          return `${params.value || 0}개`;
        },
      },
      {
        headerName: "주문금액",
        field: "totalAmount",
        flex: 1,
        minWidth: 120,
        sortable: true,
        filter: true,
        valueFormatter: (params) => {
          return new Intl.NumberFormat("ko-KR", {
            style: "currency",
            currency: "KRW",
          }).format(params.value || 0);
        },
      },
      {
        headerName: "주문일",
        field: "latestOrderDate",
        flex: 1,
        minWidth: 120,
        sortable: true,
        filter: true,
      },
      {
        headerName: "상태",
        field: "status",
        flex: 0.8,
        minWidth: 100,
        sortable: true,
        filter: true,
        cellRenderer: () => {
          return `<span class="status-chip status-warning">대기중</span>`;
        },
      },
      {
        headerName: "액션",
        field: "actions",
        flex: 0.6,
        minWidth: 80,
        sortable: false,
        filter: false,
        cellRenderer: () => {
          return '<button class="action-btn">관리</button>';
        },
        onCellClicked: (params) => {
          viewPendingOrder(params.data);
        },
      },
    ],
    defaultColDef: {
      sortable: true,
      filter: true,
      resizable: true,
    },
    pagination: false,
    animateRows: true,
    rowHeight: 40,
    suppressHorizontalScroll: false,
  });

  // 페이징 관련 - 신규 주문
  const pendingPageObj = ref({
    currentPage: 1,
    pageSize: 8,
    totalCnt: 0,
    totalPage: 0,
  });

  const pendingOrders = ref([]);

  // ag-grid 관련 - 배송중
  const shippingGridApi = ref(null);
  const shippingGridOptions = ref({
    columnDefs: [
      {
        headerName: "주문번호",
        field: "orderNo",
        flex: 1,
        minWidth: 140,
        sortable: true,
        filter: true,
      },
      {
        headerName: "인플루언서",
        field: "influencer",
        flex: 1,
        minWidth: 120,
        sortable: true,
        filter: true,
      },
      {
        headerName: "상품명",
        field: "productName",
        flex: 2,
        minWidth: 200,
        sortable: false,
        filter: true,
      },
      {
        headerName: "주문금액",
        field: "amount",
        flex: 1,
        minWidth: 120,
        sortable: true,
        filter: true,
        valueFormatter: (params) => {
          return new Intl.NumberFormat("ko-KR", {
            style: "currency",
            currency: "KRW",
          }).format(params.value || 0);
        },
      },
      {
        headerName: "배송업체",
        field: "deliveryCompany",
        flex: 1,
        minWidth: 120,
        sortable: false,
        filter: true,
      },
      {
        headerName: "송장번호",
        field: "trackingNumber",
        flex: 1,
        minWidth: 140,
        sortable: false,
        filter: true,
      },
      {
        headerName: "주문일",
        field: "orderDate",
        flex: 1,
        minWidth: 120,
        sortable: true,
        filter: true,
      },
      {
        headerName: "상태",
        field: "status",
        flex: 0.8,
        minWidth: 100,
        sortable: true,
        filter: true,
        cellRenderer: () => {
          return `<span class="status-chip status-info">배송중</span>`;
        },
      },
      {
        headerName: "액션",
        field: "actions",
        flex: 0.6,
        minWidth: 80,
        sortable: false,
        filter: false,
        cellRenderer: () => {
          return '<button class="action-btn">보기</button>';
        },
        onCellClicked: (params) => {
          viewShippingOrder(params.data);
        },
      },
    ],
    defaultColDef: {
      sortable: true,
      filter: true,
      resizable: true,
    },
    pagination: false,
    animateRows: true,
    rowHeight: 40,
    suppressHorizontalScroll: false,
  });

  // 페이징 관련 - 배송중
  const shippingPageObj = ref({
    currentPage: 1,
    pageSize: 8,
    totalCnt: 0,
    totalPage: 0,
  });

  const shippingOrders = ref([]);

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

  // 통화 포맷팅
  const formatCurrency = (amount) => {
    return new Intl.NumberFormat("ko-KR", {
      style: "currency",
      currency: "KRW",
    }).format(amount);
  };

  // 카운트업 애니메이션 함수
  const animateCountUp = (target, property, duration = 2000) => {
    const startValue = animatedMetrics.value[property];
    const endValue = target;
    const startTime = Date.now();

    const updateCount = () => {
      const now = Date.now();
      const elapsed = now - startTime;
      const progress = Math.min(elapsed / duration, 1);

      // easeOutQuart 이징 함수 사용
      const easedProgress = 1 - Math.pow(1 - progress, 4);

      const currentValue = startValue + (endValue - startValue) * easedProgress;
      animatedMetrics.value[property] = currentValue;

      if (progress < 1) {
        requestAnimationFrame(updateCount);
      }
    };

    requestAnimationFrame(updateCount);
  };

  // 모든 메트릭 애니메이션 시작
  const startMetricsAnimation = () => {
    animateCountUp(metrics.value.totalSales, "totalSales", 1500); // 금액: 1.5초로 단축
    animateCountUp(metrics.value.totalOrders, "totalOrders", 2000);
    animateCountUp(metrics.value.settlementRate, "settlementRate", 2200);
    animateCountUp(metrics.value.avgOrderValue, "avgOrderValue", 1300); // 평균 주문액: 1.3초로 단축
  };

  // 날짜 범위 변경
  const onDateRangeChange = (range) => {
    selectedPeriod.value = "custom";
    fetchDashboardData();
  };

  // 빠른 기간 선택
  const setQuickPeriod = (period) => {
    selectedPeriod.value = period;
    const today = new Date();

    switch (period) {
      case "today":
        dateRange.value = [today, today];
        break;
      case "week":
        const weekAgo = new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000);
        dateRange.value = [weekAgo, today];
        break;
      case "month":
        const monthAgo = new Date(today.getTime() - 30 * 24 * 60 * 60 * 1000);
        dateRange.value = [monthAgo, today];
        break;
      case "quarter":
        const quarterAgo = new Date(today.getTime() - 90 * 24 * 60 * 60 * 1000);
        dateRange.value = [quarterAgo, today];
        break;
    }
    fetchDashboardData();
  };

  // 상태 색상
  const getStatusColor = (status) => {
    switch (status) {
      case "completed":
        return "success";
      case "delivered":
        return "primary";
      case "shipping":
        return "info";
      case "pending":
        return "warning";
      case "cancelled":
        return "error";
      default:
        return "grey";
    }
  };

  // 상태 텍스트
  const getStatusText = (status) => {
    switch (status) {
      case "completed":
        return "정산완료";
      case "delivered":
        return "배송완료";
      case "shipping":
        return "배송중";
      case "pending":
        return "대기";
      case "cancelled":
        return "취소";
      default:
        return "알 수 없음";
    }
  };

  // ag-grid 이벤트 핸들러 - 신규 주문 (대기중)
  const onPendingGridReady = (params) => {
    pendingGridApi.value = params.api;
  };

  const onPendingSelectionChanged = () => {
    const selectedRows = pendingGridApi.value.getSelectedRows();
    console.log("선택된 대기중 주문:", selectedRows);
  };

  // 페이지 변경 - 신규 주문
  const chgPendingPage = (page) => {
    pendingPageObj.value.currentPage = page;
    const startIndex = (page - 1) * pendingPageObj.value.pageSize;
    const endIndex = startIndex + pendingPageObj.value.pageSize;
    const paginatedData = pendingOrders.value.slice(startIndex, endIndex);

    if (pendingGridApi.value) {
      pendingGridApi.value.setGridOption("rowData", paginatedData);
    }
  };

  // ag-grid 이벤트 핸들러 - 배송중
  const onShippingGridReady = (params) => {
    shippingGridApi.value = params.api;
  };

  const onShippingSelectionChanged = () => {
    const selectedRows = shippingGridApi.value.getSelectedRows();
    console.log("선택된 배송중 주문:", selectedRows);
  };

  // 페이지 변경 - 배송중
  const chgShippingPage = (page) => {
    shippingPageObj.value.currentPage = page;
    const startIndex = (page - 1) * shippingPageObj.value.pageSize;
    const endIndex = startIndex + shippingPageObj.value.pageSize;
    const paginatedData = shippingOrders.value.slice(startIndex, endIndex);

    if (shippingGridApi.value) {
      shippingGridApi.value.setGridOption("rowData", paginatedData);
    }
  };

  // 주문 상세 보기
  const viewPendingOrder = (order) => {
    router.push({
      path: `/view/common/deli/detail/${order.itemSeq}`,
    });
  };

  const viewShippingOrder = (order) => {
    router.push({
      path: `/view/order/detail/${order.orderNo}`,
    });
  };

  // 엑셀 다운로드
  const exportPendingData = () => {
    $toast.success("신규 주문 데이터 다운로드를 시작합니다.");
  };

  const exportShippingData = () => {
    $toast.success("배송중 데이터 다운로드를 시작합니다.");
  };

  // 차트 생성
  const createSalesChart = () => {
    if (!salesChart.value) {
      console.log("salesChart ref가 없습니다");
      return;
    }

    try {
      // 기존 차트 인스턴스 삭제
      if (salesChartInstance) {
        salesChartInstance.destroy();
        salesChartInstance = null;
      }

      // Canvas 컨텍스트 직접 가져오기 (재생성 없이)
      const ctx = salesChart.value.getContext("2d");

      // 실제 데이터가 있으면 사용, 없으면 빈 차트
      const salesData =
        metrics.value.totalSales > 0
          ? [0, 0, 0, 0, 0, metrics.value.totalSales]
          : [0, 0, 0, 0, 0, 0];

      salesChartInstance = new ChartJS(ctx, {
        type: salesChartType.value,
        data: {
          labels: ["1월", "2월", "3월", "4월", "5월", "6월"],
          datasets: [
            {
              label: "매출",
              data: salesData,
              borderColor: "#3f51b5",
              backgroundColor:
                salesChartType.value === "bar" ? "#3f51b5" : "rgba(63, 81, 181, 0.1)",
              borderWidth: 2,
              fill: salesChartType.value === "line",
            },
          ],
        },
        options: {
          responsive: true,
          maintainAspectRatio: false,
          plugins: {
            legend: {
              display: false,
            },
          },
          scales: {
            y: {
              beginAtZero: true,
              ticks: {
                callback: function (value) {
                  return formatCurrency(value);
                },
              },
            },
          },
        },
      });
    } catch (error) {
      console.error("Sales 차트 생성 오류:", error);
    }
  };

  const createOrdersChart = () => {
    if (!ordersChart.value) {
      console.log("ordersChart ref가 없습니다");
      return;
    }

    try {
      // 기존 차트 인스턴스 삭제
      if (ordersChartInstance) {
        ordersChartInstance.destroy();
        ordersChartInstance = null;
      }

      // Canvas 컨텍스트 직접 가져오기 (재생성 없이)
      const ctx = ordersChart.value.getContext("2d");
      // 실제 주문 데이터 계산
      const totalOrders = metrics.value.totalOrders || 1;
      const completedRate = metrics.value.settlementRate || 0;
      const deliveredRate = Math.max(0, completedRate - 10); // 임시 계산
      const shippingRate = Math.max(0, 100 - completedRate - deliveredRate - 10);
      const pendingRate = Math.max(0, 100 - completedRate - deliveredRate - shippingRate);

      ordersChartInstance = new ChartJS(ctx, {
        type: "doughnut",
        data: {
          labels: ["신규 주문", "배송중", "배송완료", "정산완료"],
          datasets: [
            {
              data: [pendingRate, shippingRate, deliveredRate, completedRate],
              backgroundColor: ["#4caf50", "#ff9800", "#2196f3", "#9c27b0"],
              borderWidth: 0,
            },
          ],
        },
        options: {
          responsive: true,
          maintainAspectRatio: false,
          plugins: {
            legend: {
              position: "bottom",
            },
          },
        },
      });
    } catch (error) {
      console.error("Orders 차트 생성 오류:", error);
    }
  };

  const createSettlementChart = () => {
    if (!settlementChart.value) {
      console.log("settlementChart ref가 없습니다");
      return;
    }

    try {
      // 기존 차트 인스턴스 삭제
      if (settlementChartInstance) {
        settlementChartInstance.destroy();
        settlementChartInstance = null;
      }

      // Canvas 컨텍스트 직접 가져오기 (재생성 없이)
      const ctx = settlementChart.value.getContext("2d");
      const settlementRate = metrics.value.settlementRate || 0;
      const pendingRate = 100 - settlementRate;

      settlementChartInstance = new ChartJS(ctx, {
        type: "bar",
        data: {
          labels: ["1주", "2주", "3주", "4주"],
          datasets: [
            {
              label: "정산 완료",
              data: [settlementRate, settlementRate, settlementRate, settlementRate],
              backgroundColor: "#4caf50",
            },
            {
              label: "정산 대기",
              data: [pendingRate, pendingRate, pendingRate, pendingRate],
              backgroundColor: "#ff9800",
            },
          ],
        },
        options: {
          responsive: true,
          maintainAspectRatio: false,
          scales: {
            x: {
              stacked: true,
            },
            y: {
              stacked: true,
              beginAtZero: true,
              max: 100,
              ticks: {
                callback: function (value) {
                  return value + "%";
                },
              },
            },
          },
        },
      });
    } catch (error) {
      console.error("Settlement 차트 생성 오류:", error);
    }
  };

  const createCategoryChart = () => {
    if (!categoryChart.value) {
      console.log("categoryChart ref가 없습니다");
      return;
    }

    try {
      // 기존 차트 인스턴스 삭제
      if (categoryChartInstance) {
        categoryChartInstance.destroy();
        categoryChartInstance = null;
      }

      // Canvas 컨텍스트 직접 가져오기 (재생성 없이)
      const ctx = categoryChart.value.getContext("2d");
      categoryChartInstance = new ChartJS(ctx, {
        type: "pie",
        data: {
          labels: ["전체 상품"],
          datasets: [
            {
              data: [100],
              backgroundColor: ["#3f51b5"],
            },
          ],
        },
        options: {
          responsive: true,
          maintainAspectRatio: false,
          plugins: {
            legend: {
              position: "right",
            },
          },
        },
      });
    } catch (error) {
      console.error("Category 차트 생성 오류:", error);
    }
  };

  // 정산 데이터 가져오기
  const fetchSettlementData = async () => {
    try {
      const userInfo =
        useAuthStore().getSnsTempData?.user ||
        JSON.parse(localStorage.getItem("authStore") || "{}")?.auth;
      const _req = {
        MEMBER_TYPE: "VENDOR",
        COMPANY_NUMBER: userInfo?.COMPANY_NUMBER,
      };

      // 전체 정산 데이터 가져오기
      const allSettlementResponse = await useAxios().post("/deli/settlement", _req);
      const allSettlements = allSettlementResponse.data || [];

      // 정산완료된 데이터만 가져오기
      const completedSettlementResponse = await useAxios().post("/deli/settlement", {
        ..._req,
        SETTLEMENT_STATUS: "COMPLETED",
      });
      const completedSettlements = completedSettlementResponse.data || [];

      // 정산 메트릭 계산
      const totalOrders = allSettlements.length;
      const completedOrders = completedSettlements.length;
      const settlementRate =
        totalOrders > 0 ? ((completedOrders / totalOrders) * 100).toFixed(1) : 0;

      const totalSales = completedSettlements.reduce(
        (sum, item) => sum + (item.TOTAL || 0),
        0
      );
      const avgOrderValue = totalOrders > 0 ? totalSales / totalOrders : 0;

      // 메트릭 업데이트 (변화율은 현재 데이터만으로는 계산 불가하므로 0으로 설정)
      metrics.value = {
        totalSales: totalSales,
        totalOrders: totalOrders,
        settlementRate: parseFloat(settlementRate),
        avgOrderValue: avgOrderValue,
        salesChange: 0,
        ordersChange: 0,
        settlementChange: 0,
        avgOrderChange: 0,
      };
    } catch (error) {
      console.error("정산 데이터 조회 실패:", error);
    }
  };

  // 신규 주문 (대기중) 데이터 가져오기 - 새로운 API 사용
  const fetchPendingOrders = async () => {
    try {
      const userInfo =
        useAuthStore().getSnsTempData?.user ||
        JSON.parse(localStorage.getItem("authStore") || "{}")?.auth;
      
      const requestData = {
        MEMBER_TYPE: "VENDOR",
        COMPANY_NUMBER: userInfo?.COMPANY_NUMBER,
      };

      console.log("대기중 주문 API 요청:", requestData);
      
      const response = await useAxios().post("/deli/pendingOrdersForVendor", requestData);
      const pendingData = response.data || [];
      
      console.log("대기중 주문 API 응답:", pendingData);
      console.log("대기중 주문 데이터 개수:", pendingData.length);

      // 테이블 형식으로 변환
      const formattedPendingOrders = pendingData.map((item, index) => ({
        orderNo: `ORD-${item.SEQ || Date.now() + index}`,
        itemSeq: item.ITEM_SEQ,
        productName: item.ITEM_NAME || "상품명 없음",
        influencer: item.NICK_NAME || "알 수 없음",
        totalQty: item.QTY || 0,
        totalAmount: item.TOTAL || 0,
        latestOrderDate: $dayjs(item.REG_DATE || item.ORDER_DATE).format("YYYY-MM-DD"),
        status: "pending",
        originalData: item,
      }));

      console.log("변환된 대기중 주문 데이터:", formattedPendingOrders);

      pendingOrders.value = formattedPendingOrders;

      // 페이징 정보 업데이트
      pendingPageObj.value.totalCnt = formattedPendingOrders.length;
      pendingPageObj.value.totalPage = Math.ceil(
        formattedPendingOrders.length / pendingPageObj.value.pageSize
      );

      // ag-grid 데이터 갱신 (첫 페이지만)
      const firstPageData = formattedPendingOrders.slice(
        0,
        pendingPageObj.value.pageSize
      );

      if (pendingGridApi.value) {
        pendingGridApi.value.setGridOption("rowData", firstPageData);
      }
    } catch (error) {
      console.error("신규 주문 데이터 조회 실패:", error);
      $toast.error("신규 주문 데이터를 불러오는데 실패했습니다.");
    }
  };

  // 배송중 데이터 가져오기 - 기존 배송중 API 사용
  const fetchShippingOrders = async () => {
    try {
      const userInfo =
        useAuthStore().getSnsTempData?.user ||
        JSON.parse(localStorage.getItem("authStore") || "{}")?.auth;
      const _req = {
        MEMBER_TYPE: "VENDOR",
        COMPANY_NUMBER: userInfo?.COMPANY_NUMBER,
      };

      const response = await useAxios().post("/deli/shipping", _req);
      const shippingData = response.data || [];

      // 테이블 형식으로 변환
      const formattedShippingOrders = shippingData.map((order, index) => ({
        orderNo: `ORD-${order.SEQ || Date.now() + index}`,
        influencer: order.NICK_NAME || "알 수 없음",
        productName: order.ITEM_NAME || "상품명 없음",
        amount: order.TOTAL || 0,
        deliveryCompany: order.DELI_COMP || "-",
        trackingNumber: order.DELI_NUMB || "-",
        orderDate: $dayjs(order.ORDER_DATE || order.REG_DATE).format("YYYY-MM-DD"),
        status: "shipping",
        originalData: order,
      }));

      shippingOrders.value = formattedShippingOrders;

      // 페이징 정보 업데이트
      shippingPageObj.value.totalCnt = formattedShippingOrders.length;
      shippingPageObj.value.totalPage = Math.ceil(
        formattedShippingOrders.length / shippingPageObj.value.pageSize
      );

      // ag-grid 데이터 갱신 (첫 페이지만)
      const firstPageData = formattedShippingOrders.slice(
        0,
        shippingPageObj.value.pageSize
      );
      if (shippingGridApi.value) {
        shippingGridApi.value.setGridOption("rowData", firstPageData);
      }
    } catch (error) {
      console.error("배송중 데이터 조회 실패:", error);
      $toast.error("배송중 데이터를 불러오는데 실패했습니다.");
    }
  };

  // 대시보드 데이터 가져오기
  const fetchDashboardData = async () => {
    loading.value = true;

    try {
      await Promise.all([
        fetchSettlementData(),
        fetchPendingOrders(),
        fetchShippingOrders(),
      ]);

      // 데이터 로드 후 애니메이션과 차트 생성
      nextTick(() => {
        startMetricsAnimation();

        // 차트 키를 업데이트하여 재렌더링 유도
        salesChartKey.value++;
        ordersChartKey.value++;
        settlementChartKey.value++;
        categoryChartKey.value++;

        // 차트 생성을 지연시켜 DOM이 완전히 렌더링된 후 실행
        setTimeout(() => {
          createSalesChart();
          createOrdersChart();
          createSettlementChart();
          createCategoryChart();
        }, 200);
      });
    } catch (error) {
      $toast.error("대시보드 데이터를 불러오는데 실패했습니다.");
    } finally {
      loading.value = false;
    }
  };

  // 차트 타입 변경 감지
  watch(salesChartType, () => {
    salesChartKey.value++;
    nextTick(() => {
      createSalesChart();
    });
  });

  /************************************************************************
|    라이프사이클
************************************************************************/

  onMounted(() => {
    // 기본 1개월 기간 설정
    setQuickPeriod("month");

    // 대시보드 데이터 로드 (차트는 데이터 로드 후에 생성됨)
    fetchDashboardData();
  });
</script>

<style scoped>
  /* 대시보드 필터 스타일 */
  .dashboard--filters {
    margin: 20px 0;
    padding: 20px;
    background: #f8f9fa;
    border-radius: 8px;
  }

  .filter--wrap {
    display: flex;
    align-items: center;
    gap: 20px;
    flex-wrap: wrap;
  }

  .date--range {
    min-width: 300px;
  }

  .quick--filters {
    display: flex;
    gap: 8px;
  }

  .quick--filters .v-btn {
    background: white;
    color: #666;
    border: 1px solid #ddd;
  }

  .quick--filters .v-btn.active {
    background: #3f51b5;
    color: white;
    border-color: #3f51b5;
  }

  /* KPI 카드 스타일 */
  .dashboard--kpi {
    margin: 20px 0;
  }

  .kpi--cards {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
    gap: 20px;
  }

  .kpi--card {
    background: white;
    padding: 24px;
    border-radius: 12px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    border: 1px solid #e0e0e0;
  }

  .kpi--header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
  }

  .kpi--header h3 {
    font-size: 14px;
    font-weight: 600;
    color: #666;
    margin: 0;
  }

  .kpi--header .icon {
    width: 32px;
    height: 32px;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .icon.sales {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  }

  .icon.orders {
    background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  }

  .icon.settlement {
    background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  }

  .icon.avg {
    background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
  }

  .kpi--value {
    font-size: 28px;
    font-weight: 700;
    color: #333;
    margin-bottom: 8px;
  }

  .kpi--change {
    font-size: 12px;
    font-weight: 500;
  }

  .kpi--change.positive {
    color: #4caf50;
  }

  .kpi--change.negative {
    color: #f44336;
  }

  /* 차트 스타일 */
  .dashboard--charts {
    margin: 30px 0;
  }

  .chart--row {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(500px, 1fr));
    gap: 20px;
    margin-bottom: 20px;
  }

  .chart--container {
    background: white;
    border-radius: 12px;
    padding: 24px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    border: 1px solid #e0e0e0;
  }

  .chart--header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
  }

  .chart--header h3 {
    font-size: 18px;
    font-weight: 600;
    color: #333;
    margin: 0;
  }

  .chart--content {
    height: 300px;
    position: relative;
  }

  .chart--content canvas {
    max-height: 100%;
  }

  /* 테이블 스타일 */
  .dashboard--table {
    background: white;
    border-radius: 12px;
    padding: 24px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    border: 1px solid #e0e0e0;
    margin: 20px 0;
  }

  .table--header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
  }

  .table--header h3 {
    font-size: 18px;
    font-weight: 600;
    color: #333;
    margin: 0;
  }

  /* ag-grid 스타일 */
  .status-chip {
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 12px;
    font-weight: 500;
    color: white;
  }

  .status-success {
    background-color: #4caf50;
  }

  .status-primary {
    background-color: #2196f3;
  }

  .status-info {
    background-color: #00bcd4;
  }

  .status-warning {
    background-color: #ff9800;
  }

  .status-error {
    background-color: #f44336;
  }

  .status-grey {
    background-color: #9e9e9e;
  }

  .action-btn {
    background: #3f51b5;
    color: white;
    border: none;
    padding: 4px 8px;
    border-radius: 4px;
    cursor: pointer;
    font-size: 12px;
  }

  .action-btn:hover {
    background: #303f9f;
  }

  /* 반응형 */
  @media (max-width: 768px) {
    .filter--wrap {
      flex-direction: column;
      align-items: stretch;
    }

    .date--range {
      min-width: auto;
    }

    .quick--filters {
      justify-content: center;
    }

    .kpi--cards {
      grid-template-columns: 1fr;
    }

    .chart--row {
      grid-template-columns: 1fr;
    }
  }
</style>
