<template>
  <div class="container">
    <div class="page-titleZone flex justify-between align-center">
      <p class="main-title flex80">연계정보 등록</p>
      <PageNavigation />
    </div>
    <div class="content content-box flex justify-between">
      <div class="right-content flex100">
        <div class="flex-column justify-between">
          <div class="table-zone">
            <p style="font-size: 2rem; font-weight: 800; margin-bottom: 10px">
              연계정보 등록
            </p>
            <table class="form-table">
              <!-- col 꼭 너비 기재해야함! 그래야 100%로 차지함 -->
              <colgroup>
                <col style="width: " />
                <col style="width: " />
                <col style="width: " />
                <col style="width: " />
              </colgroup>
              <tbody>
                <tr>
                  <th>연계 명</th>
                  <td colspan="3">
                    <input
                      id="conectNm"
                      type="text"
                      placeholder="연계 이름을 입력해 주세요"
                      class="half-input"
                      v-model="connectionDB.conectNm"
                    />
                  </td>
                </tr>
                <tr>
                  <th>DMBS</th>
                  <td colspan="3">
                    <select
                      id="databaseType"
                      @change="successAt = false"
                      class="square-select half-input"
                      v-model="connectionDB.databaseType"
                    >
                      <option
                        v-for="(itm, index) in databaseTypeList"
                        :key="index"
                        :value="itm.key"
                      >
                        {{ itm.value }}
                      </option>
                    </select>
                  </td>
                </tr>
                <tr>
                  <th>IP</th>
                  <td colspan="3">
                    <input
                      id="conectIp"
                      type="text"
                      @input="successAt = false"
                      class="half-input"
                      v-model="connectionDB.conectIp"
                      placeholder="127.0.0.1"
                    />
                  </td>
                </tr>
                <tr>
                  <th>PORT</th>
                  <td colspan="3">
                    <input
                      id="conectPort"
                      type="text"
                      @input="successAt = false"
                      class="half-input"
                      v-model="connectionDB.conectPort"
                    />
                  </td>
                </tr>
                <tr>
                  <th>DB 명</th>
                  <td colspan="3">
                    <input
                      id="databaseNm"
                      type="text"
                      @input="successAt = false"
                      class="half-input"
                      v-model="connectionDB.databaseNm"
                      placeholder="데이터베이스명 OR 스키마명"
                    />
                  </td>
                </tr>
                <tr>
                  <th>접속ID</th>
                  <td colspan="3">
                    <input
                      type="text"
                      class="half-input"
                      @input="successAt = false"
                      v-model="connectionDB.userId"
                      placeholder="접속 ID"
                    />
                  </td>
                </tr>
                <tr>
                  <th>접속PW</th>
                  <td colspan="3">
                    <input
                      type="password"
                      class="half-input"
                      @input="successAt = false"
                      v-model="connectionDB.userPassword"
                      placeholder="접속 PW"
                      autocomplete="new-password"
                    />
                  </td>
                </tr>
              </tbody>
            </table>
            <br />
            <p style="font-size: 2rem; font-weight: 800; margin-bottom: 10px">
              접속결과 확인
            </p>
            <div class="flex justify-end">
              <button
                class="blue-btn small-btn"
                @click="dataBaseConnectionCheck()"
              >
                접속 테스트
              </button>
            </div>
            <div class="table-zone">
              <table class="list-table">
                <colgroup>
                  <col width="10%" />
                  <col width="10%" />
                  <col width="80%" />
                </colgroup>
                <thead>
                  <tr>
                    <th>No</th>
                    <th>접속시간</th>
                    <th>접속결과</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="(itm, indx) in resultMessage" :key="indx">
                    <td>{{ indx + 1 }}</td>
                    <td>{{ itm.time }}</td>
                    <td>{{ itm.message }}</td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>
          <div class="flex5">
            <div class="flex justify-end">
              <button class="darkg-btn small-btn" @click="insertDbConnection()">
                수정
              </button>
              <button class="darkg-btn small-btn" @click="deleteDbConnection()">
                삭제
              </button>
              <button class="darkg-border-btn small-btn" @click="goBack()">
                목록
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";

export default {
  data() {
    return {
      // 커넥션 DB 오브젝트
      connectionDB: {},
      resultMessage: [],
      // 연계 성공여부
      successAt: false,
      databaseTypeList: [],
    };
  },
  methods: {
    // 공통코드 가져오기
    getCommnCode: async function (groupCode) {
      const response = await this.$getCommonCode(groupCode);
      return response;
    },
    // 초기화(데이터 베이스 타입 초기화)
    init: async function () {
      const vm = this;
      this.databaseTypeList = await this.$getDataBaseTypeList();
      this.connectionDB = Object.assign(
        {},
        this.$getDefaultJobGroup().connectionDb
      );
      this.connectionDB.databaseType = this.databaseTypeList.MARIADB.key;

      axios({
        url: "/data/selectDbConnectionOne.json",
        method: "post",
        headers: {
          "Content-Type": "application/json; charset=UTF-8",
        },
        data: { dbConectId: vm.$route.query.dbConnection },
      })
        .then(function (response) {
          vm.connectionDB = response.data.resultData.dbConnection;
        })
        .catch(function (error) {
          this.$showAlert(
            "에러 발생",
            "에러가 발생했습니다. 관리자에게 문의해 주세요."
          );
        });
    },
    // 연계가능 여부 테스트
    dataBaseConnectionCheck: function () {
      var vm = this;
      axios({
        url: "/data/dataBaseConnectionCheck.json",
        method: "post",
        headers: {
          "Content-Type": "application/json; charset=UTF-8",
        },
        data: vm.connectionDB,
      })
        .then(function (response) {
          if (response.data.checkMessage.success == true) {
            vm.successAt = true;
          } else {
            vm.successAt = false;
          }
          vm.$showAlert("결과내용", response.data.checkMessage.message);
          vm.resultMessage.push({
            time: vm.$getFullTime(),
            message: response.data.checkMessage.message,
            result: response.data.checkMessage.success
              ? "접속성공"
              : "접속실패",
          });
        })
        .catch(function (error) {
          this.$showAlert(
            "에러 발생",
            "에러가 발생했습니다. 관리자에게 문의해 주세요."
          );
        });
    },
    // 연계정보 저장
    insertDbConnection: async function () {
      var vm = this;

      if (vm.$isEmpty(this.connectionDB.conectNm)) {
        vm.$showAlert("경고", "연계제목은 필수입력입니다.");
        return false;
      } else if (this.successAt == false) {
        vm.$showAlert("경고", "정상적인 접속정보가 아닙니다.");
        return false;
      }

      if (vm.$showConfirm("확인", "연계 정보수정을 진행하시겠습니까?")) {
        alert("확인");
      } else {
        alert("취소");
      }

      axios({
        url: "/data/insertDbConnection.json",
        method: "post",
        headers: {
          "Content-Type": "application/json; charset=UTF-8",
        },
        data: vm.connectionDB,
      })
        .then(function (response) {
          vm.$showAlert("메세지", "수정되었습니다.");
          vm.$router.push("/dbConnectionList.page");
        })
        .catch(function (error) {
          this.$showAlert(
            "에러 발생",
            "에러가 발생했습니다. 관리자에게 문의해 주세요."
          );
        });
    },
    deleteDbConnection: async function () {
      var vm = this;
      axios({
        url: "/data/deleteConnectionDb.json",
        method: "post",
        headers: {
          "Content-Type": "application/json; charset=UTF-8",
        },
        data: vm.connectionDB,
      })
        .then(function (response) {
          vm.$showAlert("메세지", "삭제되었습니다.");
          vm.$router.push("/dbConnectionList.page");
        })
        .catch(function (error) {
          this.$showAlert(
            "에러 발생",
            "에러가 발생했습니다. 관리자에게 문의해 주세요."
          );
        });
    },
    goBack: function () {
      window.history.back();
    },
  },
  mounted() {
    this.init();
  },
};
</script>