<template>
  <div>
    <div class="inner--headers">
      <h2>{{ pageId }}</h2>
      <div class="bread--crumbs--wrap">
        <span>홈</span>
        <span>이벤트 관리</span>
        <span>{{ pageId }}</span>
        <span v-if="pageIdSub">{{ pageIdSub }}</span>
      </div>
    </div>
    <div class="data--list--wrap">
      <div class="table--wrap">
        <v-form ref="addForm">
          <table>
            <colgroup>
              <col width="20%" />
              <col width="80%" />
            </colgroup>
            <tbody>
              <tr>
                <th class="bg le">
                  이벤트명<span v-if="!isDisabled" class="bul">*</span>
                </th>
                <td class="le" v-if="isDisabled">
                  {{ form.formValue1 }}
                </td>
                <td v-else>
                  <v-text-field
                    maxlength="50"
                    v-model="form.formValue1"
                    style="width: 100%"
                    :rules="[useValid.required('이벤트명')]"
                    class="custom-input mini left"
                    placeholder="이벤트명을 입력하세요"
                  ></v-text-field>
                </td>
              </tr>
              <tr>
                <th class="bg le">
                  이벤트 기간<span v-if="!isDisabled" class="bul">*</span>
                </th>
                <td v-if="!isDisabled">
                  <div class="calendar-wrap ml--0">
                    <div class="calendar">
                      <VueDatePicker
                        :format="datePickerFormat"
                        v-model="form.formValue2"
                        placeholder="날짜를 선택하세요"
                        :auto-apply="true"
                        :readonly="isDisabled"
                        week-start="0"
                      ></VueDatePicker>
                    </div>
                    <span class="text">~</span>
                    <div class="calendar">
                      <VueDatePicker
                        :format="datePickerFormat"
                        v-model="form.formValue3"
                        placeholder="날짜를 선택하세요"
                        :auto-apply="true"
                        week-start="0"
                        :readonly="isDisabled"
                      ></VueDatePicker>
                    </div>
                    <div class="btn--wrap evt--btn ml--10">
                      <v-btn
                        v-show="pageType == 'U' && evtStatus == '0'"
                        class="custom-btn btn-sky"
                        @click="fnStUpdEvt"
                        ><i class="ico"></i>이벤트 진행</v-btn
                      >
                      <v-btn
                        v-show="pageType == 'U' && evtStatus == '1'"
                        class="custom-btn btn-red"
                        @click="fnStUpdEvt"
                        ><i class="ico"></i>이벤트 마감</v-btn
                      >
                    </div>
                  </div>
                </td>
                <td v-else>
                  <div class="calendar-wrap ml--0">
                    {{ form.formValue2 }} ~ {{ form.formValue3 }}
                    <div class="btn--wrap evt--btn ml--10">
                      <v-btn
                        v-show="pageType == 'U' && evtStatus == '0'"
                        class="custom-btn btn-sky"
                        @click="fnStUpdEvt"
                        ><i class="ico"></i>이벤트 진행</v-btn
                      >
                      <v-btn
                        v-show="pageType == 'U' && evtStatus == '1'"
                        class="custom-btn btn-red"
                        @click="fnStUpdEvt"
                        ><i class="ico"></i>이벤트 마감</v-btn
                      >
                    </div>
                  </div>
                </td>
              </tr>
              <tr v-for="(item, index) in itemsForm.items" :key="index">
                <th class="bg le">
                  아이템 등록
                  <span v-if="itemsForm.items.length > 0"> {{ index + 1 }} </span>
                  <span v-if="!isDisabled && index < 2" class="bul">*</span>
                </th>
                <td v-if="!isDisabled">
                  <div class="input--wrap">
                    <v-text-field
                      maxlength="50"
                      v-model="item.name"
                      style="width: 30%"
                      class="custom-input mini left"
                      placeholder="아이템명을 입력하세요"
                      :rules="[useValid.required('아이템명')]"
                      :readonly="isDisabled"
                    ></v-text-field>
                    <v-text-field
                      v-model="item.qty"
                      placeholder="당첨 수량을 입력하세요"
                      style="width: 20%"
                      class="custom-input mini left"
                      :rules="[useValid.required('당첨 수량')]"
                      maxlength="10"
                      @input="(e) => formatNumber(e, item, 'qty')"
                      :readonly="isDisabled"
                    />
                    <v-text-field
                      v-model="item.rate"
                      placeholder="당첨 확률을 입력하세요"
                      style="width: 15%"
                      :rules="[useValid.required('당첨 확률')]"
                      class="custom-input mini left"
                      maxlength="7"
                      @input="(e) => formatFloat(e, item, 'rate')"
                      :readonly="isDisabled"
                    />
                    <span class="text"> % </span>
                    <v-btn
                      icon="mdi-minus"
                      color="red"
                      size="small"
                      :disabled="itemsForm.items.length <= 2 || isDisabled"
                      @click="removeItem(index)"
                    ></v-btn>
                    <v-btn
                      icon="mdi-plus"
                      color="primary"
                      size="small"
                      :disabled="itemsForm.items.length >= 15 || isDisabled"
                      v-if="index === itemsForm.items.length - 1"
                      @click="addItem"
                    ></v-btn>
                  </div>
                </td>
                <td v-else>
                  <div class="input--wrap">
                    {{ item.name }}
                    / 당첨 수량 : {{ item.qty }} / 당첨 확률 : {{ item.rate }} %
                  </div>
                </td>
              </tr>
              <tr>
                <th class="bg le">
                  문자 메시지<span v-if="!isDisabled" class="bul">*</span>
                </th>
                <td>
                  <div class="btn--wrap evt--btn">
                    <v-btn class="custom-btn btn-sky" @click="messageFormOpen()"
                      ><i class="ico"></i>문자 메시지 입력</v-btn
                    >
                    <v-dialog v-model="messageForm" persistent width="50rem">
                      <div class="v-common-dialog-wrapper custom-dialog">
                        <div class="modal-tit">
                          <strong>문자 메시지 입력</strong>
                          <button class="btn-close" @click="messageForm = false"></button>
                        </div>
                        <div class="v-common-dialog-content">
                          <div class="ms--pop">
                            <div class="ms--input--wrap">
                              <v-textarea
                                row-height="15"
                                v-model="form.formValue4Temp"
                                hide-details=""
                                rows="15"
                                :readonly="isDisabled"
                                variant="outlined"
                                no-resize
                              >
                              </v-textarea>
                            </div>
                            <div class="ms--desc--wrap">
                              <p>
                                <strong>코드명</strong>
                                코드명은 자동으로 노출됩니다.
                                <br />
                                {이벤트명} : 등록된 이벤트명이 노출됩니다.<br />
                                {상품명} : 등록된 상품이 노출됩니다.<br />
                                {당첨일} : 당첨된 날짜가 노출됩니다.
                              </p>
                            </div>
                          </div>
                        </div>
                        <div class="btn-wrap">
                          <v-btn
                            class="custom-btn btn-white mini"
                            v-if="!isDisabled"
                            @click="messageForm = false"
                            ><i class="ico"></i>취소</v-btn
                          >
                          <v-btn
                            class="custom-btn btn-blue mini"
                            v-if="!isDisabled"
                            @click="messageFormUpt()"
                            ><i class="ico"></i>저장</v-btn
                          >
                        </div>
                      </div>
                    </v-dialog>
                  </div>
                </td>
              </tr>
              <tr>
                <th class="bg le">이벤트 바로가기</th>
                <td>
                  <div class="btn--wrap evt--btn" v-if="evtStatus == '1'">
                    <v-btn class="custom-btn btn-sky" @click="evtLocationAction"
                      ><i class="ico"></i>이벤트 바로가기</v-btn
                    >
                  </div>
                  <div class="caution--text text-left" v-else>
                    * 이벤트 진행전에 룰렛페이지 접속이 불가능합니다.
                  </div>
                </td>
              </tr>
            </tbody>
          </table>
        </v-form>
      </div>
      <div class="view-btm-btn">
        <div class="btn-l">
          <v-btn class="custom-btn btn-list" @click="router.back()"
            ><i class="ico"></i>목록</v-btn
          >
        </div>
        <div class="btn-r">
          <v-btn v-if="pageType == 'I'" class="custom-btn btn-blue2" @click="fnRegCheck"
            ><i class="ico"></i>저장</v-btn
          >
          <v-btn
            v-else-if="pageType == 'U' && evtStatus == '0'"
            class="custom-btn btn-blue2"
            @click="fnRegCheck"
            ><i class="ico"></i>수정</v-btn
          >
          <v-btn
            v-else
            class="custom-btn btn-blue2"
            @click="router.push('/view/event/evtList')"
            >참여자 보기</v-btn
          >
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import VueDatePicker from "@vuepic/vue-datepicker";
import "@vuepic/vue-datepicker/dist/main.css";
import { reactive } from "vue";
  /************************************************************************
|    레이아웃
************************************************************************/
  definePageMeta({
    layout: "default",
  });

  /************************************************************************
|   PROPS
 ************************************************************************/
  const props = defineProps({
    propsData: {
      type: Object,
      default: () => {},
    },
  });

  /************************************************************************
|    스토어
 ************************************************************************/
  //const useAuthStore = useAuthStore();
  const useDtStore = useDetailStore();
  /************************************************************************
|    전역
 ************************************************************************/
  const { $toast, $log, $dayjs, $eventBus } = useNuxtApp();
  const router = useRouter();
  const pageType = useDtStore.boardInfo.pageType;
  const evtStatus = useDtStore.boardInfo.status;
  const pageId =
    pageType == "U"
      ? evtStatus == "1"
        ? "진행중 이벤트"
        : evtStatus == "2"
        ? "마감된 이벤트"
        : "이벤트 수정"
      : "이벤트 등록";
  const isDisabled = pageType == "I" ? false : evtStatus !== "0" ? true : false;
  const pageIdSub = ref();
  const addForm = ref(null);
  const datePickerFormat = "yyyy-MM-dd";
  const messageForm = ref(false);
  const form = ref({
    formValue1: "",
    formValue2: "",
    formValue3: "",
    formValue4:
      "안녕하세요. 고객님!\n{이벤트명}\n{상품명} 당첨을 축하드립니다. \n당첨일자 : {당첨일}\n\n*이 메시지는 고객님이 참여한 이벤트 당첨으로 지급된 안내 메시지입니다.\n\n문의 : 고객센터 1234-1234\n\n감사합니다.",
    formValue4Temp: "",
  });
  const itemsForm = reactive({
    items: [
      {
        name: "",
        qty: "",
        rate: "",
      },
      {
        name: "",
        qty: "",
        rate: "",
      },
    ],
  });

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

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

  const addItem = () => {
  if (itemsForm.items.length < 15) {
    itemsForm.items.push({ name: '', qty: '', rate: '' })
  }
}

  const removeItem = (index) => {
    if (itemsForm.items.length > 1) {
      itemsForm.items.splice(index, 1);
    }
  };

  const formatNumber = (event, row, field) => {
    let input = event.target.value.replace(/[^0-9]/g, "");
    let formattedInput = input ? new Intl.NumberFormat().format(input) : "";
    row[field] = formattedInput;
  };

  const formatFloat = (event, row, field) => {
    let input = event.target.value;

    // 숫자만 추출
    input = input.replace(/[^0-9]/g, "");

    // 입력값이 없으면 빈값 처리
    if (!input) {
      row[field] = "";
      return;
    }

    // 2자리까진 그대로, 3자리 이상이면 소수점 자동 삽입
    let result = "";
    if (input.length <= 2) {
      result = input;
    } else {
      const intPart = input.slice(0, 2);
      const decimalPart = input.slice(2, 5); // 소수점 이하 최대 3자리
      result = `${intPart}.${decimalPart}`;
    }

    // 숫자로 변환해서 100 초과면 강제로 100으로 고정
    const num = parseFloat(result);
    if (!isNaN(num) && num > 100) {
      result = "100";
    }

    // 최종 결과 저장
    row[field] = result;
  };

  const messageFormOpen = () => {
    messageForm.value = true;
    form.value.formValue4Temp = form.value.formValue4;
  };

  const messageFormUpt = () => {
    if (form.value.formValue4Temp) {
      form.value.formValue4 = form.value.formValue4Temp;
      messageForm.value = false;
    } else {
      let param = {
        id: pageId,
        title: "문자 메시지 입력",
        content: "문자 메시지를 입력해주세요.",
        yes: {
          text: "확인",
          isProc: false,
        },
      };
      $eventBus.emit("OPEN_CONFIRM_POP_UP", param);
    }
  };

  const formatDate = (date) => {
    const d = new Date(date);
    const year = d.getFullYear();
    const month = ("0" + (d.getMonth() + 1)).slice(-2);
    const day = ("0" + d.getDate()).slice(-2);
    return `${year}-${month}-${day}`;
  };

  const fnRegCheck = () => {
    nextTick(() => {
      if (addForm.value && typeof addForm.value.validate === "function") {
        addForm.value
          .validate()
          .then((isValid) => {
            if (isValid.valid) {
              if (pageType == "I") {
                // 등록시 이벤트 기간만 별도로 필수 체크
                if (form.value.formValue2 && form.value.formValue3) {
                  fnRegEvt();
                } else {
                  let param = {
                    id: pageId,
                    title: "이벤트 등록",
                    content: "이벤트 기간을 선택해주세요.",
                    yes: {
                      text: "확인",
                      isProc: false,
                    },
                  };
                  $eventBus.emit("OPEN_CONFIRM_POP_UP", param);
                }
              } else {
                fnUpdEvt();
              }
            } else {
              if (pageType == "I") {
                let param = {
                  id: pageId,
                  title: "이벤트 등록",
                  content: "필수항목을 입력해주세요.",
                  yes: {
                    text: "확인",
                    isProc: false,
                  },
                };
                $eventBus.emit("OPEN_CONFIRM_POP_UP", param);
              } else {
                let param = {
                  id: pageId,
                  title: "이벤트 수정",
                  content: "필수항목을 입력해주세요.",
                  yes: {
                    text: "확인",
                    isProc: false,
                  },
                };
                $eventBus.emit("OPEN_CONFIRM_POP_UP", param);
              }
            }
          })
          .catch((err) => {
            console.error("벨리데이션 에러", err);
          });
      } else {
        console.error("항목 누락체크[fnRegCheck]]");
      }
    });
  };

  const fnRegEvt = () => {
    let param = {
      id: pageId,
      title: "이벤트 등록",
      content: "등록하시겠습니까?",
      yes: {
        text: "등록",
        isProc: true,
        event: "FN_INSERT",
        param: "",
      },
      no: {
        text: "취소",
        isProc: false,
      },
    };
    $eventBus.emit("OPEN_CONFIRM_POP_UP", param);
  };

  const fnInsert = () => {
    let params = {
      compId: useAuthStore().getCompanyId,
      title: form.value.formValue1,
      startdate: form.value.formValue2,
      enddate: form.value.formValue3,
      item: itemsForm.items.map((item) => ({
        name: item.name,
        qty: item.qty.replace(/,/g, ""),
        rate: item.rate,
      })),
    };

    useAxios()
      .post("/evt/reg", params)
      .then((res) => {
        router.push("/view/event/evtList");
      })
      .catch((error) => {})
      .finally(() => {});
  };

  const fnUpdate = () => {
    let _req = {
      seq: useDtStore.boardInfo.seq,
      title: form.value.formValue1,
      startdate: form.value.formValue2,
      enddate: form.value.formValue3,
      item: itemsForm.items.map((item) => ({
        name: item.name,
        qty: item.qty.replace(/,/g, ""),
        rate: item.rate,
      })),
    };

    useAxios()
      .post("/evt/update", _req)
      .then((res) => {
        router.push({
          path: "/view/event/evtList",
        });
      })
      .catch((error) => {});
  };

  const fnDetail = () => {
    let _req = {
      seq: useDtStore.boardInfo.seq,
    };
    useAxios()
      .get(`evt/detail/${_req.seq}`)
      .then((res) => {
        form.value.formValue1 = res.data.title;
        form.value.formValue2 = new Date(res.data.startdate);
        form.value.formValue3 = new Date(res.data.enddate);
        //form.value.formValue4 =

        itemsForm.items.splice(
          0,
          itemsForm.items.length,
          ...res.data.items.map((item) => ({
            name: item.name || "",
            qty: item.qty ? new Intl.NumberFormat().format(item.qty) : "",
            rate: item.rate || "",
          }))
        );
      })
      .catch((error) => {});
  };

  const fnStUpdate = () => {
    let _req = {
      seq: useDtStore.boardInfo.seq,
    };

    useAxios()
      .post(`/evt/stupdate/${_req.seq}`)
      .then((res) => {
        router.push({
          path: "/view/event/evtList",
        });
      })
      .catch((error) => {});
  };
  const fnUpdEvt = () => {
    let param = {
      id: pageId,
      title: "이벤트 수정",
      content: "수정하시겠습니까?",
      yes: {
        text: "확인",
        isProc: true,
        event: "FN_UPDATE",
        param: "",
      },
      no: {
        text: "취소",
        isProc: false,
      },
    };
    $eventBus.emit("OPEN_CONFIRM_POP_UP", param);
  };

  const fnStUpdEvt = () => {
    if (evtStatus == 0) {
      let param = {
        id: pageId,
        title: "이벤트 진행",
        content: "이벤트를 진행하시겠습니까?",
        yes: {
          text: "확인",
          isProc: true,
          event: "FN_STUPDATE",
          param: "",
        },
        no: {
          text: "취소",
          isProc: false,
        },
      };
      $eventBus.emit("OPEN_CONFIRM_POP_UP", param);
    } else if (evtStatus == 1) {
      let param = {
        id: pageId,
        title: "이벤트 마감",
        content: "이벤트를 마감하시겠습니까?",
        yes: {
          text: "확인",
          isProc: true,
          event: "FN_STUPDATE",
          param: "",
        },
        no: {
          text: "취소",
          isProc: false,
        },
      };
      $eventBus.emit("OPEN_CONFIRM_POP_UP", param);
    }
  };

  const evtLocationAction = () => {
    window.open("/view/roulette", "_blank");
  };
  /************************************************************************
|    팝업 이벤트버스 정의
************************************************************************/
  $eventBus.off("FN_STUPDATE");
  $eventBus.on("FN_STUPDATE", () => {
    fnStUpdate();
  });
  $eventBus.off("FN_UPDATE");
  $eventBus.on("FN_UPDATE", () => {
    fnUpdate();
  });
  $eventBus.off("FN_INSERT");
  $eventBus.on("FN_INSERT", () => {
    fnInsert();
  });

  /************************************************************************
|    WATCH
************************************************************************/
  watch(
    [() => form.value.formValue2, () => form.value.formValue3],
    ([newVal2, newVal3]) => {
      if (newVal2) {
        form.value.formValue2 = formatDate(newVal2);
      }
      if (newVal3) {
        form.value.formValue3 = formatDate(newVal3);
      }
    }
  );

  onMounted(() => {
    if (pageType == "U") fnDetail();
  });
</script>
