<template>
  <div v-show="isModalOpen" class="modal-wrapper">
    <div class="modal-container large-modal">
      <div class="modal-title">
        <div class="flex justify-between align-center">
          <h2>API 연결</h2>
          <button class="close-btn" @click="$emit('fnCloseModal')">
            <svg-icon type="mdi" :width="20" :height="20" :path="closePath"></svg-icon>
          </button>
        </div>
      </div>
      <div class="modal-content-monthly">
        <div v-if="modalView == 'default'">
          <div class="content-titleZone">
            <p class="box-title">API 기본정보</p>
          </div>
          <table class="form-table">
            <colgroup>
              <col style="width: 15%" />
              <col style="width: 85%" />
            </colgroup>
            <tbody>
              <tr>
                <th>API URL</th>
                <td>
                  <input type="text" class="full-input" v-model="apiUrl" @change="fnApiUrlChange" />
                </td>
              </tr>
              <tr>
                <th>결과타입</th>
                <td>
                  <div class="flex">
                    <div class="flex15 pl0">
                      <input type="radio" name="json" id="json" value="1" class="chekck-type" v-model="jobItm.itm.type" />
                      <label for="json" class="chekcktype-label text-ct"> json </label>
                    </div>
                    <div class="flex15">
                      <input type="radio" name="xml" id="xml" value="2" class="chekck-type" v-model="jobItm.itm.type" />
                      <label for="xml" class="chekcktype-label text-ct"> xml </label>
                    </div>
                    <div class="flex15 pr0">
                      <input type="radio" name="seol" id="seol" value="3" class="chekck-type" v-model="jobItm.itm.type" />
                      <label for="seol" class="chekcktype-label text-ct"> seol </label>
                    </div>
                  </div>
                </td>
              </tr>
            </tbody>
          </table>
          <div class="content-titleZone flex justify-between align-center mt20">
            <p class="box-title">파라미터 목록</p>
            <div>
              <button class="blue-border-btn small-btn" @click="fnAddRow()"> 파라미터 추가 </button>
              <button v-if="apiUrl" class="blue-btn small-btn" @click="fnAutoCreate()"> 자동 생성 </button>
            </div>
          </div>
          <div style="height: 400px; overflow: auto">
            <table class="list-table" style="table-layout: fixed">
              <colgroup>
                <col width="10%" />
                <col width="30%" />
                <col width="50%" />
                <col width="10%" />
              </colgroup>
              <thead>
                <tr>
                  <th style="text-align: center">No</th>
                  <th style="text-align: center">Key</th>
                  <th style="text-align: center">Value</th>
                  <th style="text-align: center">삭제</th>
                </tr>
              </thead>
              <tbody>
                <template v-if="parameterList.length > 0">
                  <tr v-for="(item, index) in parameterList" :key="index">
                    <td style="text-align: center">{{ index + 1 }}</td>
                    <td>
                      <input type="text" class="full-input" v-model.trim="item.key" />
                    </td>
                    <td>
                      <input type="text" class="full-input" v-model.trim="item.value" />
                    </td>
                    <td>
                      <button class="cbtnDelete" @click="fnDeleteRow(item)">
                        <img src="../../../../resources/img/delete.png" alt="삭제" />
                      </button>
                    </td>
                  </tr>
                </template>
                <tr v-else>
                  <td colspan="4">등록된 데이터가 없습니다.</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
        <div v-if="modalView == 'preview'">
          <div class="content-titleZone flex justify-between align-center">
            <p class="box-title">미리보기</p>
            <button type="button" class="blue-border-btn small-btn" @click="fnDataKeySelect"> 조회 </button>
          </div>
          <table class="form-table">
            <colgroup>
              <col style="width: 15%" />
              <col style="width: 85%" />
            </colgroup>
            <tbody>
              <tr>
                <th>사용할 데이터</th>
                <td>
                  <select v-model="selectKey">
                    <template v-if="apiResponseKeys.length > 0">
                      <option value="">사용할 데이터를 선택하세요.</option>
                      <option v-for="(key, index) of apiResponseKeys" :key="index" :value="key"> {{ key }} </option>
                    </template>
                    <option v-else value="">전체 조회</option>
                  </select>
                </td>
              </tr>
            </tbody>
          </table>
          <div class="content-titleZone flex justify-between align-center mt20">
            <p class="box-title"> 데이터셋 <small> (총 ROW: {{ rowData.length > 1 ? rowData.length : 0 }}개) </small>
            </p>
          </div>
          <table class="list-table table-flow">
            <template v-if="!$isEmpty(dataTable)">
              <thead>
                <tr>
                  <th>No</th>
                  <th v-for="(rowKey, index) of rowKeys" :key="index"> {{ rowKey }} </th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(items, indexI) of rowData" :key="indexI">
                  <td>{{ indexI + 1 }}</td>
                  <td v-for="(item, indexJ) of items" :key="indexJ"> {{ item }} </td>
                </tr>
              </tbody>
            </template>
            <tr v-else>
              <td>등록된 데이터가 없습니다.</td>
            </tr>
          </table>
        </div>
      </div>
      <div class="modal-end" style="text-align: right">
        <button type="button" :class="{
          'small-btn': true,
          'blue-btn': modalView == 'default',
          'blue-border-btn': modalView == 'preview',
        }" @click="fnPrevNextPage">
          <span v-if="modalView == 'preview'">이전</span>
          <span v-if="modalView == 'default'">다음</span>
        </button>
        <button type="button" v-if="modalView == 'preview'" class="blue-btn small-btn" @click="fnSave"> 저장 </button>
        <button type="button" class="blue-border-btn small-btn" @click="$emit('fnCloseModal')"> 취소 </button>
      </div>
    </div>
  </div>
</template>
<script>
import SvgIcon from "@jamescoyle/vue-icon";
import { mdiClose } from "@mdi/js";
import ApiRusultCus from "./apiRusultCus.vue";
import axios from "axios";

export default {
  components: {
    SvgIcon: SvgIcon,
    ApiRusultCus: ApiRusultCus,
  },
  props: {
    openPopup: {
      type: Boolean,
      default: false,
    },
    jobItem: {
      type: Boolean,
      default: null,
    },
  },
  data() {
    return {
      isModalOpen: this.openPopup,
      closePath: mdiClose,
      jobItm: this.jobItem,

      modalView: "default",

      apiUrl: null,
      parameterList: [],

      apiResponse: null,
      apiResponseKeys: [],
      selectKey: "",

      dataTable: {},

      rowData: [],
      rowKeys: [],
    };
  },
  mounted() {
    this.init();
  },
  methods: {
    // 초기화 function
    async init() {
      this.modalView = "default";
      this.apiUrl = null;
      this.parameterList = [];
      this.apiResponseKeys = [];
      this.selectKey = "";
      this.dataTable = {};
      this.rowData = [];
      this.rowKeys = [];

      if (!this.$isEmpty(this.jobItm)) {
        let item = this.jobItm.itm;
        if (item.url != null && item.url != "") {
          if (item.url.indexOf("?") != -1) {
            item.url.substring(0, item.url.indexOf("?"));
          }
          let params = "";
          for (let param of item.params) {
            if (params != "") {
              params += "&";
            }
            params += param.key + "=" + param.value;
          }
          this.apiUrl = item.url + "?" + params;

          for (let param of item.params) {
            this.parameterList.push({
              index: param.index,
              key: param.key,
              value: param.value,
              addMonth: 0,
            });
          }
        }
      } else {
        this.jobItm = Object.assign({}, this.$getDefaultJobGroup().node);
        this.jobItm.itm = Object.assign(
          {},
          this.$getDefaultJobGroup().connectionApi
        );
      }
    },

    // API URL 변경
    fnApiUrlChange() {
      this.parameterList = []; // 파라미터 목록 초기화

      // 미리보기 페이지 데이터 초기화
      this.selectKey = "";
      this.dataTable = {};
      this.rowData = [];
      this.rowKeys = [];
    },

    // 파라미터 행 추가
    fnAddRow() {
      this.parameterList.push({
        index: this.parameterList.length + 1,
        key: null,
        value: null,
        addMonth: 0,
      });
    },
    // 파라미터 행 삭제
    fnDeleteRow(item) {
      this.parameterList = this.parameterList.filter(
        (parameter) => parameter !== item
      );
    },

    // 자동 생성 버튼
    async fnAutoCreate() {
      // 덮어쓰기 경고
      if (this.parameterList.length > 0) {
        let isChecked = await this.$showConfirm(
          "경고",
          "자동생성 실행 시, 기존에 작성한 파라미터가 삭제됩니다. 그래도 실행하시겠습니까?"
        );
        if (!isChecked) {
          return;
        } else {
          this.parameterList = []; // 파라미터 목록 초기화
        }
      }

      // 실행
      let apiUrl = this.apiUrl;
      if (apiUrl) {
        let parameters = apiUrl.substring(apiUrl.indexOf("?") + 1);
        if (parameters.length > 1) {
          let params = parameters.split("&");
          for (let param of params) {
            let paramIndex = param.indexOf("=");
            this.parameterList.push({
              index: this.parameterList.length + 1,
              key: param.substring(0, paramIndex),
              value: param.substring(paramIndex + 1),
              addMonth: 0,
            });
          }
        }
      }
    },
    // 셀 크기
    fnColWidth(keys) {
      return `width: ${100 / (keys + 1)}%`;
    },

    // 이전/다음 버튼
    fnPrevNextPage() {
      if (this.modalView == "default") {
        // 데이터 조회
        this.apiRequestTest();
      } else if (this.modalView == "preview") {
        // 데이터 초기화
        this.apiResponseKeys = [];
        this.dataTable = {};
        this.rowKeys = [];
        this.rowData = [];

        // 모달창 변경
        this.modalView = "default";
      }
    },
    // 다음 버튼
    apiRequestTest() {
      const vm = this;
      if (vm.parameterList.length < 1) {
        vm.$showAlert(
          "경고",
          "파라미터가 비어있습니다. 파라미터를 입력해 주세요."
        );
        return;
      }
      // 데이터 세팅
      vm.jobItm.itm.url = vm.apiUrl.substring(0, vm.apiUrl.indexOf("?"));
      vm.jobItm.itm.params = vm.parameterList;
      // 실행
      axios({
        url: "/apiRequestTest.json",
        method: "post",
        headers: {
          "Content-Type": "application/json; charset=UTF-8",
        },
        data: vm.jobItm.itm,
      })
        .then((response) => {
          vm.apiResponseKeys = response.data.key;
          vm.modalView = "preview"; // 모달창 변경
        })
        .catch((error) => {
          vm.$showAlert(
            "결과내용",
            "응답이 없습니다. 파라미터를 확인해 주세요."
          );
        });
    },
    getType(target) {
      return Object.prototype.toString.call(target).slice(8, -1);
    },
    // 조회 버튼
    fnDataKeySelect() {
      if (this.apiResponseKeys.length > 0 && (this.selectKey == null || this.selectKey == "")) {
        this.$showAlert("경고", "사용할 데이터를 선택해 주세요.");
        return;
      }
      this.jobItm.itm.depth = this.selectKey;

      // 데이터 세팅
      this.jobItm.itm.url = this.apiUrl.substring(0, this.apiUrl.indexOf("?"));

      // 실행
      axios({
        url: "/getApiDataTable.json",
        method: "post",
        headers: {
          "Content-Type": "application/json; charset=UTF-8",
        },
        data: this.jobItm.itm,
      })
        .then((response) => {
          let result = response.data;
          this.dataTable = result;
          this.rowKeys = []; // 초기화
          for (let columnData of result.columnDatas) {
            this.rowKeys.push(columnData.columnNm);
            // displayColumnNm 초기값 설정
            columnData.displyColumnNm = columnData.orginlColumnNm;
          }
          this.rowData = result.rowData;
        })
        .catch((error) => {
          this.$showAlert(
            "결과내용",
            "응답이 없습니다. 데이터를 확인해 주세요."
          );
        });
    },
    // 저장 버튼
    fnSave() {
      // 유효성 검사
      if (this.$isEmpty(this.apiUrl)) {
        this.$showAlert("경고", "API URL을 입력해 주세요.");
        return false;
      }
      if (this.$isEmpty(this.dataTable)) {
        this.$showAlert("경고", "사용할 데이터를 조회해 주세요.");
        return false;
      }
      // 데이터 세팅
      this.jobItm.dataTable = this.dataTable;
      // 실행
      let jobItem = this.jobItm;
      this.$emit("fnSaveSetup", jobItem);
    },
  },
};
</script>
<style scoped>
.cbtnDelete {
  width: 18px;
  height: 18px;
}

.cbtnDelete img {
  width: 100%;
}

.table-flow {
  width: 100%;
  word-wrap: break-word;
}
</style>