<template>
  <div class="container">
    <div class="page-titleZone flex justify-between align-center">
      <p class="main-title flex80">OpenAPI Key 관리</p>
    </div>
    <div class="content-wrap flex100">
      <div class="content flex-column">
        <div class="flex45">
          <div class="content-titleZone">
            <p class="box-title">OpenAPI Key 리스트</p>
          </div>
          <div class="flex" style="margin-right: auto; margin-bottom: 10px; justify-content: flex-end">
            <button class="blue-btn large-btn" id="confirmOk" style="width:120px" @click="fnModal">키 생성</button>
          </div>
          <div class="flex justify-between align-center">
            <div class="count-zone">
              <p> 총 <span>{{ search.totalRows }}</span>건 </p>
            </div>
          </div>
          <div class="table-zone">
            <table class="list-table">
              <colgroup>
                <col style="width: 10%" />
                <col style="width: 30%" />
                <col style="width: 15%" />
                <col style="width: 10%" />
                <col style="width: 10%" />
                <col style="width: 15%" />
                <col style="width: 10%" />
              </colgroup>
              <thead>
                <tr>
                  <th>No</th>
                  <th>Key</th>
                  <th>유효일자</th>
                  <th>상태</th>
                  <th>생성자</th>
                  <th>생성일자</th>
                  <th></th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(itm, indx) in apiKeyList" :key="indx">
                  <td>{{ this.search.totalRows - indx - (this.search.currentPage - 1) * this.search.perPage }}</td>
                  <td><span class="mr10">{{ itm.api_key }}</span><button class="blue-border-btn set-btn" @click="copyText(itm.api_key)">복사</button></td>
                  <td>{{ itm.bgnde }} ~ {{ itm.endde }}</td>
                  <td :class="itm.status">{{ getStatusNm(itm.status) }}</td>
                  <td>{{ itm.creat_id }}</td>
                  <td>{{ itm.creat_dt }}</td>
                  <td><button class="red-border-btn small-btn" @click="fnDelApiKey(itm)">삭제</button></td>
                </tr>
              </tbody>
            </table>
          </div>
          <PaginationButton v-model:currentPage="search.currentPage" :perPage="search.perPage" :totalCount="search.totalRows" :maxRange="5" :click="fnSelectKeyList" />
        </div>
      </div>
    </div>
  </div>
  <div v-show="isAddModalOpen" class="modal-wrapper">
    <div class="modal-wrapper">
      <div class="modal-container small-modal">
        <div class="modal-title">
          <div class="flex justify-between align-center">
            <h2>Open API Key 생성</h2>
            <button class="close-btn" @click="fnModal">X</button>
          </div>
        </div>
        <div class="modal-content-monthly">
          <p>key 유효 기간 설정</p>
          <div class="flex justify-center align-center mt10" style="gap: 10px;">
            <p>시작기간: <input type="date" v-model="startDate" @input="fnValidate('start')" /></p>
            <p>~</p>
            <p>종료기간: <input type="date" v-model="endDate" @input="fnValidate('end')" /></p>
          </div>
        </div>
        <div class="modal-end flex justify-center">
          <button class="gray-border-btn small-btn" @click="fnModal"> 취소 </button>
          <button class="blue-btn small-btn" @click="fnCreateKey"> 생성 </button>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import axios from "axios";
import PaginationButton from "../../component/PaginationButton.vue";

export default {
  data() {
    return {
      // 검색 객체
      search: _.cloneDeep(this.$getDefaultSerchVO()),

      isAddModalOpen: false,
      apiKeyList: [],

      startDate: "",
      endDate: "",

    };
  },
  created: function () {
    this.fnSelectKeyList();
  },
  methods: {
    fnCreateValidation() {

      if (this.startDate == "") {
        this.$showAlert("경고", "시작일을 입력해 주세요.");
        return false;
      }
      if (this.endDate == "") {
        this.$showAlert("경고", "종료일을 입력해 주세요.");
        return false;
      }
      return true; // 모든 검증이 통과할 경우 true 반환
    },
    fnCreateKey: function () {
      if (this.fnCreateValidation()) {
        const vm = this;
        const data = {
          bgnde: this.startDate,
          endde: this.endDate,
        };
        axios({
          url: "/export/openApiKeyCreate.json",
          method: "post",
          headers: {
            "Content-Type": "application/json; charset=UTF-8",
          },
          data: data,
        }).then(function (response) {
          console.log(response);
          if (response.data.checkMessage.success) {
            vm.$showAlert(
              "success",
              "openAPI 키가 생성되었습니다."
            );
            vm.fnModal();
            vm.fnSelectKeyList();
          }
        }).catch(function (error) {
          vm.$showAlert(
            "에러 발생",
            "에러가 발생했습니다. 관리자에게 문의해 주세요."
          );
        });
      }
    },
    // 리스트 조회
    fnSelectKeyList: function () {
      const vm = this;
      axios({
        url: "/export/openApiKeySelectList.json",
        method: "post",
        headers: {
          "Content-Type": "application/json; charset=UTF-8",
        },
        data: JSON.stringify(vm.search),
      }).then(function (response) {
        console.log(response);
        if (response.data.checkMessage.success) {
          vm.apiKeyList = response.data.resultData.list.apiKeyList;
          vm.search.totalRows = response.data.resultData.list.totalRows;

        }
      }).catch(function (error) {
        vm.$showAlert(
          "에러 발생",
          "에러가 발생했습니다. 관리자에게 문의해 주세요."
        );
      });
    },
    copyText(text) {
      navigator.clipboard.writeText(text)
        .then(() => {
          this.$showAlert("성공", "텍스트가 클립보드에 복사되었습니다.");
        })
        .catch((error) => {
          this.$showAlert("오류", "텍스트 복사에 실패했습니다. 다시 시도해 주세요.");
          console.error("복사 오류:", error);
        });
    },
    // API Key 삭제
    fnDelApiKey: function (item) {
      const vm = this;
      axios({
        url: "/export/openApiKeyDelete.json",
        method: "post",
        headers: {
          "Content-Type": "application/json; charset=UTF-8",
        },
        data: item,
      }).then(function (response) {
        console.log(response);
        if (response.data.checkMessage.success) {
          vm.$showAlert(
            "success",
            "openAPI 키가 삭제되었습니다."
          );
          vm.fnSelectKeyList();

        }
      }).catch(function (error) {
        vm.$showAlert(
          "에러 발생",
          "에러가 발생했습니다. 관리자에게 문의해 주세요."
        );
      });
    },
    // 모달 동작 로직
    fnModal: function () {
      // this.fnToday();
      this.startDate = "";
      this.endDate = "";
      this.isAddModalOpen = !this.isAddModalOpen;
    },
    // 오늘 날짜
    // fnToday: function() {
    //     const today = new Date().toISOString().split('T')[0]; // YYYY-MM-DD 형식으로 변환
    //     this.startDate = today;
    //     this.endDate = today; // 종료일도 오늘로 설정
    // },
    // 날짜 유효성 검사
    fnValidate: function (type) {
      if (type === "start" && this.endDate !== "") {
        if (this.startDate > this.endDate) {
          this.$showAlert("경고", "시작일은 종료일보다 클 수 없습니다.");
          this.startDate = "";
        }
      } else if (type === "end" && this.startDate !== "") {
        if (this.startDate > this.endDate) {
          this.$showAlert("경고", "종료일은 시작일보다 작을 수 없습니다.");
          this.endDate = "";
        }
      }
    },
    getStatusNm(status) {
      if (status === "wait") {
        return "대기중";
      } else if (status === "use") {
        return "사용중";
      } else {
        return "만료됨";
      }
    },
  },
  watch: {
    // isAddModalOpen: function() {
    //     if (this.isAddModalOpen) {
    //         this.fnToday(); // 모달이 열릴 때 오늘 날짜 설정
    //     }
    // }
  },
  components: {
    PaginationButton,
  },
};
</script>
<style scoped>
.wait {
  font-weight: bold;
  color: #f1c40f;
}

.use {
  font-weight: bold;
  color: #2ecc71;
}

.expire {
  font-weight: bold;
  color: #e74c3c;
}
</style>