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

    <div class="view-wrap mt--45">
      <div class="view-box">
        <div class="view-box-top">
          <h3 >주문 관리</h3>
        </div>
        <div class="view-box-btm">
          <div class="form-style1">
            <v-form ref="addForm">
              <table>
                <colgroup>
                  <col style="width: 12.5rem" />
                  <col />
                </colgroup>
                <tbody>
                  <tr>
                    <th>이벤트 명</th>
                    <td>{{ form.title }}</td>
                  </tr>

                  <tr>
                    <th>이벤트 기간</th>
                    <td>{{ form.startDate }} ~ {{ form.endDate }}</td>
                  </tr>
                </tbody>
              </table>
            </v-form>
          </div>
        </div>
      </div>

      <div
        class="winner--rank--wrapper mt--45"
        :class="form.winnerArr.length > 0 ? 'count--' + form.winnerArr.length : ''"
      >
        <dl v-for="(item, index) in form.winnerArr" :key="index">
          <dt>
            <span class="rank"
              >{{ index + 1 }}등 (<i>{{ item.itemName }}</i></span
            >)
          </dt>
          <dd>
            <span class="name">
              {{ item.name }} <i v-if="item.count > 1">{{ item.count }} 외</i>
            </span>
            <span class="rank--count"> ( 1 / {{ item.count }} )</span>
          </dd>
        </dl>
        <!-- 3의 배수가 아닐 경우 또는 0개일 때 빈 dl 추가 -->
        <dl
          v-for="n in form.winnerArr.length === 0
            ? 4
            : form.winnerArr.length % 4 === 0
            ? 0
            : 4 - (form.winnerArr.length % 4)"
          :key="'empty-' + n"
        >
          <dt>&nbsp;</dt>
          <dd>&nbsp;</dd>
        </dl>
      </div>

      <div class="data--list--wrap">
        <div class="btn--actions--wrap">
          <div class="left--sections">
            <!-- <v-btn class="custom-btn mini btn-white">선택 삭제</v-btn> -->
          </div>
          <div class="right--sections d-flex gap--10">
            <!-- <v-btn class="custom-btn mini btn-reg" @click="addLocated()"
              ><i class="ico"></i>신규 등록</v-btn
            > -->
            <v-btn
              class="custom-btn btn-excel"
              @click="fnExcelDown"
              :disabled="Number(pageObj.totalCnt) <= 0"
              ><i class="ico"></i>엑셀 다운로드</v-btn
            >
            <div class="form--group--inner">
              <v-select
                v-model="form.productItemsSet"
                variant="outlined"
                style="min-width: 200px"
                class="custom-select"
                :items="form.productItemsArr"
                @update:modelValue="emailPush(form.productItemsSet)"
              >
              </v-select>
            </div>
          </div>
        </div>

        <div class="tbl-wrapper">
          <div class="tbl-wrap">
            <!-- ag grid -->
            <ag-grid-vue
              style="width: 100%; height: calc(4 * 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 class="view-btm-btn">
        <div class="btn-l">
          <!-- <v-btn class="custom-btn btn-list" @click="listLocated"
            ><i class="ico"></i>목록</v-btn
          > -->
          <!-- <v-btn v-show="pageType == 'U'" class="custom-btn btn-del" @click="fnDelEvt"
            ><i class="ico"></i>삭제</v-btn
          > -->
        </div>
        <div class="btn-r">
          <v-btn class="custom-btn btn-list" @click="listLocated"
            ><i class="ico"></i>목록</v-btn
          >
          <!-- <v-btn v-show="pageType == 'I'" class="custom-btn btn-blue2" @click="fnRegCheck"
            ><i class="ico"></i>저장</v-btn
          >
          <v-btn v-show="pageType == 'U'" class="custom-btn btn-blue2" @click="fnRegCheck"
            ><i class="ico"></i>수정</v-btn
          > -->
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
  import customButtonSms from "@/components/cellRenderer/customButtonSms";
import useUtil from "@/composables/useUtil";
import { AgGridVue } from "ag-grid-vue3";
import pagination from "../components/common/pagination.vue";

  /***********************
   *     plugins inject
   ************************/
  const { $toast, $log, $dayjs, $eventBus } = useNuxtApp();

  /************************************************************************
  |    레이아웃
  ************************************************************************/
  definePageMeta({
    layout: "default",
  });
  /************************************************************************
  |    스토어
   ************************************************************************/
  const useDtStore = useDetailStore();
  /************************************************************************
  |    전역
  ************************************************************************/
  let pageObj = ref({
    page: 1, // 현재 페이지
    pageMaxNumSize: 10, // 페이지 숫자 최대 표현 개수
    pageSize: 3, // 테이블 조회 데이터 개수
    totalCnt: 0, // 전체 페이지
  });
  const tblItems = ref([]); // stat 데이터
  const hide = ref(null);
  const addForm = ref(null);
  const router = useRouter();
  const isReadonly = ref(false);
  const pageType = ref("");
  const adminId = ref("");
  const pageId = ref("");
  const form = ref({
    id: "",
    passWord: "",
    passWordCheck: "",
    name: "",
    phone: ["", "", ""],
    email: ["", ""],
    title: "",
    startDate: "",
    endDate: "",
    emailAlarmArr: [
      { title: "Y", value: "Y" },
      { title: "N", value: "N" },
    ],
    emailSet: "",
    emailArr: [
      { title: "직접 입력하세요", value: "" },
      { title: "naver.com", value: "naver.com" },
      { title: "gmail.com", value: "gmail.com" },
      { title: "daum.net", value: "daum.net" },
      { title: "yahoo.com", value: "yahoo.com" },
      { title: "icloud.com", value: "icloud.com" },
      { title: "hotmail.com", value: "hotmail.com" },
      { title: "outlook.com", value: "outlook.com" },
    ],
    productItemsArr: [{ title: "선택 하세요.", value: "" }],
    productItemsSet: "",

    winnerArr: [],
    authority: {
      auth01: false,
      auth02: false,
      auth03: false,
      auth04: false,
      auth05: false,
      auth06: false,
    },
    idCheck: false,
  });

  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: [
      {
        headerName: "No",
        valueGetter: (params) => params.api.getDisplayedRowCount() - params.node.rowIndex,
        sortable: false,
        width: 70,
      },
      // { headerName: "번호", field: "NO", sortable: false },
      { headerName: "순위", field: "rank", sortable: false },
      { headerName: "상품명", field: "item_name", sortable: true },
      { headerName: "이름", field: "name", sortable: false, width: 140 },
      { headerName: "핸드폰", field: "phone", sortable: false, width: 140 },
      {
        headerName: "개인정보동의",
        field: "privacy_agree",
        sortable: false,
        width: 140,
        valueFormatter: (params) => (params.value == 1 ? "동의" : ""),
      },
      {
        headerName: "개인정보3자 동의",
        field: "thirdparty_agree",
        sortable: false,
        width: 140,
        valueFormatter: (params) => (params.value == 1 ? "동의" : ""),
      },
      { headerName: "당첨일", field: "winner_date", sortable: false, width: 140 },
      {
        headerName: "SMS",
        field: "phone",
        cellRenderer: customButtonSms,
        cellRendererParams: {
          onSendKakao: (phone) => sendKakaoMessage(phone),
        },
      },
    ],
    rowData: tblItems.value, // 테이블 데이터
    autoSizeStrategy: {
      type: "fitGridWidth", // width맞춤
    },
    suppressMovableColumns: true,
    headerHeight: rowHeightPx,
    rowHeight: rowHeightPx,
    pagination: true,
    suppressPaginationPanel: true, // 하단 default 페이징 컨트롤 숨김
  };

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

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

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

  const fnDetail = () => {
    let url = "/winner/detail/" + useDtStore.boardInfo.seq;
    useAxios()
      .get(url, null)
      .then((res) => {
        let winnerList = res.data.participations_cal;
        form.value.title = res.data.title;
        form.value.startDate = res.data.startdate;
        form.value.endDate = res.data.enddate;

        //아이템 리스트
        res.data.items.forEach((element) => {
          form.value.productItemsArr.push({
            title: element.name,
            value: element.name,
          });
        });

        //당첨자 리스트
        winnerList.forEach((element) => {
          if (element.rank > 0) {
            form.value.winnerArr.push({
              rank: element.rank,
              itemName: element.item_name,
              name: element.name,
              count: element.count,
            });
          }
        });

        tblItems.value = res.data.participations;
        pageObj.value.totalCnt = tblItems.value.length;
      })
      .catch((error) => {})
      .finally(() => {});
  };

  const emailPush = (__VAL) => {
    form.value.email[1] = __VAL;
    hide.value = __VAL.length > 0 ? true : false;
  };

  function sendKakaoMessage(phone) {
    // 문자 발송 API 호출
    alert(phone + "번호로 문자가 발송되었습니다.");

    // useAxios()
    //   .post("/kakao/send", { phone })
    //   .then(() => {
    //     // 성공 처리
    //   })
    //   .catch(() => {
    //     // 실패 처리
    //   });
  }

  function fnExcelDown() {
    let headers = [];
    let excelData = [];

    tblItems.value.forEach((item) => {
      let excelRow = {};
      excelRow.ipAddr = item.ipAddr;
      excelRow.allowYnTxt = item.allowYnTxt;
      excelRow.ipDesc = item.ipDesc;
      excelRow.updateDate = $dayjs(item.updateDate).format("YYYY-MM-DD HH:mm:ss");
      excelData.push(excelRow);
    });
    headers.push({ header: "순위", dataKey: "rank" });
    headers.push({ header: "상품명", dataKey: "item_name" });
    headers.push({ header: "이름", dataKey: "name" });
    headers.push({ header: "핸드폰", dataKey: "phone" });
    headers.push({ header: "개인정보 동의", dataKey: "privacy_agree" });
    headers.push({ header: "개인정보3자 동의", dataKey: "thirdparty_agree" });
    headers.push({ header: "당첨일", dataKey: "winner_date" });

    let params = {
      uri: "",
      title: "접속IP설정",
    };
    // Excel 다운로드 요청
    useUtil.fnExcelDownLoad(params, headers, excelData);
  }

  function fnPartList(EVT_SEQ, ITEM_NAME) {
    let params = {
      seq: EVT_SEQ,
      item_name: ITEM_NAME,
    };
    useAxios()
      .post("/winner/partclist", params)
      .then((res) => {
        tblItems.value = res.data.list;
        pageObj.value.totalCnt = tblItems.value.length;
      })
      .catch((error) => {})
      .finally(() => {});
  }
  /************************************************************************
  |    함수(METHODS)
  ************************************************************************/

  const listLocated = () => {
    router.push({
      path: "/view/winner",
    });
  };

  /************************************************************************
  |    라이프사이클
  ************************************************************************/
  onMounted(() => {
    pageType.value = useDtStore.adminInfo.pageType;

    //관리자 등록/수정 분기처리
      pageId.value = "주문 관리";
  });

  /************************************************************************
  |    팝업 이벤트버스 정의
  ************************************************************************/
  // $eventBus.off("FN_INSERT");
  // $eventBus.on("FN_INSERT", () => {
  //   fnInsert();
  // });
  // $eventBus.off("FN_UPDATE");
  // $eventBus.on("FN_UPDATE", () => {
  //   fnUpdate();
  // });
  // $eventBus.off("FN_DELETE");
  // $eventBus.on("FN_DELETE", () => {
  //   fnDelete();
  // });
  /************************************************************************
  |    WATCH
  ************************************************************************/
  watch(
    () => form.value.productItemsSet,
    (newVal, oldVal) => {
      if (newVal !== oldVal) {
        fnPartList(useDtStore.boardInfo.seq, newVal);
      }
    }
  );
</script>
