<template>
  <div class="content content-box">
    <div class="flex-column justify-between">
      <!-- <div style="height: 30%">
        <div class="content-titleZone">
          <div class="flex justify-between align-center">
            <p class="box-title">데이터 필터</p>
          </div>
        </div>
        <JobContainer :jobGroup="jobGroup" @getDataTable="getResult" ref="jobcon" />
      </div>
      <div style="height: 70%"> -->
      <div>
        <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="blue-border-btn small-btn" @click="addRow"> 데이터추가 </button>
              <button class="blue-btn small-btn" @click="updateRow"> 데이터적용 </button>
              <button class="red-border-btn small-btn" @click="deleteRow"> 선택삭제 </button>
            </div>
          </div>
        </div>
        <!-- <div class="content-zone" style="overflow: auto"> -->
        <div class="content-zone">
          <div class="table-zone">
            <div class="count-zone">
              <p> 총 <span>{{ dataTable.totalRows }}</span>건 </p>
            </div>
            <table class="list-table" v-if="start">
              <thead>
                <tr v-if="dataTable.columnDatas.length > 0">
                  <th>
                    <input type="checkbox" id="AllCheck" v-model="selectAll" />
                    <label for="AllCheck" style="padding-left: 0px"></label>
                  </th>
                  <th>상태</th>
                  <th v-for="(itm, indx) in dataTable.columnDatas" :key="indx" style="min-width: 150px !important"> {{ itm.displyColumnNm }} <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 != undefined &&
                dataTable.rowData != null &&
                dataTable.rowData.length > 0
              ">
                <tr v-for="(cells, i) in dataTable.rowData" :key="i">
                  <td>
                    <input type="checkbox" :id="i + 'Check'" v-model="selected" :value="i" />
                    <label :for="i + 'Check'" style="padding-left: 0px"></label>
                  </td>
                  <td>
                    <div class="editType" :class="'editType' + statusList[i]"> ({{ statusList[i] }}) </div>
                  </td>
                  <td v-for="(cell, j) in cells" :key="j" :title="cell" :id="i + '-' + j" @click="editStart(i, i + '-' + j, j)">
                    <input type="text" class="full-input" v-model="cells[j]" v-if="editPoint == i + '-' + j" @blur="editEnd($event, i, 2)" @keyup="editEnd($event, i, 1)" />
                    <span v-else> {{ cell }} </span>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import axios from "axios";
import JobContainer from "../connection/jobContainer.vue";
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),
      dataPostId: this.datasetPost_id,
      jobGroup: this.$getDefaultJobGroup().jobGroup,
      dataTable: {},
      // 현재 에디트 창
      editPoint: "",
      selected: [],
      // row 별 상태(일반, 수정 , 삭제)
      statusList: [],
      // 원본 저장
      originData: [],
      start: false,
    };
  },
  methods: {
    // 데이터 초기화
    init: function () {
      let vm = this;
      this.jobGroup.datasetPost_id = this.datasetPost_id;
      // jobGroup parameter 생성
      let tampJobGroup = _.cloneDeep(this.$getDefaultJobGroup().jobGroup);
      // 기본 필터 생성
      let newItm = _.cloneDeep(this.$getDefaultJobGroup().jobItem);
      newItm.type = "dataSort";
      newItm.indx = 1;
      tampJobGroup.jobItm.push(newItm);
      let newItm2 = _.cloneDeep(this.$getDefaultJobGroup().jobItem);
      newItm2.type = "dataFilter";
      newItm2.indx = 1;
      newItm2.itm = _.cloneDeep(this.$getDefaultJobGroup().dataFilter);
      tampJobGroup.jobItm.push(newItm2);

      axios({
        url: "/job/createJobGroup.json",
        method: "post",
        headers: {
          "Content-Type": "application/json; charset=UTF-8",
        },
        data: tampJobGroup,
      })
        .then(function (response) {
          vm.jobGroup = response.data.resultData.jobGroup;
          vm.dataTable = response.data.resultData.jobGroup.dataTable;
          vm.satatusInint();
          vm.start = true;
        })
        .catch(function (error) {
          this.$showAlert(
            "에러 발생",
            "에러가 발생했습니다. 관리자에게 문의해 주세요."
          );
        });
    },
    getResult: function (dataTable) {
      this.dataTable = dataTable;
      this.satatusInint();
    },
    // 데이터 에디트
    editStart: function (indx, info, seIndx) {
      // pk는 수정불가
      if (
        this.dataTable.columnDatas[seIndx].pkAt == true &&
        this.statusList[indx] != 4
      ) {
        return false;
      }
      this.editPoint = info;
      // 원본데이터 넣기
      if (this.statusList[indx] == 1) {
        this.originData[indx].orgData = _.cloneDeep(
          this.dataTable.rowData[indx]
        );
      }
    },
    editEnd: function (e, indx, type) {
      if (e.keyCode == 13 || e.keyCode == 27 || type == 2) {
        this.editPoint = "";
        this.statusList[indx] = this.checkData(indx);
      }
    },
    // 원본데이터 비교
    checkData: function (indx) {
      var result = 2;
      if (this.statusList[indx] == 4) {
        return 4;
      }

      if (
        this.originData[indx].orgData == null ||
        _.isEqual(this.dataTable.rowData[indx], this.originData[indx].orgData)
      ) {
        result = 1;
        this.originData[indx].orgData = null;
      }
      return result;
    },

    // 수정스테이터스값 초기화
    satatusInint: function () {
      this.originData = [];
      this.statusList = [];
      this.selected = [];
      for (var i = 0; i < this.dataTable.rowData.length; i++) {
        this.statusList.push(1);
        this.originData.push({
          row: i,
          orgData: null,
        });
      }
      this.usePk = false;
      for (var i = 0; i < this.dataTable.columnDatas.length; i++) {
        if (this.dataTable.columnDatas[i].pkAt) {
          this.usePk = true;
          continue;
        }
      }
      if (this.usePk == false) {
        this.$showAlert(
          "message",
          "primary 키가 존재하지 않아 사용상에 제한이 발생합니다."
        );
      }
    },
    // 데이터 추가
    addRow: function () {
      this.statusList.splice(0, 0, 4);
      var Array = [];
      // 데이터가 없을 때도 데이터 추가가 가능하도록
      var columnLength =
        this.dataTable.columnDatas.length > 0
          ? this.dataTable.columnDatas.length
          : 1;

      for (var i = 0; i < columnLength; i++) {
        Array.push("");
      }

      if (!this.dataTable.rowData) {
        this.dataTable.rowData = [];
      }
      this.dataTable.rowData.splice(0, 0, Array);
      for (let i = 0; i < this.selected.length; i++) {
        this.selected[i] = this.selected[i] + 1;
      }

      this.selected.sort();
    },

    // 선택된 컬럼들을 삭제한다.
    deleteRow: function () {
      this.selected.sort();
      let deletCount = 0;
      for (var i = this.selected.length - 1; i >= 0; i--) {
        if (this.statusList[this.selected[i]] == 3) {
          this.statusList[this.selected[i]] = 3;
        } else if (this.statusList[this.selected[i]] == 4) {
          this.statusList.splice(this.selected[i], 1);
          this.dataTable.rowData.splice(this.selected[i], 1);
          this.selected.splice(i, 1);
          deletCount++;
        } else {
          this.statusList[this.selected[i]] = 3;
          if (this.originData[this.selected[i]].orgData == null) {
            this.originData[this.selected[i]].orgData = _.cloneDeep(
              this.dataTable.rowData[this.selected[i]]
            );
          }
        }
      }

      // 셀렉트 값 보정
      for (let i = 0; i < this.selected.length; i++) {
        this.selected[i] = this.selected[i] - deletCount;
      }

      this.$forceUpdate();
    },

    // 데이터 업데이트
    updateRow: function () {
      var vm = this;

      if (this.usePk == false) {
        this.$showAlert(
          "message",
          "primary 키가 존재하지 않아 사용상에 제한이 발생합니다."
        );
        return false;
      }

      var changeData = [];
      var deleteData = [];
      var insertData = [];

      // 변경된 데이터 담기
      for (var i = 0; i < this.statusList.length; i++) {
        if (this.statusList[i] == 2) {
          changeData.push(this.dataTable.rowData[i]);
        } else if (this.statusList[i] == 3) {
          deleteData.push(this.originData[i].orgData);
        } else if (this.statusList[i] == 4) {
          insertData.push(this.dataTable.rowData[i]);
        }
      }

      if (
        insertData.length == 0 &&
        changeData.length == 0 &&
        deleteData.length == 0
      ) {
        this.$showAlert("message", "변경된 내용이 없습니다.");
        return false;
      }

      var requestData = {
        datasetPost_id: this.datasetPost_id,
        jobGroup: this.jobGroup,
        changeData: changeData,
        deleteData: deleteData,
        insertData: insertData,
      };

      axios({
        url: "/data/changeDatasetRows.json",
        method: "post",
        headers: {
          "Content-Type": "application/json; charset=UTF-8",
        },
        data: requestData,
      })
        .then(function (response) {
          if (response.data.checkMessage.success) {
            vm.dataTable = response.data.resultData.dataTable;
            vm.satatusInint();
            vm.$showAlert("message", "변경완료");
          } else {
            vm.$showAlert("경고", response.data.checkMessage.message);
          }
        })
        .catch(function (error) {
          this.$showAlert(
            "에러 발생",
            "에러가 발생했습니다. 관리자에게 문의해 주세요."
          );
        });
    },
  },
  computed: {
    selectAll: {
      get: function () {
        return this.dataTable.rowData
          ? this.selected.length == this.dataTable.rowData.length
          : false;
      },
      set: function (value) {
        var selected = [];

        if (value) {
          var i = 0;
          this.dataTable.rowData.forEach(function (rowData) {
            selected.push(i++);
          });
        }
        this.selected = selected;
      },
    },
  },
  components: {
    JobContainer: JobContainer,
    SvgIcon: SvgIcon,
  },
  mounted() {
    this.init();
  },
};
</script>