<template>
  <div class="container">
    <div class="page-titleZone flex justify-between align-center">
      <p class="main-title flex80">데이터셋 등록</p>
      <PageNavigation />
    </div>
    <div class="content-wrap">
      <div class="content content-box flex justify-between">
        <div class="right-content flex100">
          <div class="flex-column justify-between">
            <div class="table-zone">
              <table class="form-table">
                <tbody>
                  <tr>
                    <th>제목</th>
                    <td colspan="3">
                      <input type="text" placeholder="데이터셋 제목을 입력하세요" class="full-input" v-model="datasetPost.post_sj" />
                    </td>
                  </tr>
                  <tr>
                    <th>테이블 명(한글)</th>
                    <td colspan="3">
                      <input type="text" class="half-input" v-model="dataset.tableNmKr" />
                    </td>
                  </tr>
                  <tr>
                    <th>테이블 명(영문)</th>
                    <td colspan="3">
                      <input type="text" class="half-input" v-model="dataset.tableNm" @input="duplicationTableNameAt = false" />
                      <button class="green-border-btn small-btn" @click="tableNameCheck"> 중복확인 </button>
                    </td>
                  </tr>
                  <tr>
                    <th>카테고리</th>
                    <td colspan="3">
                      <select name="ctgry" id="ctgry" class="square-select half-input" v-model="datasetPost.ctgry_id">
                        <option v-for="(item, indx) in categoryList" :key="indx" :value="item.cmmnCode"> {{ item.codeNm }} </option>
                      </select>
                    </td>
                  </tr>
                  <tr>
                    <th>공개여부</th>
                    <td colspan="3">
                      <div class="input-container flex">
                        <label class="radio-label">
                          <input type="radio" name="public_at" class="custom-radiobox" :value="true" v-model="datasetPost.public_at" />
                          <span>공개</span>
                        </label>
                        <label class="radio-label">
                          <input type="radio" name="public_at" class="custom-radiobox" :value="false" v-model="datasetPost.public_at" />
                          <span>비공개</span>
                        </label>
                      </div>
                    </td>
                  </tr>
                  <tr>
                    <th>목표 DB</th>
                    <td colspan="3">
                      <input type="text" class="half-input" disabled v-if="targetDBConnection.conectNm != null" :value="targetDBConnection.conectNm +
                        '(' +
                        targetDBConnection.conectIp +
                        ')'
                        " />
                      <input type="text" class="half-input" disabled v-else />
                      <button class="green-border-btn small-btn" @click="dbConSearchOpen(true)"> 검색 </button>
                    </td>
                  </tr>
                  <tr>
                    <th>검색키워드</th>
                    <td colspan="3">
                      <input type="text" class="half-input" v-model="keyword" @keyup.enter="addKwrd" />
                      <button class="green-border-btn small-btn" @click="addKwrd"> 추가 </button>
                      <div class="tagBox">
                        <ul class="flex">
                          <li v-for="(keyword, i) in keywordList" :key="i" class="file-list"> {{ keyword }} <button class="del-icon-btn" @click="keywordDelete(i)">
                              <svg-icon type="mdi" :width="15" :height="15" :path="this.$getIconPath('mdiTrashCan')"></svg-icon>
                            </button>
                          </li>
                        </ul>
                      </div>
                    </td>
                  </tr>
                  <tr>
                    <th>내용</th>
                    <td colspan="3">
                      <quill-editor style="height: 170px" @change="onEditorChange" contentType="html" :options="editorOption"></quill-editor>
                    </td>
                  </tr>
                  <tr>
                    <th>데이터 출처</th>
                    <td colspan="3">
                      <input type="text" class="half-input" v-model="datasetPost.origin" />
                    </td>
                  </tr>
                  <tr>
                    <th>데이터셋</th>
                    <td colspan="3">
                      <input type="text" class="half-input" v-model="selectedDataset" readonly />
                      <button class="green-border-btn small-btn" @click="createData()"> 파일선택 </button>
                    </td>
                  </tr>
                  <tr>
                    <th>첨부파일</th>
                    <td colspan="3">
                      <div class="file_input">
                        <form name="fileForm" id="fileForm" method="post" enctype="multipart/form-data">
                          <label for="fileUp" class="green-border-btn small-btn">파일선택</label>
                          <input type="file" id="fileUp" @change="fileChange()" multiple style="display: none" />
                        </form>
                      </div>
                      <div class="filename">
                        <ul>
                          <li v-for="(file, i) in tempFile" :key="i">
                            <span>{{ file.name }}</span>
                          </li>
                        </ul>
                      </div>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
            <div class="flex5">
              <div class="flex justify-end">
                <button class="darkg-btn small-btn" @click="activateInsert">등록</button>
                <button class="darkg-border-btn small-btn" @click="goBack()">취소</button>
              </div>
            </div>
          </div>
          <!-- <div class="flex-column justify-between">
                </div> -->
        </div>
      </div>
    </div>
    <DBConSearch :openPopup="openModal" @modalclose="dbConSearchOpen" @selectItm="selectDbcon" />
    <!-- <DatabaseConnection :openPopup="popupToggls.DB" @closePopup="closePopup" /> -->
    <FileSelect :openPopup="popupToggls.FILE" :mode="'fileRead'" @closePopup2="closePopup" />
  </div>
</template>
<script>
//import { quillEditor } from "vue-quill-editor";
import DBConSearch from "../../component/dataComponent/DbConnectionSearchModal.vue";
import DatabaseConnection from "../../component/connection/itm/databaseConnection.vue";
import FileSelect from "../../component/connection/itm/fileSelect.vue";
import axios from "axios";

export default {
  data() {
    return {
      //에디터 옵션
      editorOption: {
        placeholder: "내용 입력하세요.",
      },
      openModal: false,
      dataset: Object.assign({}, this.$getDefaultObject().dataset),
      targetDBConnection: Object.assign(
        {},
        this.$getDefaultObject().connectionDb
      ),
      datasetPost: Object.assign({}, this.$getDefaultObject().datasetPost),
      JobItm: Object.assign({}, this.$getDefaultObject().jobItem),
      keyword: "",
      createItemType: "FILE",
      categoryList: [],
      popupToggls: {
        DB: false,
        API: false,
        FILE: false,
      },
      connection: {
        host_code: null,
        path: null,
        depth: null,
        type: null,
      },
      duplicationTableNameAt: false,

      //input type File에서 선택된 파일 목록
      tempFile: [],

      selectedDataset: "",
    };
  },
  methods: {
    goBack() {
      window.history.back();
    },

    // db커넥션 선택창 호출
    dbConSearchOpen(val) {
      this.openModal = val;
    },
    // 선택된 db커넥션 전달 받음
    selectDbcon(dbcon) {
      this.targetDBConnection = dbcon;
    },

    // 키워드 추가
    addKwrd() {
      //입력한 키워드가 없을 때
      if (this.keyword == null || this.keyword == "") return false;

      //등록할 키워드값이 null 값일 때
      if (this.datasetPost.kwrd == null) {
        this.datasetPost.kwrd = "";
      }

      //등록할 키워드값이 존재할 때 => ','입력
      if (
        this.datasetPost.kwrd.length > 0 ||
        this.datasetPost.kwrd.indexOf(",") > -1
      ) {
        this.datasetPost.kwrd += ",";
      }

      //입력한 키워드 값을 등록할 키워드값에 추가
      this.datasetPost.kwrd += this.keyword;

      //키워드 입력창 초기화
      this.keyword = "";
    },

    //keyword 삭제
    keywordDelete(index) {
      //등록할 keyword 목록 가지고 오기
      var keywordList = this.keywordList;
      //keyword 목록에서 특정 index 삭제
      keywordList.splice(index, 1);

      //등록할 keyword 초기화
      this.datasetPost.kwrd = "";

      //삭제된 keyword 빼고 재할당
      for (var i = 0; i < keywordList.length; i++) {
        //등록할 키워드값이 존재할 때 => ','입력
        if (
          this.datasetPost.kwrd.length > 0 ||
          this.datasetPost.kwrd.indexOf(",") > -1
        ) {
          this.datasetPost.kwrd += ",";
        }

        //입력한 키워드 값을 등록할 키워드값에 추가
        this.datasetPost.kwrd += keywordList[i];
      }
    },

    closePopup(indx, JobItm, connection) {
      if (indx == 0) {
        this.popupToggls.DB = false;
        this.popupToggls.FILE = false;
        this.JobItm = JobItm;
        this.connection = connection;
        this.JobItm.itm.viewMode = false;
      }
      this.selectedDataset = JobItm.itm.fileName;
    },

    // 데이터 생성
    createData() {
      if (this.createItemType == "DB") {
        this.popupToggls.DB = true;
      } else if (this.createItemType == "API") {
      } else if (this.createItemType == "FILE") {
        this.popupToggls.FILE = true;
      }
    },

    // 테이블 네임 중복체크
    tableNameCheck() {
      let vm = this;
      if (this.$isEmpty(this.dataset.tableNm)) {
        this.$showAlert("경고", "테이블 영문명을 입력해 주세요");
        return;
      } else if (this.$isEmpty(this.targetDBConnection.conectIp)) {
        this.$showAlert("경고", "목표DB를 선택해 주세요");
        return;
      }

      this.targetDBConnection.loadAt = true;

      var reqeustData = {
        tableNm: this.dataset.tableNm,
        connectionDB: this.targetDBConnection,
      };

      axios({
        url: "/data/checkTableName.json",
        method: "post",
        headers: {
          "Content-Type": "application/json; charset=UTF-8",
        },
        data: reqeustData,
      })
        .then(function (response) {
          if (response.data.checkMessage.success) {
            vm.$showAlert("message", "등록가능한 테이블입니다.");
            vm.duplicationTableNameAt = true;
          } else {
            vm.$showAlert("경고", "중복테이블이 존재합니다.");
            vm.duplicationTableNameAt = false;
          }
        })
        .catch(function (error) {
          this.$showAlert(
            "에러 발생",
            "에러가 발생했습니다. 관리자에게 문의해 주세요."
          );
        });
    },

    activateInsert() {
      let vm = this;
      // 벨리데이션 체크
      if (
        !vm.datasetPost.post_sj ||
        vm.datasetPost.post_sj.trim().length === 0
      ) {
        vm.$showAlert("경고", "제목을 입력해주세요.");
        return false;
      } else if (
        !vm.dataset.tableNmKr ||
        vm.dataset.tableNmKr.trim().length === 0
      ) {
        vm.$showAlert("경고", "테이블 명을 입력해주세요.");
        return false;
      }
      // 테이블 영문명
      else if (!vm.dataset.tableNm || vm.dataset.tableNm.trim().length === 0) {
        vm.$showAlert("경고", "테이블 영문명을 입력해주세요.");
        return false;
      } else if (vm.duplicationTableNameAt !== true) {
        vm.$showAlert("경고", "중복 테이블 검사를 해주세요.");
        return false;
      }
      //카테고리
      else if (!vm.datasetPost.ctgry_id) {
        vm.$showAlert("경고", "카테고리를 선택해주세요.");
        return false;
      }
      //내용
      else if (
        !vm.datasetPost.post_dc ||
        vm.datasetPost.post_dc.trim().length === 0
      ) {
        vm.$showAlert("경고", "내용을 입력해주세요.");
        return false;
      }
      //데이터셋
      else if (vm.JobItm.dataTable.columnDatas.length === 0) {
        vm.$showAlert("경고", "데이터셋을 입력해주세요.");
        return false;
      }

      if (vm.tempFile.length !== 0) {
        vm.fileUpload();
      } else {
        vm.insertDataPost();
      }
    },

    // 데이터 포스트 등록
    insertDataPost() {
      const vm = this;

      delete vm.JobItm.dataTable.originalColumnDatas;

      this.datasetPost.dept_code = this.$store.state.loginUser.dept_code;
      var reqeustData = {
        datasetPost: this.datasetPost,
        dataset: this.dataset,
        connectionDB: this.targetDBConnection,
        JobItm: this.JobItm,
        hostCode: this.connection.host_code,
      };

      axios({
        url: "/dataset/insertDataPost.json",
        method: "post",
        headers: { "Content-Type": "application/json; charset=UTF-8" },
        data: reqeustData,
      })
        .then(function (response) {
          if (response.data.checkMessage.success) {
            vm.$showAlert("message", "등록이 완료되었습니다.");
            vm.$router.push("/dataManagement.page");
          } else {
            vm.$showAlert("message", "등록 실패.");
          }
        })
        .catch(function (error) {
          vm.$showAlert("message", "등록 실패.");
        });
    },

    // 등록할 파일 출력
    fileChange() {
      this.tempFile = [];
      var files =
        event.target.files ||
        event.dataTransfer.files ||
        window.event.target.files ||
        window.event.dataTransfer.files;

      for (var i = 0; i < files.length; i++) {
        files[i].progress = 0;
        this.tempFile.push(files[i]);
      }
    },

    // 게시글 등록 시 파일도 등록
    fileUpload() {
      const vm = this;

      var formData = new FormData();
      vm.tempFile.forEach(function (file, index) {
        formData.append("files", file);
      });

      axios
        .post("/fileManage/read", formData, {
          headers: {
            "Content-Type": "multipart/form-data",
          },
          onUploadProgress(progressEvent) {
            if (progressEvent.lengthComputable) {
              vm.tempFile.attach.fileList.forEach(function (file, index) {
                file.progress =
                  (progressEvent.loaded / progressEvent.total) * 100;
              });
            }
          },
        })
        .then(function (response) {
          vm.datasetPost.file_manager_id =
            response.data.resultData.fileManage.fileManagerId;
          vm.insertDataPost();
        })
        .catch(function (error) {
          console.error(error);
        });
    },

    onEditorChange(v) {
      this.datasetPost.post_dc = v.html;
    },

    init: async function () {
      this.categoryList = await this.$getCommonCode("DATA_CTGRY");
      this.datasetPost.ctgry_id = this.categoryList[0].cmmnCode;
    },
  },
  watch: {},
  computed: {
    keywordList() {
      if (this.datasetPost.kwrd == null || this.datasetPost.kwrd.length == 0) {
        return [];
      } else {
        return this.datasetPost.kwrd.split(",");
      }
    },
  },
  components: {
    DBConSearch: DBConSearch,
    DatabaseConnection: DatabaseConnection,
    FileSelect: FileSelect,
  },
  mounted() {
    this.init();
  },
};
</script>