<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" style="overflow-y: inherit; padding: 15px">
        <div class="flex-column justify-between">
          <div style="height: 20%">
            <div class="content-titleZone">
              <p class="box-title">연계 스케줄러</p>
            </div>
            <table class="list-table">
              <thead>
                <tr>
                  <th>NO</th>
                  <th>작업명</th>
                  <th>상태</th>
                  <th>작동일시</th>
                  <th>등록자</th>
                  <th>등록일</th>
                  <th>스케줄관리</th>
                </tr>
              </thead>
              <tbody>
                <tr>
                  <td colspan="7">등록된 스케쥴이 없습니다.</td>
                </tr>
              </tbody>
            </table>
          </div>
          <div style="height: 70%">
            <ul class="tab-nav2 flex align-center">
              <li @click="showTab('tab1')">
                <a :class="{ activeTab: activeTab === 'tab1' }">데이터셋</a>
              </li>
              <li @click="showTab('tab2')">
                <a :class="{ activeTab: activeTab === 'tab2' }">등록정보</a>
              </li>
            </ul>
            <ul class="tab-content2">
              <li id="tab01" v-show="activeTab === 'tab1'" class="content-box">
                <div class="content-titleZone">
                  <p class="box-title">데이터셋 정보</p>
                </div>
                <div class="content-zone" style="overflow: auto">
                  <div class="table-zone">
                    <div class="count-zone">
                      <p> 총 <span>{{ dataTable.totalRows }}</span>건 </p>
                    </div>
                    <table class="list-table" v-if="dataTable.columnDatas">
                      <thead>
                        <tr v-if="dataTable.columnDatas.length > 0">
                          <th v-for="(itm, indx) in dataTable.columnDatas" :key="indx" style="min-width: 150px !important"> {{ itm.columnNm }} <button class="tp-btn" v-if="itm.pkAt">
                              <svg-icon type="mdi" :width="15" :height="15" :path="this.$getIconPath('mdiKeyVariant')" :color="'#213f99'"></svg-icon>
                            </button>
                          </th>
                        </tr>
                      </thead>
                      <tbody v-if="dataTable.rowData.length > 0">
                        <tr v-for="(row, rows) in dataTable.rowData" :key="rows">
                          <td v-for="(itm, indx) in row" :key="indx" style="
                              overflow: hidden;
                              white-space: nowrap;
                              text-overflow: ellipsis;
                            "> {{ itm }} </td>
                        </tr>
                      </tbody>
                    </table>
                    <PaginationButton v-model:currentPage="search.currentPage" :perPage="search.perPage" :totalCount="dataTable.totalRows" :maxRange="5" :click="init" />
                  </div>
                </div>
              </li>
              <li id="tab02" v-show="activeTab === 'tab2'">
                <div class="content-box">
                  <div class="content-titleZone">
                    <p class="box-title">등록 정보</p>
                  </div>
                  <table class="form-table" v-if="!editMode">
                    <colgroup>
                      <col style="width: 15%" />
                      <col style="width: 85%" />
                    </colgroup>
                    <tbody>
                      <tr>
                        <th>제목</th>
                        <td>
                          <span>{{ datasetPost.post_sj }}</span>
                        </td>
                      </tr>
                      <tr>
                        <th>테이블 한글명</th>
                        <td>{{ dataset.tableNmKr }}</td>
                      </tr>
                      <tr>
                        <th>테이블 영문명</th>
                        <td>{{ dataset.tableNm }}</td>
                      </tr>
                      <tr>
                        <th>카테고리</th>
                        <td>
                          <select name="ctgry" id="ctgry" class="square-select half-input" v-model="datasetPost.ctgry_id" disabled>
                            <option v-for="(item, indx) in categoryList" :key="indx" :value="item.cmmnCode"> {{ item.codeNm }} </option>
                          </select>
                        </td>
                      </tr>
                      <tr>
                        <th>공개여부</th>
                        <td>
                          <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" disabled />
                              <span>공개</span>
                            </label>
                            <label class="radio-label">
                              <input type="radio" name="public_at" class="custom-radiobox" :value="false" v-model="datasetPost.public_at" disabled />
                              <span>비공개</span>
                            </label>
                          </div>
                        </td>
                      </tr>
                      <tr>
                        <th>목표 DB</th>
                        <td>{{ dataset.databaseNm }}</td>
                      </tr>
                      <tr>
                        <th>검색 키워드</th>
                        <td>{{ datasetPost.kwrd }}</td>
                      </tr>
                      <tr>
                        <th>내용</th>
                        <td>
                          <quill-editor style="height: 130px" :value="datasetPost.post_dc" contentType="html" :options="editorOption" ref="quillEditorA" disabled />
                        </td>
                      </tr>
                      <tr>
                        <th>데이터 출처</th>
                        <td>{{ datasetPost.origin }}</td>
                      </tr>
                      <tr>
                        <th>첨부 파일</th>
                        <td>
                          <ul>
                            <li v-for="(file, i) in fileList" :key="i">
                              <span>{{ file.name }}</span>
                              <button @click="downloadFile(file)" class="green-border-btn small-btn"> 파일 다운로드 </button>
                            </li>
                          </ul>
                        </td>
                      </tr>
                    </tbody>
                  </table>
                  <table class="form-table" v-else>
                    <colgroup>
                      <col style="width: 15%" />
                      <col style="width: 85%" />
                    </colgroup>
                    <tbody>
                      <tr>
                        <th>제목</th>
                        <td>
                          <input type="text" class="half-input" v-model="datasetPost.post_sj" />
                        </td>
                      </tr>
                      <tr>
                        <th>테이블 한글명</th>
                        <td>
                          <input type="text" class="half-input" v-model="dataset.tableNmKr" />
                        </td>
                      </tr>
                      <tr>
                        <th>테이블 영문명</th>
                        <td>{{ dataset.tableNm }}</td>
                      </tr>
                      <tr>
                        <th>카테고리</th>
                        <td colspan>
                          <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>
                          <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>{{ dataset.databaseNm }}</td>
                      </tr>
                      <tr>
                        <th>검색 키워드</th>
                        <td>
                          <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>
                          <quill-editor style="height: 130px" :value="datasetPost.post_dc" @change="onEditorChange" contentType="html" :options="editorOption2" ref="quillEditorB"></quill-editor>
                        </td>
                      </tr>
                      <tr>
                        <th>데이터 출처</th>
                        <td>
                          <input type="text" class="half-input" v-model="datasetPost.origin" @keyup.enter="addKwrd" />
                        </td>
                      </tr>
                      <tr>
                        <th>첨부 파일</th>
                        <td>
                          <ul>
                            <li v-for="(file, i) in fileList" :key="i">
                              <span>{{ file.name }}</span>
                            </li>
                          </ul>
                        </td>
                      </tr>
                    </tbody>
                  </table>
                  <div style="height: 5%; margin-top: 5px">
                    <div class="flex justify-end">
                      <button class="blue-btn small-btn" v-if="editMode && activeTab === 'tab2'" @click="updateDataPost">저장</button>
                      <button class="blue-btn small-btn" v-if="!editMode && activeTab === 'tab2'" @click="editMode = !editMode">수정</button>
                      <button class="blue-border-btn small-btn" v-else-if="editMode && activeTab === 'tab2'" @click="editMode = !editMode">취소</button>
                      <button class="blue-border-btn small-btn" v-if="activeTab === 'tab2'" @click="goBack()"> 목록 </button>
                    </div>
                  </div>
                </div>
              </li>
            </ul>
          </div>
          <div style="height: 5%">
            <div class="flex justify-end">
              <button class="blue-btn small-btn" v-if="activeTab === 'tab1'" @click="moveEditPage()"> 데이터 수정 </button>
              <button class="red-border-btn small-btn" v-if="activeTab === 'tab1'" @click="deleteDataset()"> 데이터 삭제 </button>
              <button class="blue-border-btn small-btn" v-if="activeTab === 'tab1'" @click="goBack()"> 목록 </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
//import { quillEditor } from "vue-quill-editor";
import axios from "axios";
import SvgIcon from "@jamescoyle/vue-icon";
import PageNavigation from "../../component/PageNavigation.vue";
import PaginationButton from "../../component/PaginationButton.vue";

export default {
  props: {
    datapost: {
      type: Object,
      default: {},
    },
  },
  data() {
    return {
      dataPost: this.datapost,
      activeTab: "tab1",
      dataTable: {},
      datasetPost: {},
      dataset: {},
      fileList: [],
      editMode: false,
      categoryList: [],
      editorOption: {
        placeholder: "내용 입력하세요.",
        readOnly: true,
      },
      editorOption2: {
        placeholder: "내용 입력하세요.",
      },
      search: this.$getDefaultSerchVO(),
    };
  },
  methods: {
    showTab: function (tabName) {
      this.activeTab = tabName;
    },
    init: async function () {
      const vm = this;
      this.categoryList = await this.$getCommonCode("DATA_CTGRY");
      axios({
        url: "/dataset/selectDataPost.json",
        method: "post",
        headers: {
          "Content-Type": "application/json; charset=UTF-8",
        },
        data: { datapost_id: vm.$route.query.datapost, search: vm.search },
      })
        .then(function (response) {
          if (response.data.checkMessage.success) {
            vm.datasetPost = response.data.resultData.datasetPost;
            vm.dataTable = response.data.resultData.dataTable;
            vm.dataset = response.data.resultData.dataset;
            vm.fileList = response.data.resultData.fileList;
          }
        })
        .catch(function (error) {
          this.$showAlert(
            "에러 발생",
            "에러가 발생했습니다. 관리자에게 문의해 주세요."
          );
        });
    },
    goBack: function () {
      window.history.back();
    },

    // 키워드 추가
    addKwrd: function () {
      //입력한 키워드가 없을 때
      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: function (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];
      }
    },

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

    // 데이터 포스트 등록
    updateDataPost: function () {
      let vm = this;

      var reqeustData = {
        datasetPost: this.datasetPost,
        dataset: this.dataset,
      };

      // 벨리데이션 체크
      this.datasetPost.dept_code = this.$store.state.loginUser.dept_code;

      axios({
        url: "/dataset/updateDataPost.json",
        method: "post",
        headers: {
          "Content-Type": "application/json; charset=UTF-8",
        },
        data: reqeustData,
      })
        .then(function (response) {
          vm.$showAlert("message", response.data.checkMessage.message);
          if (response.data.checkMessage.success) {
            vm.editMode = false;
          } else {
            vm.$showAlert("message", "등록 실패.");
          }
        })
        .catch(function (error) {
          this.$showAlert(
            "에러 발생",
            "에러가 발생했습니다. 관리자에게 문의해 주세요."
          );
        });
    },

    // 데이터 수정 페이지 이동
    moveEditPage: function () {
      this.$router.push({
        name: "DataEditView",
        query: { datapost: this.$route.query.datapost },
      });
    },

    // 데이터셋 삭제
    deleteDataset: async function () {
      let vm = this;

      let check = await vm.$showConfirm("데이터 삭제", "데이터를 삭제하시겠습니까?");
      if (!check) {
        return;
      }

      var reqeustData = {
        datasetPost: this.datasetPost,
      };
      axios({
        url: "/dataset/deleteDataPost.json",
        method: "post",
        headers: {
          "Content-Type": "application/json; charset=UTF-8",
        },
        data: reqeustData,
      })
        .then(function (response) {
          vm.$showAlert("message", response.data.checkMessage.message);
          if (response.data.checkMessage.success) {
            vm.$showAlert("message", "삭제 성공하였습니다.");
            vm.$router.push("/dataManagement.page");
          } else {
            vm.$showAlert("message", "삭제 실패.");
          }
        })
        .catch(function (error) {
          this.$showAlert(
            "에러 발생",
            "에러가 발생했습니다. 관리자에게 문의해 주세요."
          );
        });
    },

    // 파일 다운로드
    downloadFile(file) {
      axios({
        url: "/fileManage/download",
        method: "post",
        headers: {
          "Content-Type": "application/json; charset=UTF-8",
        },
        data: { fileManagerId: file.fileManagerId },
        responseType: "blob",
      })
        .then(function (response) {
          const url = window.URL.createObjectURL(new Blob([response.data]));
          const link = document.createElement("a");
          link.href = url;
          link.setAttribute("download", file.name);
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
        })
        .catch(function (error) {
          this.$showAlert(
            "에러 발생",
            "에러가 발생했습니다. 관리자에게 문의해 주세요."
          );
        });
    },
  },
  computed: {
    keywordList: function () {
      if (this.datasetPost.kwrd == null || this.datasetPost.kwrd.length == 0) {
        return [];
      } else {
        return this.datasetPost.kwrd.split(",");
      }
    },
  },
  components: {
    SvgIcon: SvgIcon,
    PageNavigation: PageNavigation,
    PaginationButton: PaginationButton,
  },
  mounted() {
    this.search.perPage = 15;
    this.init();
  },
};
</script>