<template>
  <div class="data-set pt10 pb10" style="border-bottom: 1px solid #ddd">
    <div class="flex100 content-box">
      <div class="content-titleZone">
        <div class="flex justify-between align-center">
          <p class="box-title">데이터 관리</p>
          <button class="blue-border-btn small-btn" @click="dataAdd"> 데이터 추가 </button>
        </div>
      </div>
      <div class="data-list">
        <ul class="flex">
          <li v-for="(diagram, idx) in diagramList" :key="idx" class="flex50 mb5" @click="clickDiagram(diagram)">
            <div class="item flex justify-between align-center" :class="{
              selectData: diagram.group_nm == selectDiagram.group_nm,
            }">
              <p class="flex align-center">
                <svg-icon type="mdi" :path="dataPath"> </svg-icon>
                <span>{{ diagram.group_nm }}</span>
              </p>
              <div>
                <button class="blue-border-btn set-btn" @click="setModal(diagram)">설정</button>
                <button class="red-border-btn set-btn" @click="deleteDiagram(diagram)">삭제</button>
              </div>
            </div>
          </li>
        </ul>
      </div>
    </div>
  </div>
  <div class="column-list flex no-gutter">
    <div class="content-box flex50 pt10 pb10" style="border-right: 1px solid #ddd">
      <div class="flex100 content-box">
        <p class="box-title mb10">컬럼정보</p>
        <ul class="overflow-y" style="height: calc(100% - 29px)" v-if="columns != []">
          <li class="item mb5" v-for="(column, indx) in columns" :key="indx" @dragstart="startDrag($event, column, indx)" draggable="true">
            <p>{{ column.displyColumnNm }} : [{{ column.dataTy }}]</p>
          </li>
        </ul>
        <ul class="overflow-y" style="height: calc(100% - 29px)" v-else>
          <li class="item mb5">
            <p>NO_DATA</p>
          </li>
        </ul>
      </div>
    </div>
    <div class="content-box flex50 pt10 pb10">
      <div class="flex100 content-box flex-column no-gutter overflow-y">
        <div>
          <div class="editor-box content-box pd10 mb5" style="display: flex" @drop.prevent="onDrop($event, 'xdata')" @dragenter.prevent @dragover.prevent>
            <input type="radio" class="selectCal" id="default" value="default" v-model="selectedCal" /> default<br />
            <input type="radio" class="selectCal" id="sum" value="sum" v-model="selectedCal" /> Sum<br />
            <input type="radio" class="selectCal" id="avg" value="avg" v-model="selectedCal" /> Average<br />
            <input type="radio" class="selectCal" id="min" value="min" v-model="selectedCal" /> Min<br />
            <input type="radio" class="selectCal" id="max" value="max" v-model="selectedCal" /> Max<br />
          </div>
        </div>
        <div class="flex30">
          <div class="editor-box content-box pd10" @drop.prevent="onDrop($event, 'xdata')" @dragenter.prevent @dragover.prevent>
            <p class="object-title mb5">수직(Category)</p>
            <ul class="overflow-y" style="height: calc(100% - 29px)" v-if="dataX.length > 0">
              <li class="item mb5" v-for="(column, indx) in dataX" :key="indx">
                <p>{{ column.displyColumnNm }} : [{{ column.dataTy }}]</p>
                <div>
                  <button class="red-border-btn set-btn" @click="deleteItem(column, 'x')"> 삭제 </button>
                </div>
              </li>
            </ul>
            <ul class="overflow-y" style="height: calc(100% - 29px)" v-else>
              <li class="item mb5">
                <p>NO_DATA</p>
              </li>
            </ul>
          </div>
        </div>
        <div class="flex30 mt10">
          <div class="editor-box content-box pd10" @drop.prevent="onDrop($event, 'ydata')" @dragenter.prevent @dragover.prevent>
            <p class="object-title mb5">수평(Value)</p>
            <ul class="overflow-y" style="height: calc(100% - 29px)" v-if="dataY.length > 0">
              <li class="item mb5" v-for="(column, indx) in dataY" :key="indx">
                <p>{{ column.displyColumnNm }} : [{{ column.dataTy }}]</p>
                <div>
                  <button class="red-border-btn set-btn" @click="deleteItem(column, 'y')"> 삭제 </button>
                </div>
              </li>
            </ul>
            <ul class="overflow-y" style="height: calc(100% - 16px)" v-else>
              <li class="item mb5 orange">
                <p>column</p>
              </li>
            </ul>
          </div>
        </div>
        <div class="flex30 mt10">
          <div class="editor-box content-box pd10">
            <p class="object-title mb5">다음으로 색상 지정</p>
            <ul class="overflow-y" style="height: calc(100% - 16px)">
              <li class="item mb5">
                <p>column</p>
              </li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  </div>
  <VueFlowZonePopup :isModalOpen="isModalOpen" :diagram="currentDiagram" @updateData="dataUpdate" @close="close" />
</template>
<script>
import { mdiDatabase } from "@mdi/js";
import VueFlowZonePopup from "./VueFlowZonePopup.vue";
import TemplateGuide from "../../template/guide/TemplateGuide.vue";

export default {
  props: {
    diagramList: {
      type: Array,
      default: [],
    },
    layoutChartData: {
      type: Object,
      default: {},
    },
    splitInfo: {
      type: Object,
      default: {}
    }
  },
  data() {
    return {
      comId:
        "comId_" +
        Math.random().toString(36).substring(2, 15) +
        Math.random().toString(36).substring(2, 15),
      diagramListModel: [],
      selectDiagram: _.cloneDeep(this.$getDefaultObject().jobGroup),
      idIndex: 0,
      dataPath: mdiDatabase,
      dragData: {},
      columns: [], // 데이터 컬럼 정보 리스트 (선택 다이어그램에 따라 변경됨)
      dataX: [], // x축 데이터 리스트
      dataY: [], // y축 데이터 리스트
      selectedCal: "", // 선택된 계산 방법

      isModalOpen: false,
      currentDiagram: {},
    };
  },
  methods: {
    // 다이어 그램 추가
    dataAdd: function () {
      const temp = _.cloneDeep(this.$getDefaultObject().jobGroup);
      temp.group_nm = "데이터" + ++this.idIndex;
      this.diagramList.push(temp);
    },

    close() {
      this.currentDiagram = {};
      this.isModalOpen = false;
    },
    // 모달 오픈
    setModal: function (diagram) {
      this.currentDiagram = diagram;
      this.isModalOpen = true;
    },

    // 다이어그램 선택
    clickDiagram: function (diagram) {
      // 다이어그램 선택에 따라 컬럼 리스트가 변경되어야함
      this.selectDiagram = diagram;
      if (diagram.dataTable != null) {
        this.columns = diagram.dataTable.columnDatas;
      } else {
        this.columns = [];
      }
      // 다이어그램 선택에 따른 데이터 테이블 정보를 가져와야함
      this.$emit("clickDiagramDataTable", diagram);
    },

    // 데이터 내용 및 선택 데이터 변경시 이벤트
    dataUpdate: function (diagram) {
      // diagram 데이터 적용시 가지고오는 데이터 테이블 정보
      if (diagram.dataTable != null) {
        this.columns = diagram.dataTable.columnDatas;
      } else {
        this.columns = [];
      }
      this.$emit("clickDiagramDataTable", diagram);
    },

    // 드래그 이벤트
    startDrag: function (event, data, indx) {
      this.dragData = _.cloneDeep(data);
      this.dragData.columnIdx = indx;
    },

    // 드랍 이벤트
    onDrop: async function (event, idx) {
      if (idx == "xdata") {
        if (this.dataX.length > 0) {
          if (
            await this.$showConfirm(
              " Category변경",
              "Category 데이터를 변경하시겠습니까?"
            )
          ) {
            this.dataX = [];
            this.dataX.push(_.cloneDeep(this.dragData));
          }
        }
        this.dataX.push(_.cloneDeep(this.dragData));
      } else if (idx == "ydata") {
        if (this.dragData.dataTy === "STRING") {
          this.$showAlert("메세지", "Value에는 숫자 데이터만 사용 가능합니다.");
          return;
        }
        this.dataY.push(_.cloneDeep(this.dragData));
      }

      this.$emit("axisData", { dataX: this.dataX, dataY: this.dataY });
    },

    // 아이템 삭제
    deleteItem: function (column, category) {
      if (category == "x") {
        for (let i = 0; i < this.dataX.length; i++) {
          if (this.dataX[i].orginlColumnNm == column.orginlColumnNm) {
            this.dataX.splice(i, 1);
          }
        }
      } else if (category == "y") {
        for (let i = 0; i < this.dataY.length; i++) {
          if (this.dataY[i].orginlColumnNm == column.orginlColumnNm) {
            this.dataY.splice(i, 1);
          }
        }
      }
    },
    async deleteDiagram(item) {
      if (await this.$showConfirm("삭제", "선택한 데이터를 삭제하시겠습니까?\n관련된 데이터도 함께 삭제됩니다.")) {
        const index = this.diagramList.indexOf(item);
        // splitInfo에 적용했던 데이터가 있는지 확인하여 삭제 (재귀)
        if (this.splitInfo.children.length > 0) {
          this.RecursiveFunc(this.splitInfo.children, item);
        }
        if (this.splitInfo.component != null) {
          if (this.splitInfo.component.jobInfo[0].group_nm == item.group_nm) {
            this.splitInfo.component = null;
            this.splitInfo.se = "splitter";
          }
        }
        this.diagramList.splice(index, 1);
        this.columns = [];
      }
    },
    RecursiveFunc: function (children, item) {
      // 재귀함수
      for (let i = 0; i < children.length; i++) {
        if (children[i].children.length > 0) {
          this.RecursiveFunc(children[i].children, item);
        }
        else {
          if (children[i].component != null) {
            // children[i].jobInfo 와 item이 같은지 확인하여 삭제
            if (children[i].component.jobInfo[0].group_nm == item.group_nm) {
              children[i].component = null;
              children[i].se = "splitter";

            }
          }
        }
      }
    }
  },
  watch: {
    diagramList: function (v) {
      this.idIndex = v.length;
    },
    layoutChartData: {
      handler: function () {
        if (this.layoutChartData.component != null) {
          this.dataX = this.layoutChartData.component.component_itm.categoryAxis;
          this.dataY = this.layoutChartData.component.component_itm.valueAxis;
          this.selectedCal = this.layoutChartData.component.component_itm.chart_cal;
        } else {
          this.dataX = [];
          this.dataY = [];
          this.selectedCal = "default";
        }
      },
      deep: true,
    },
    selectedCal: function (v) {
      if (this.layoutChartData.component != null) {
        this.$emit("selectedCal", v);
      }
    },
  },
  components: {
    VueFlowZonePopup: VueFlowZonePopup,
  },
};
</script>
<style scoped>
.selectData {
  border: solid 2px #5d5c5c;
  color: #ffffff;
  background-color: #ff9e29;
}
</style>
