<template>
  <div class="content content-box">
    <div class="flex-column justify-between">
      <div style="height: 100%">
        <div class="content-titleZone">
          <div class="flex justify-between align-center no-gutter">
            <div class="flex30">
              <p class="box-title">컬럼정보</p>
            </div>
            <div class="flex justify-end flex70">
              <button class="darkg-border-btn small-btn" @click="executionChangeData('on')"> 자동PK 생성 </button>
              <button class="blue-border-btn small-btn" @click="addColumn"> 추가 </button>
              <button class="blue-btn small-btn" @click="executionChangeData('off')"> 실행 </button>
            </div>
          </div>
        </div>
        <div class="content-zone" style="overflow: auto">
          <div class="table-zone">
            <div class="count-zone">
              <p> 총 ROW : <span> {{ coulmnsInfo.length }} </span>
              </p>
            </div>
            <table class="list-table">
              <colgroup>
                <col width="80px" />
                <col width="80px" />
                <col width="" />
                <col width="" />
                <col width="" />
                <col width="100px" />
                <col width="50px" />
                <col width="50px" />
                <col width="400px" />
              </colgroup>
              <thead>
                <tr>
                  <th>No</th>
                  <th>상태</th>
                  <th>컬럼명(영문)</th>
                  <th>컬럼한글(한글)</th>
                  <th>데이터유형</th>
                  <th>데이터길이</th>
                  <th>PK</th>
                  <th>표준</th>
                  <th>설정</th>
                </tr>
              </thead>
              <tbody v-if="coulmnsInfo != null && coulmnsInfo.length > 0">
                <tr v-for="(cells, i) in coulmnsInfo" :key="i">
                  <td>{{ i + 1 }}</td>
                  <td style="text-align: center">
                    <span>{{ cells.status }}</span>
                  </td>
                  <td>
                    <span v-if="!cells.enableEdit">{{ cells.columnNm }}</span>
                    <input v-else type="text" class="width100p" v-model="cells.columnNm" />
                  </td>
                  <td>
                    <span v-if="!cells.enableEdit">{{ cells.displyColumnNm }}</span>
                    <input v-else type="text" autocomplete="off" name="text" class="width100p" v-model="cells.displyColumnNm" />
                    <!-- @input="getStandardTermListByContains(cells, $event.target.value, i)"
                                            @keyup="selectingStandardTermByKey(cells, $event, i)"> -->
                    <div class="search_list_box" id="search_list" name="search_list" v-show="cells.searchListViewAt == true" style="
                        top: auto;
                        left: auto;
                        border: solid 0.1px #bcbcbc;
                        max-width: 400px;
                      ">
                      <div class="item" v-for="(search, j) in cells.standardTermSearchList" :key="j" :title="'한글명:' +
                        search.korean +
                        '/영문명:' +
                        search.english +
                        '/영문약어명:' +
                        search.englishAbbr
                        " :id="search.termSeqs" :class="{
                          item_selected:
                            cells.selectingStandardTerm != null &&
                            cells.selectingStandardTerm.termSeqs ==
                            search.termSeqs,
                        }"></div>
                    </div>
                  </td>
                  <td>
                    <span v-if="!cells.enableEdit">{{ cells.dataTy }}</span>
                    <select name="public" class="select_R width120 mr5" v-model="cells.dataTy" v-else>
                      <option v-for="(item, indx) in dataTypeList" :value="item" :key="indx"> {{ item }} </option>
                    </select>
                  </td>
                  <td>
                    <span v-if="!cells.enableEdit">{{ cells.dataSize }}</span>
                    <input v-else type="number" class="width100p" v-model="cells.dataSize" />
                  </td>
                  <td style="text-align: center">
                    <input type="checkbox" :id="'pr' + i" v-model="cells.pkAt" :disabled="cells.enableEdit == false" />
                    <label :for="'pr' + i" style="padding-left: 0px"></label>
                  </td>
                  <td style="text-align: center">
                    <input type="checkbox" :id="'st' + i" v-model="cells.columnStdizAt" :disabled="cells.enableEdit == false" />
                    <label :for="'st' + i" style="padding-left: 0px"></label>
                  </td>
                  <td style="text-align: center">
                    <button type="button" class="blue-border-btn small-btn" title="수정" v-if="!cells.enableEdit" @click="editStart(cells)"> 수정 </button>
                    <button type="button" class="blue-border-btn small-btn" title="닫기" v-if="cells.enableEdit" @click="editEnd(cells)"> 완료 </button>
                    <button type="button" class="red-border-btn small-btn" v-if="cells.status != 3" title="삭제" @click="deleteColumn(cells)"> 삭제 </button>
                    <button type="button" class="red-border-btn small-btn" v-if="cells.status == 3" title="취소" @click="deleteColumn(cells)"> 취소 </button>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import axios from "axios";
import SvgIcon from "@jamescoyle/vue-icon";
import _ from "lodash";

export default {
  props: {
    datasetPost_id: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      comId:
        "comId_" +
        Math.random().toString(36).substring(2, 15) +
        Math.random().toString(36).substring(2, 15),
      dataTable: _.cloneDeep(this.$getDefaultObject().dataTable),
      dataTypeList: _.cloneDeep(this.$getDefaultObject().dataTypeList),
      coulmn_infoId:
        "coulmn_info" +
        Math.random().toString(36).substring(2, 15) +
        Math.random().toString(36).substring(2, 15),
      coulmn_infoIds:
        "coulmn_info" +
        Math.random().toString(36).substring(2, 15) +
        Math.random().toString(36).substring(2, 15),
      coulmnsInfo: [],
      changeData: [],
      orgPkList: [],
      currentPkList: [],
    };
  },
  methods: {
    init: function () {
      let vm = this;
      axios({
        url: "/dataset/getDataTableInfo.json",
        method: "post",
        headers: {
          "Content-Type": "application/json; charset=UTF-8",
        },
        data: { datapost_id: vm.datasetPost_id },
      })
        .then(function (response) {
          vm.dataTable = response.data.resultData.dataTable;
          vm.coulmnsInfo = response.data.resultData.dataTable.columnDatas;
          vm.orgPkList = vm.getcurrentPkList();
        })
        .catch(function (error) {
          this.$showAlert(
            "에러 발생",
            "에러가 발생했습니다. 관리자에게 문의해 주세요."
          );
        });
    },
    editStart: function (data) {
      data.enableEdit = true;
      if (data.status == 1) {
        data.orgData = _.cloneDeep(data);
      }
    },
    editEnd: function (data) {
      data.enableEdit = false;
      data.searchListViewAt = false;
      data.standardTermSearchList = [];
      this.checkData(data);
    },
    checkData: function (data) {
      var checkData = _.cloneDeep(data);
      checkData.orgData = null;
      checkData.enableEdit = true;
      checkData.status = 1;
      if (_.isEqual(checkData, data.orgData)) {
        data.status = 1;
        data.orgData = null;
      } else {
        data.status = 2;
      }
    },
    // 컬럼 추가
    addColumn: function () {
      var columnData = _.cloneDeep(this.coulmnsInfo[0]);
      columnData.dataTy = "STRING";
      columnData.displyColumnNm = "NEW_DT";
      columnData.orginlColumnNm = "NEW_DT";
      columnData.columnNm = "NEW_DT";
      columnData.pkAt = false;
      columnData.columnStdizAt = false;
      columnData.dataSize = 50;
      columnData.ordr = this.coulmnsInfo.length;
      columnData.status = 4;
      columnData.enableEdit = true;
      this.coulmnsInfo.push(columnData);
    },
    // 컬럼 삭제
    deleteColumn: function (column) {
      if (column.status == 3) {
        if (column.orgData == null) {
          column.status = 1;
        } else {
          column.status = 2;
        }
      } else if (column.status == 4) {
        this.coulmnsInfo.splice(column.orders, 1);
      } else {
        column.status = 3;
      }
    },
    // 변경된 데이터 리스트 가져오기
    getChangeList: function () {
      this.changeData = [];
      for (var i = 0; i < this.coulmnsInfo.length; i++) {
        if (this.coulmnsInfo[i].status != 1) {
          this.changeData.push(this.coulmnsInfo[i]);
        }
      }
    },
    // pk 찾기
    getcurrentPkList: function () {
      var pkList = [];
      for (var i = 0; i < this.coulmnsInfo.length; i++) {
        if (this.coulmnsInfo[i].pkAt) {
          pkList.push(this.coulmnsInfo[i].columnNm);
        }
      }
      return pkList;
    },
    // 데이터 변경 실행
    executionChangeData: function (autoPk) {
      var vm = this;
      this.getChangeList();

      if (this.changeData.length == 0 && autoPk == false) {
        alert("변경된 데이터가 없습니다.");
        return false;
      }

      var request = {
        changeData: this.changeData,
        connectionId: this.dataTable.dbConectId,
        tableName: this.dataTable.tableNm,
        databaseName: this.dataTable.databaseNm,
        orgPkList: this.orgPkList,
        currentPkList: this.getcurrentPkList(),
        datasetId: this.dataTable.datasetId,
        datasetPostId: this.dataTable.datasetPostId,
        pkInsert: autoPk,
      };
      axios({
        url: "/dataset/changeColumnInfo.json",
        method: "post",
        headers: {
          "Content-Type": "application/json; charset=UTF-8",
        },
        data: request,
      })
        .then(function (response) {
          if (response.data.checkMessage.success) {
            vm.coulmnsInfo = response.data.resultData.columnDatas;
            vm.orgPkList = vm.getcurrentPkList();
            vm.$showAlert("message", "변경완료");
          } else {
            vm.$showAlert("경고", response.data.checkMessage.message);
          }
        })
        .catch(function (error) {
          this.$showAlert(
            "에러 발생",
            "에러가 발생했습니다. 관리자에게 문의해 주세요."
          );
        });
    },
  },
  components: {
    SvgIcon: SvgIcon,
  },
  mounted() {
    this.init();
  },
};
</script>