<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">
          <div class="summary-info">
            <span class="summary-item">
              총 주문: {{ totalStats.totalOrders }}건
            </span>
            <span class="summary-item">
              총 금액: {{ Number(totalStats.totalAmount).toLocaleString() }}원
            </span>
            <span class="summary-item">
              정산대기: {{ totalStats.pendingCount }}건
            </span>
            <span class="summary-item">
              정산완료: {{ totalStats.completedCount }}건
            </span>
          </div>
        </div>
        <div class="right--sections">
          <div class="item-type-filter">
            <v-select
              v-model="itemTypeFilter"
              :items="itemTypeOptions"
              variant="outlined"
              class="custom-select mini"
              @update:modelValue="applyItemTypeFilter"
            >
            </v-select>
          </div>
          <div class="form--cont--filter">
          <v-select
            v-model="settlementFilter"
            :items="settlementOptions"
            variant="outlined"
            class="custom-select"
            @update:modelValue="applySettlementFilter"
          >
          </v-select>
        </div>
          <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(12 * 2.94rem)"
            class="ag-theme-quartz"
            :gridOptions="gridOptions"
            :rowData="tblItems"
            :paginationPageSize="pageObj.pageSize"
            :suppressPaginationPanel="true"
            @grid-ready="onGridReady"
          >
          </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 selectedRange = ref('all');
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" },
  { title: "구매자명", value: "buyer" },
  { title: "인플루언서", value: "inf_name"}
]);
const settlementFilter = ref("");
const settlementOptions = ref([
  { title: "전체", value: "" },
  { title: "정산대기", value: "PENDING" },
  { title: "정산완료", value: "COMPLETED" },
]);
const itemTypeFilter = ref("");
const itemTypeOptions = ref([
  { title: "전체", value: "" },
  { title: "개별구매", value: "E" },
  { title: "공동구매", value: "G" },
]);
const originalTblItems = ref([]);
const { $toast, $log, $dayjs, $eventBus } = useNuxtApp();
const router = useRouter();
const pageId = ref("정산 관리");
let pageObj = ref({
  page: 1,
  pageMaxNumSize: 10,
  pageSize: 12,
  totalCnt: 0,
});
const tblItems = ref([]);
const totalStats = ref({
  totalOrders: 0,
  totalAmount: 0,
  pendingCount: 0,
  completedCount: 0
});

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

// gridOption
const gridOptions = {
  columnDefs: [
    {
      headerName: "No",
      valueGetter: (params) => params.api.getDisplayedRowCount() - params.node.rowIndex,
      sortable: false,
      width: 70,
    },
    {
      headerName: "구분",
      field: "ITEM_TYPE",
      width: 90,
      cellRenderer: (params) => {
        return params.value === 'E' ? '개별구매' : '공동구매';
      },
    },
    {
      headerName: "인플루언서",
      field: "INF_NICK_NAME",
      width: 120,
    },
    {
      headerName: "제품명",
      field: "ITEM_NAME",
      width: 200,
    },
    {
      headerName: "구매자명",
      field: "BUYER_NAME",
      width: 120,
    },
    {
      headerName: "연락처",
      field: "PHONE",
      width: 140,
    },
    {
      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: "DELIVERED_DATE",
      width: 140,
      cellRenderer: (params) => {
        return params.value ? dayjs(params.value).format('YYYY-MM-DD') : '';
      },
    },
    {
      headerName: "정산상태",
      field: "SETTLEMENT_STATUS",
      width: 100,
      cellRenderer: (params) => {
        const status = params.value || 'PENDING';
        const statusMap = {
          'PENDING': { text: '대기', color: 'warning' },
          'COMPLETED': { text: '완료', color: 'success' }
        };
        const config = statusMap[status] || statusMap['PENDING'];
        
        return `<span class="v-chip v-chip--density-default v-chip--size-default v-chip--variant-elevated bg-${config.color}" style="font-size: 12px; padding: 4px 8px;">${config.text}</span>`;
      }
    },
    {
      headerName: "정산완료일",
      field: "SETTLED_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,
};

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 = "";
      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 getSettlementList = async () => {
  let _req = {
    MEMBER_TYPE: memberType
  };

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

  await useAxios()
    .post("/deli/settlement", _req)
    .then((res) => {
      console.log(res.data)
      originalTblItems.value = res.data;
      applyAllFilters();
      calculateStats();
    });
};

const calculateStats = () => {
  const data = originalTblItems.value;
  totalStats.value = {
    totalOrders: data.length,
    totalAmount: data.reduce((sum, item) => sum + (Number(item.TOTAL) || 0), 0),
    pendingCount: data.filter(item => (item.SETTLEMENT_STATUS || 'PENDING') === 'PENDING').length,
    completedCount: data.filter(item => item.SETTLEMENT_STATUS === 'COMPLETED').length
  };
};

const applyAllFilters = () => {
  let filteredData = originalTblItems.value;
  
  // 정산상태 필터 적용
  if (settlementFilter.value !== "") {
    filteredData = filteredData.filter(item => {
      const itemStatus = item.SETTLEMENT_STATUS || 'PENDING';
      return itemStatus === settlementFilter.value;
    });
  }
  
  // 아이템 타입 필터 적용
  if (itemTypeFilter.value !== "") {
    console.log('아이템 타입 필터 적용:', itemTypeFilter.value);
    console.log('필터 전 데이터 개수:', filteredData.length);
    filteredData = filteredData.filter(item => {
      console.log(`아이템: ${item.ITEM_NAME}, 타입: "${item.ITEM_TYPE}", 필터값: "${itemTypeFilter.value}", 매치: ${item.ITEM_TYPE === itemTypeFilter.value}`);
      return item.ITEM_TYPE === itemTypeFilter.value;
    });
    console.log('필터 후 데이터 개수:', filteredData.length);
  }
  
  // 날짜 범위 검색 적용 (배송완료일 기준)
  if (searchStartDate.value || searchEndDate.value) {
    filteredData = filteredData.filter(item => {
      if (!item.DELIVERED_DATE) return false;
      
      const deliveredDate = dayjs(item.DELIVERED_DATE).format('YYYY-MM-DD');
      
      // 시작날짜와 끝날짜가 모두 있는 경우
      if (searchStartDate.value && searchEndDate.value) {
        const startDate = dayjs(searchStartDate.value).format('YYYY-MM-DD');
        const endDate = dayjs(searchEndDate.value).format('YYYY-MM-DD');
        return deliveredDate >= startDate && deliveredDate <= endDate;
      }
      // 끝날짜만 있는 경우
      else if (searchEndDate.value) {
        const endDate = dayjs(searchEndDate.value).format('YYYY-MM-DD');
        return deliveredDate <= endDate;
      }
      
      return true;
    });
  }
  
  tblItems.value = filteredData;
  pageObj.value.totalCnt = tblItems.value.length;
  
  // ag-grid 데이터 갱신
  if (gridApi.value) {
    gridApi.value.setGridOption('rowData', tblItems.value);
  }
};

const applySettlementFilter = () => {
  applyAllFilters();
};

const applyItemTypeFilter = () => {
  applyAllFilters();
};

const fnSearch = (__KEYWORD, __FILTER) => {
  // 검색 로직 구현
  let filteredData = originalTblItems.value;
  
  // 정산상태 필터 적용
  if (settlementFilter.value !== "") {
    filteredData = filteredData.filter(item => {
      const itemStatus = item.SETTLEMENT_STATUS || 'PENDING';
      return itemStatus === settlementFilter.value;
    });
  }
  
  // 아이템 타입 필터 적용
  if (itemTypeFilter.value !== "") {
    filteredData = filteredData.filter(item => {
      return item.ITEM_TYPE === itemTypeFilter.value;
    });
  }
  
  // 키워드 검색 적용
  if (__KEYWORD && __KEYWORD.trim() !== '') {
    filteredData = filteredData.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 if (__FILTER === 'inf_name') {
        return item.INF_NICK_NAME && item.INF_NICK_NAME.toLowerCase().includes(__KEYWORD.toLowerCase());
      } {
        // 전체 검색
        return (item.ITEM_NAME && item.ITEM_NAME.toLowerCase().includes(__KEYWORD.toLowerCase())) ||
               (item.BUYER_NAME && item.BUYER_NAME.toLowerCase().includes(__KEYWORD.toLowerCase())) ||
               item.INF_NICK_NAME && item.INF_NICK_NAME.toLowerCase().includes(__KEYWORD.toLowerCase());
      }
    });
  }
  
  // 날짜 범위 검색 적용 (배송완료일 기준)
  if (searchStartDate.value || searchEndDate.value) {
    filteredData = filteredData.filter(item => {
      if (!item.DELIVERED_DATE) return false;
      
      const deliveredDate = dayjs(item.DELIVERED_DATE).format('YYYY-MM-DD');
      
      // 시작날짜와 끝날짜가 모두 있는 경우
      if (searchStartDate.value && searchEndDate.value) {
        const startDate = dayjs(searchStartDate.value).format('YYYY-MM-DD');
        const endDate = dayjs(searchEndDate.value).format('YYYY-MM-DD');
        return deliveredDate >= startDate && deliveredDate <= endDate;
      }
      // 끝날짜만 있는 경우
      else if (searchEndDate.value) {
        const endDate = dayjs(searchEndDate.value).format('YYYY-MM-DD');
        return deliveredDate <= endDate;
      }
      
      return true;
    });
  }
  
  tblItems.value = filteredData;
  pageObj.value.totalCnt = tblItems.value.length;
  
  if (gridApi.value) {
    gridApi.value.setGridOption('rowData', filteredData);
  }
};

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

<style scoped>
.summary-info {
  display: flex;
  gap: 20px;
  align-items: center;
}

.item-type-filter {
  margin-left: 20px;
}

.summary-item {
  font-size: 14px;
  font-weight: 500;
  color: #333;
  padding: 8px 12px;
  background: #f5f5f5;
  border-radius: 4px;
}

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

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

.btn--actions--wrap .left--sections {
  flex: 1;
}
</style>