<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">기본 정보</p>
          </div>
          <div>
            <table class="form-table">
              <colgroup>
                <col style="width: 15%" />
                <col style="width: 35%" />
                <col style="width: 15%" />
                <col style="width: 35%" />
              </colgroup>
              <tbody>
                <tr>
                  <th>송신기관 코드</th>
                  <td><input type="text" v-model="job.lafCode" class="full-input" placeholder="송신기관 코드를 입력해 주세요."></td>
                  <th>업무구분 코드</th>
                  <td><input type="text" v-model="job.taskCode" class="full-input" placeholder="업무구분 코드를 입력해 주세요."></td>
                </tr>
                <tr>
                  <th>테이블 명</th>
                  <td><input type="text" v-model="job.tableName" class="full-input" placeholder="테이블 명을 입력해 주세요."></td>
                  <th>인터페이스 ID</th>
                  <td><input type="text" v-model="job.ifId" class="full-input" placeholder="인터페이스 ID를 입력해 주세요."></td>
                </tr>
              </tbody>
            </table>
          </div>
          <div class="flex justify-between">
            <div class="flex50 pl0">
              <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('header')">헤더 정보 추가</button>
                </div>
              </div>
              <div style="height: 300px; 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">키</th>
                      <th style="text-align: center">값</th>
                      <th style="text-align: center">비고</th>
                    </tr>
                  </thead>
                  <tbody>
                    <tr v-for="(item, idx) in job.headers" :key="idx">
                      <td style="text-align: center">{{ idx + 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 v-if="!item.required" class="cbtnDelete" @click="fnDelRow('header', item)">
                          <img src="../../../resources/img/delete.png" alt="삭제" />
                        </button>
                      </td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </div>
            <div class="flex50 pr0">
              <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('body')">바디 정보 추가</button>
                </div>
              </div>
              <div style="height: 300px; 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">키</th>
                      <th style="text-align: center">값</th>
                      <th style="text-align: center">비고</th>
                    </tr>
                  </thead>
                  <tbody>
                    <tr v-for="(item, idx) in job.bodys" :key="idx">
                      <td style="text-align: center">{{ idx + 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="fnDelRow('body', item)">
                          <img src="../../../resources/img/delete.png" alt="삭제" />
                        </button>
                      </td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        </div>
        <div v-if="modalView == 'preview'">
          <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>
          <div style="height: 400px; overflow: auto">
            <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>
      <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>
// IMPORTS
import SvgIcon from "@jamescoyle/vue-icon";
import { mdiClose } from "@mdi/js";
import axios from "axios";

export default {
  components: {
    SvgIcon: SvgIcon,
  },

  props: {
    openPopup: {
      type: Boolean,
      default: false,
    },
    jobItem: {
      type: Boolean,
      default: null,
    },
  },

  data() {
    return {
      // ICON
      closePath: mdiClose,

      // DEFAULT
      isModalOpen: this.openPopup,
      modalView: "default",

      dataTable: {},
      rowData: [],
      rowKeys: [],

      job: Object.assign({}, this.$getDefaultJobGroup().connectionEhojo),

      // 기본값
      defaultHeaders: [
        { index: 1, key: "transfGramNo", value: null, required: false },
        { index: 2, key: "userDeptCode", value: null, required: false },
        { index: 3, key: "userName", value: null, required: false },
      ],
      defaultBodys: [
        { index: 1, key: "curPage", value: 1, required: false },
        { index: 2, key: "pageSize", value: 3000, required: false },
      ],
    };
  },

  mounted() {
    this.init();
  },

  methods: {
    // 초기화 function
    init() {
      this.modalView = "default";

      if (this.jobItem.itm_id != null) {
        this.job = this.jobItem.itm;
        this.dataTable = this.jobItem.dataTable;
        this.rowData = this.dataTable.rowData;
        for (let columnData of this.dataTable.columnDatas) {
          this.rowKeys.push(columnData.columnNm);
          // displayColumnNm 초기값 설정
          columnData.displyColumnNm = columnData.orginlColumnNm;
        }
      } else {
        this.dataTable = {};
        this.rowData = [];
        this.rowKeys = [];

        // 헤더, 바디 기본값 설정
        this.job.headers = this.defaultHeaders;
        this.job.bodys = this.defaultBodys;
      }
    },

    // ##파라미터
    // 행 추가
    fnAddRow(type) {
      if (type == 'header') {
        this.job.headers.push({
          index: this.job.headers.length + 1,
          key: null,
          value: null,
          required: false
        });
      } else if (type == 'body') {
        this.job.bodys.push({
          index: this.job.bodys.length + 1,
          key: null,
          value: null,
          required: false
        });
      }
    },
    // 행 삭제
    fnDelRow(type, item) {
      if (type == 'header') {
        this.job.headers = this.job.headers.filter(parameter => parameter !== item);
      } else if (type == 'body') {
        this.job.bodys = this.job.bodys.filter(parameter => parameter !== item);
      }
    },

    // 유효성 검사
    chkValidations() {
      // 기본 정보
      if (this.$isEmpty(this.job.lafCode)) {
        this.$showAlert("경고", "송신기관 코드를 입력하지 않았습니다. 송신기관 코드를 입력해 주세요.");
        return false;
      }
      if (this.$isEmpty(this.job.taskCode)) {
        this.$showAlert("경고", "업무구분 코드를 입력하지 않았습니다. 업무구분 코드를 입력해 주세요.");
        return false;
      }
      if (this.$isEmpty(this.job.tableName)) {
        this.$showAlert("경고", "테이블 명을 입력하지 않았습니다. 테이블 명을 입력해 주세요.");
        return false;
      }
      if (this.$isEmpty(this.job.ifId)) {
        this.$showAlert("경고", "인터페이스 ID를 입력하지 않았습니다. 인터페이스 ID를 입력해 주세요.");
        return false;
      }

      // 헤더 정보
      for (let item of this.defaultHeaders) {
        if (item.required) {
          if (this.$isEmpty(item.value)) {
            this.$showAlert("경고", "헤더 정보 중 필수 입력값을 입력하지 않았습니다. 필수 입력값을 입력해 주세요.");
            return false;
          }
        }
      }

      return true;
    },

    // ##버튼
    // 이전/다음 버튼
    fnPrevNextPage() {
      if (this.modalView == "default") {
        if (!this.chkValidations()) { return; }
        this.fnRun();
      } else if (this.modalView == "preview") {
        // defaultData 초기화
        this.job.ifId = null;

        this.dataTable = {};
        this.rowKeys = [];
        this.rowData = [];

        // 모달창 변경
        this.modalView = "default";
      }
    },
    // 조회
    fnRun() {
      const vm = this;
      // 실행
      axios({
        url: "/openfiscal.json",
        method: "post",
        headers: { "Content-Type": "application/json; charset=UTF-8" },
        data: vm.job,
      })
        .then((response) => {
          if (response.data.checkMessage.status == 0) {
            let result = response.data.resultData.dataTable;
            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;

            // 모달창 변경
            this.modalView = "preview";
          } else {
            this.$showAlert("알람", response.data.checkMessage.message);
          }
        })
        .catch((error) => {
          vm.$showAlert("경고", "응답이 없습니다. 입력한 정보를 확인해 주세요.");
        });
    },
    // 저장 버튼
    fnSave() {
      // 데이터 세팅
      let jobItm = this.jobItem;
      jobItm.itm = this.job;
      jobItm.dataTable = this.dataTable;

      // 실행
      this.$emit("fnSaveSetup", jobItm);
    },
  }
}
</script>
<style scoped>
.cbtnDelete {
  width: 18px;
  height: 18px;
}

.cbtnDelete img {
  width: 100%;
}
</style>