<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 flex-column flex100">
        <div class="content">
          <div class="search-bar">
            <div class="flex justify-end align-center">
              <select name="" id="searchItm1" class="square-select" v-model="search_data.key">
                <option value="korean">표준용어명</option>
                <option value="english">영문명</option>
                <option value="english_abbr">영문약어명</option>
              </select>
              <div class="search-square">
                <div class="flex justify-end align-center no-gutter">
                  <input type="text" class="square-input flex90" placeholder="Search" v-model="search_data.value" v-on:keyup.enter="searchData()" />
                  <button class="square-button blue-btn flex10" @click="searchData()">
                    <svg-icon type="mdi" :path="this.$getIconPath()" class="square-icon"></svg-icon>
                  </button>
                </div>
              </div>
            </div>
          </div>
          <div class="content-zone">
            <div class="table-zone">
              <div class="list-info flex justify-between align-center">
                <div class="count-zone">
                  <p>총<span>{{ search.totalRows }}</span>건</p>
                </div>
              </div>
              <table class="list-table">
                <colgroup>
                  <col style="width: 10%" />
                  <col style="width: 20%" />
                  <col style="width: 20%" />
                  <col style="width: 20%" />
                  <col style="width: 15%" />
                  <col style="width: 15%" />
                </colgroup>
                <thead>
                  <tr>
                    <th>No</th>
                    <th>표준용어명</th>
                    <th>영문명</th>
                    <th>영문약어명</th>
                    <th>표준타입</th>
                    <th>생성일</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="(itm, indx) in stdWrdList" :key="indx" @click="clickWrd(itm)">
                    <td>{{ itm.wrd_seq }}</td>
                    <td>{{ itm.korean }}</td>
                    <td>{{ itm.english }}</td>
                    <td>{{ itm.english_abbr }}</td>
                    <td>{{ itm.sys_group }}</td>
                    <td>{{ itm.creat_dt }}</td>
                  </tr>
                </tbody>
              </table>
            </div>
            <PaginationButton v-model:currentPage="search.currentPage" :perPage="search.perPage" :totalCount="search.totalRows" :maxRange="5" :click="searchData" />
          </div>
        </div>
        <div class="content">
          <div class="content-titleZone">
            <p class="box-title">표준용어 상세</p>
          </div>
          <div class="table-zone">
            <table class="form-table">
              <colgroup>
                <col style="width: 10%" />
                <col style="width: 40%" />
                <col style="width: 10%" />
                <col style="width: 40%" />
              </colgroup>
              <tbody>
                <tr>
                  <th>표준용어명</th>
                  <td>
                    <input type="text" class="full-input" v-model="selectWrd.korean" />
                  </td>
                  <th>표준타입</th>
                  <td>{{ selectWrd.sys_group }}</td>
                </tr>
                <tr>
                  <th>영문명</th>
                  <td>
                    <input type="text" class="full-input" v-model="selectWrd.english" />
                  </td>
                  <th>영문약어명</th>
                  <td>
                    <input type="text" class="full-input" v-model="selectWrd.english_abbr" />
                  </td>
                </tr>
                <tr>
                  <th>생성일자</th>
                  <td>{{ selectWrd.creat_dt }}</td>
                  <th>생성자</th>
                  <td>{{ selectWrd.creat_id }}</td>
                </tr>
                <tr>
                  <th>수정일자</th>
                  <td>{{ selectWrd.updt_dt }}</td>
                  <th>수정자</th>
                  <td>{{ selectWrd.updt_id }}</td>
                </tr>
                <tr>
                  <th>설명</th>
                  <td colspan="3">
                    <input type="text" class="full-input" v-model="selectWrd.wrd_dc" />
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
          <div class="flex justify-end">
            <button class="blue-btn small-btn" v-if="editMode" @click="metaWrdUpdate()">수정</button>
            <button class="blue-btn small-btn" v-else @click="metaWrdInsert()">등록</button>
            <!-- <button class="blue-border-btn small-btn" @click="newData">초기화</button> -->
            <button class="blue-border-btn small-btn" @click="fnCancel">취소</button>
            <button class="red-border-btn small-btn" v-if="editMode" @click="metaWrdDelete()">삭제</button>
          </div>
        </div>
        <div class="content">
          <div class="content-titleZone">
            <p class="box-title">파일 업로드</p>
          </div>
          <div class="table-zone">
            <table class="form-table">
              <colgroup>
                <col style="width: 10%" />
                <col style="width: 90%" />
              </colgroup>
              <tbody>
                <tr>
                  <th>첨부파일</th>
                  <td>
                    <span>{{ fileName }}</span>
                    <button class="blue-border-btn small-btn" @click="downLoadExecel">양식 다운로드</button>
                    <button class="blue-border-btn small-btn" @click="fileSelect">양식 업로드</button>
                    <input type="file" id="fileUpload" @change="handleFileChange" style="display: none" accept=".xlsx, .xls" />
                  </td>
                </tr>
                <!-- <tr>
                  <th>양식다운로드</th>
                  <td @click="downLoadExecel">행정표준용어 데이터 양식.xlsx</td>
                </tr> -->
              </tbody>
            </table>
          </div>
          <div class="flex justify-end flex70">
            <button v-if="fileName != null" class="blue-btn small-btn" @click="selectFileUpload">등록</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import PageNavigation from "../../component/PageNavigation.vue";
import PaginationButton from "../../component/PaginationButton.vue";
import axios from "axios";
import store from "../AppStore";
import SvgIcon from "@jamescoyle/vue-icon";
import _ from "lodash";

export default {
  data() {
    return {
      // 검색 객체
      search: _.cloneDeep(this.$getDefaultSerchVO()),
      search_data: _.cloneDeep(this.$getDefaultSerchItem("korean", "string")),
      stdWrdList: [],
      selectWrd: _.cloneDeep(this.$getDefaultJobGroup().stdWrm),

      fileName: null, // 파일명
      editMode: false,
    };
  },
  methods: {
    searchData: function () {
      const vm = this;
      axios({
        url: "/meta/wrd/selectStdWrdList.json",
        method: "post",
        headers: {
          "Content-Type": "application/json; charset=UTF-8",
        },
        data: JSON.stringify(vm.search),
      })
        .then(function (response) {
          if (response.data.checkMessage.success) {
            vm.stdWrdList = response.data.resultData.stdWrdtList;
            vm.search.totalRows = response.data.resultData.totalRow;
          }
        })
        .catch(function (error) {
          vm.$showAlert(
            "에러 발생",
            "에러가 발생했습니다. 관리자에게 문의해 주세요."
          );
        });
    },

    // 단어선택
    clickWrd: function (selectWrd) {
      this.editMode = true;
      this.selectWrd = _.cloneDeep(selectWrd);
    },

    // 초기화
    init: function () {
      this.search.searchObjectList.push(this.search_data);
      this.search.perPage = 10;
      this.selectWrd.sys_group = "행안부 표준";
      this.searchData();
    },

    // 취소 버튼
    fnCancel() {
      this.editMode = false;
      this.newData();
    },

    // 신규등록폼
    newData: function () {
      this.selectWrd = _.cloneDeep(this.$getDefaultJobGroup().stdWrm);
      this.selectWrd.sys_group = "행안부 표준";
    },

    // 엑셀 다운로드
    downLoadExecel: function () {
      // /resurce/file/행정표준용어 양식.xlsx 파일 다운로드
      const a_tag = document.createElement("a");
      a_tag.href = "../../../../client/resources/file/stdWrdFile.xlsx";
      a_tag.download = "행정표준용어 양식.xlsx";
      a_tag.click();
    },
    // 유효성 검사
    checkValidation: function () {
      const vm = this;
      if (vm.selectWrd.korean == "" || vm.selectWrd.korean == null) {
        vm.$showAlert("warning", "표준용어명을 입력해 주세요.");
        return false;
      }
      if (vm.selectWrd.english == "" || vm.selectWrd.english == null) {
        vm.$showAlert("warning", "영문명을 입력해 주세요.");
        return false;
      }
      if (
        vm.selectWrd.english_abbr == "" ||
        vm.selectWrd.english_abbr == null
      ) {
        vm.$showAlert("warning", "영문약어명을 입력해 주세요.");
        return false;
      }
      return true;
    },
    // 표준 용어 등록 로직
    metaWrdInsert: function () {
      const vm = this;
      if (vm.checkValidation()) {
        vm.selectWrd.creat_id = store.state.loginUser.user_id;

        axios({
          url: "/meta/wrd/stdWrdInsert.json",
          method: "post",
          headers: {
            "Content-Type": "application/json; charset=UTF-8",
          },
          data: JSON.stringify(vm.selectWrd),
        })
          .then(function (response) {
            if (response.data.checkMessage.success) {
              if (response.data.resultData.result == -1) {
                vm.$showAlert("warning", "이미 등록된 단어입니다.");
                return;
              }
              vm.$showAlert("success", "등록되었습니다.");
              vm.searchData();
              vm.newData();
            }
          })
          .catch(function (error) {
            this.$showAlert(
              "에러 발생",
              "에러가 발생했습니다. 관리자에게 문의해 주세요."
            );
          });
      }
    },
    // 표준 용어 수정 로직
    metaWrdUpdate: function () {
      const vm = this;
      if (vm.checkValidation()) {
        vm.selectWrd.updt_id = store.state.loginUser.user_id;
        axios({
          url: "/meta/wrd/stdWrdUpdate.json",
          method: "post",
          headers: {
            "Content-Type": "application/json; charset=UTF-8",
          },
          data: JSON.stringify(vm.selectWrd),
        })
          .then(function (response) {
            if (response.data.checkMessage.success) {
              vm.$showAlert("success", "수정되었습니다.");
              vm.searchData();
              vm.newData();
              vm.editMode = false;
            }
          })
          .catch(function (error) {
            this.$showAlert(
              "에러 발생",
              "에러가 발생했습니다. 관리자에게 문의해 주세요."
            );
          });
      }
    },
    // 표준 용어 삭제 로직
    metaWrdDelete: async function () {
      const vm = this;
      if (vm.selectWrd.creat_dt == null) {
        vm.$showAlert("warning", "삭제할 단어를 선택해 주세요.");
        return;
      }
      if (await this.$showConfirm("삭제", "선택한 단어를 삭제하시겠습니까?")) {
        vm.selectWrd.updt_id = store.state.loginUser.user_id;

        axios({
          url: "/meta/wrd/stdWrdDelete.json",
          method: "post",
          headers: {
            "Content-Type": "application/json; charset=UTF-8",
          },
          data: JSON.stringify(vm.selectWrd),
        })
          .then(function (response) {
            if (response.data.checkMessage.success) {
              vm.$showAlert("success", "삭제되었습니다.");
              vm.searchData();
              vm.newData();
              vm.editMode = false;
            }
          })
          .catch(function (error) {
            this.$showAlert(
              "에러 발생",
              "에러가 발생했습니다. 관리자에게 문의해 주세요."
            );
          });
      }
    },
    // 파일 업로드 로직
    fileSelect: function () {
      // 버튼 클릭시 file input 클릭
      document.getElementById("fileUpload").click();
    },
    handleFileChange: function (event) {
      this.fileName = event.target.files[0].name;
    },
    selectFileUpload: function () {
      let vm = this;
      // 파일 업로드 로직
      // 엑셀 파일이 아닌경우 경고창
      if (!(vm.fileName.endsWith("xlsx") || vm.fileName.endsWith("xls"))) {
        vm.$showAlert("알림", "엑셀 파일만 업로드 가능합니다.");
        return;
      }

      let formData = new FormData();
      formData.append("file", document.getElementById("fileUpload").files[0]);
      formData.append("create_id", store.state.loginUser.user_id);
      axios({
        url: "/meta/wrd/stdWrdFileUpload.json",
        method: "post",
        headers: {
          "Content-Type": "multipart/form-data",
        },
        data: formData,
      })
        .then(function (response) {
          let duplicateCheck = response.data.resultData.duplicateCheck;
          if (response.data.checkMessage.success) {
            vm.$showAlert(
              "success",
              "파일이 성공적으로 업로드되었습니다.<br>중복 데이터 : " +
              duplicateCheck +
              "건 제외"
            );
            vm.fileName = "";
            vm.searchData();
          }
        })
        .catch(function (error) {
          this.$showAlert(
            "에러 발생",
            "에러가 발생했습니다. 관리자에게 문의해 주세요."
          );
        });
    },
  },
  components: {
    PageNavigation: PageNavigation,
    PaginationButton: PaginationButton,
    SvgIcon: SvgIcon,
  },
  mounted() {
    this.init();
  },
};
</script>