<template>
  <div class="container rrmse-wrap" :style="isLoading ? { cursor: 'wait' } : {}">
    <!-- 로딩 시작 { -->
    <div v-if="isLoading" class="loading-overlay">
      <div class="loading-div">
        <span>LOADING</span>
        <span class="anima">.</span>
        <span class="anima">.</span>
        <span class="anima">.</span>
      </div>
    </div>
    <!-- } 로딩 종료 -->
    <div class="page-titleZone flex justify-between align-center align-start">
      <p class="main-title flex80">데이터 활용관리 {{ !isUpdatePage ? '등록' : '수정' }}</p>
    </div>
    <div class="content-wrap content flex100">
      <div class="custom-tab content-box">
        <div class="flex justify-start align-center no-gutter content-box">
          <!-- 네비게이션 시작 { -->
          <div class="column-nav flex5">
            <ul>
              <li v-for="(item, idx) in navList" :key="idx" @click="showTab('nav', item.id)" class="cursor">
                <a :class="{ activeTab: activeTab === item.id }" :title="item.name">
                  <svg-icon type="mdi" :path="item.iconPath" class="mb5"></svg-icon>
                  <p>{{ item.name }}</p>
                </a>
              </li>
            </ul>
          </div>
          <!-- } 네비게이션 종료 -->
          <!-- 네비게이션 화면 { -->
          <div class="content-box flex justify-between align-start flex95 no-gutter">
            <div :class="{
              'tab-zone flex align-start': true,
              flex30: accordion === false,
              flex0: accordion === true,
            }">
              <div class="content-box flex100 pl0" :style="accordion === true ? { display: 'none' } : ''">
                <div class="content-box flex justify-between tab-box overflow-y" v-show="activeTab === 'pageInfo'">
                  <div class="content-list layout flex100">
                    <div class="page-info content-box">
                      <div class="content-titleZone">
                        <div class="flex justify-between align-center">
                          <p class="box-title">페이지 정보</p>
                        </div>
                      </div>
                      <div class="info-area">
                        <div class="input-group mb10">
                          <label for="" class="mb10">제목</label>
                          <input type="text" name="" id="" class="full-input" v-model="customTitle" @input="customTitle = $event.target.value" />
                        </div>
                        <div class="input-group mb10">
                          <label for="" class="mb10">공개여부</label>
                          <div class="input-container flex">
                            <label class="radio-label">
                              <input type="radio" name="public_at" class="custom-radiobox" :value="true" v-model="public_at" />
                              <span>공개</span>
                            </label>
                            <label class="radio-label">
                              <input type="radio" name="public_at" class="custom-radiobox" :value="false" v-model="public_at" />
                              <span>비공개</span>
                            </label>
                          </div>
                        </div>
                        <div class="input-group" style="height: calc(100% - 150px)">
                          <label for="" class="mb10">설명</label>
                          <textarea name="" id="" cols="30" rows="35" v-model="customComment" @input="customComment = $event.target.value" class="content-box"></textarea>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
                <div class="content-box tab-box" v-show="activeTab === 'dataset'">
                  <div class="content-list content-box">
                    <VueFlowZoneGroup :diagramList="diagramList" :splitInfo="splitInfo" @axisData="handlerAxisData" @clickDiagramDataTable="getDiagramDataInfo" @selectedCal="changeSelectCal" @updateSplitInfo="updateSplitInfo" :layoutChartData="selectLayout" />
                  </div>
                </div>
                <div class="content-box flex justify-between tab-box" v-show="activeTab === 'viewSetting'">
                  <div class="content-list layout flex50">
                    <div class="layout-tree content-box">
                      <div class="content-titleZone">
                        <div class="flex justify-between align-center">
                          <p class="box-title">레이아웃 및 컴포넌트</p>
                          <div>
                            <button id="horizontal-btn" @click="addSplitterLayout($event, 'vertical')" title="수직레이아웃">
                              <img :src="verticalImg" />
                            </button>
                            <button id="vertical-btn" @click="addSplitterLayout($event, 'horizontal')" title="수평레이아웃">
                              <img :src="horizontalImg" />
                            </button>
                            <button id="split-delete-btn" @click="deleteSplitterLayout" title="삭제">
                              <svg-icon type="mdi" :path="trashPath" :color="'#aaa'"></svg-icon>
                            </button>
                            <button class="attribute-btn" @click="attributeSelected">
                              <svg-icon type="mdi" :path="dotPath" :color="'#aaa'"></svg-icon>
                              <div class="attribute-modal" v-show="attribute">
                                <ul>
                                  <li class="flex align-center">
                                    <svg-icon type="mdi" :path="tablePath"></svg-icon>
                                    <p class="ml5">테이블 추가</p>
                                  </li>
                                  <li class="flex align-center">
                                    <svg-icon type="mdi" :path="chartPath"></svg-icon>
                                    <p class="ml5">차트 추가</p>
                                  </li>
                                </ul>
                              </div>
                            </button>
                          </div>
                        </div>
                      </div>
                      <ul>
                        <TreeItem :splitInfo="splitInfo" :selectLayout="selectLayout" @changeselectLayout="changeselectLayout" />
                      </ul>
                    </div>
                  </div>
                  <div class="layout-option flex-column flex50">
                    <div class="tabnav3">
                      <ul class="flex justify-start align-center">
                        <li v-for="(nav, idx) in optionList" @click="showTab('opt', nav.name)" :key="idx" class="cursor">
                          <p :class="{
                            activeOption: activeOption === nav.name,
                          }">{{ nav.name }}</p>
                        </li>
                      </ul>
                    </div>
                    <div v-show="activeOption === '레이아웃'">
                      <StyleSheet :styleSheet="selectLayout.styleSheet" />
                    </div>
                    <div v-show="activeOption === '컴포넌트'">
                      <StyleSheet :styleSheet="selectLayout.styleSheet" />
                    </div>
                    <div v-show="activeOption === '타이틀'">
                      <TitleStyleSheet :component="selectLayout.component" v-if="selectLayout.component" />
                    </div>
                  </div>
                </div>
                <div class="content-box flex justify-between tab-box" v-show="activeTab === 'component'">
                  <div class="content-box overflow-y">
                    <ul class="flex justify-center">
                      <li v-for="(cmpnt, idx) in chartComponent" :key="idx" class="flex5 mt10 cursor" @click="
                        addComponent(idx, cmpnt.type, cmpnt.id, cmpnt.name)
                        ">
                        <div :class="{ 'img-wrap border': true, active: isActiveIndex(idx) }">
                          <img :src="cmpnt.src" alt="" />
                          <div class="img-hover">
                            <span>{{ cmpnt.name }}</span>
                          </div>
                        </div>
                      </li>
                    </ul>
                  </div>
                </div>
              </div>
              <button @click="accordionToggle" class="custom-toggle" :style="accordion === true ? { right: '-25px' } : { right: '-14px' }">
                <svg-icon type="mdi" :path="arrowPath" :color="'#333'"></svg-icon>
              </button>
            </div>
            <!-- 미리보기  -->
            <div :class="{
              'preview-zone': true,
              flex70: accordion === false,
              flex95: accordion === true,
            }">
              <div id="splitter-container" ref="splitterContainer" @click="handleSplitterComponentClick" :class="{ active: clickElement === 'splitter-container' }" class="splitter-panel-custom">
                <SplitterLayout id="SplitterLayout" :splitInfo="splitInfo_dumy" @changeselectLayout="changeselectLayout" :selectLayout="selectLayout" @parentInfo="parentInfo" :createChartData="createChartData">
                </SplitterLayout>
              </div>
              <div class="flex justify-end" id="buttonZone">
                <button v-if="!isUpdatePage" class="blue-btn small-btn" id="registerButton" @click="registerLayout">등록</button>
                <button v-else class="blue-btn small-btn" id="editButton" @click="registerLayout">수정</button>
                <button class="blue-border-btn small-btn" id="resetButton" @click="initClickEvent">초기화</button>
                <button class="darkg-btn small-btn" id="resetButton" @click="moveBack">취소</button>
              </div>
            </div>
            <!-- 미리보기  -->
          </div>
          <!-- } 네비게이션 화면 종료 -->
        </div>
      </div>
    </div>
  </div>
  <!-- 데이터 설정 모달 시작 { -->
  <div v-show="isModalOpen" class="modal-wrapper">
    <div class="modal-container">
      <div class="modal-title">
        <div class="flex justify-between align-center">
          <h2>데이터설정</h2>
          <button class="close-btn" @click="closeModal">
            <svg-icon type="mdi" :width="20" :height="20" :path="closePath"></svg-icon>
          </button>
        </div>
      </div>
      <div class="modal-content-monthly">
        <JobContainer :jobGroup="jobGroup" @getDataTable="getResult" />
      </div>
      <div class="modal-end flex justify-end">
        <button class="orange-btn small-btn">접속</button>
        <button class="blue-btn small-btn">확인</button>
      </div>
    </div>
  </div>
  <!-- } 데이터 설정 모달 종료 -->
</template>
<script>
import SplitterLayout from "../../component/SplitterLayoutDev.vue";
import JobContainer from "../../component/connection/jobContainer.vue";
import axios from "axios";
import store from "../AppStore";
import SvgIcon from "@jamescoyle/vue-icon";
import TreeItem from "../../component/LayoutTree.vue";
import { mdiChevronLeft, mdiChevronRight, mdiLandPlots, mdiRhombusSplit, mdiDatabaseCogOutline, mdiInformationSlabCircleOutline, mdiDotsVertical, mdiTableLarge, mdiChartLine, mdiDatabase, mdiTrashCanOutline, } from "@mdi/js";
import StyleSheet from "../../component/style/StyleSheetComponent.vue";
import TitleStyleSheet from "../../component/style/TitleStyleComponent.vue";
import BackgroundOption from "../../component/style/BackgroundOption.vue";
import CellOption from "../../component/style/CellOption.vue";
import FontOption from "../../component/style/FontOption.vue";
import VueFlowZoneGroup from "../../component/flowComponent/VueFlowZoneGroup.vue";
import _ from "lodash";
import chartDataTransform from "../../component/chart/chartDataTransform.js";
import html2canvas from "html2canvas";
import { split } from "lodash";

export default {
  openPopup: {
    type: Boolean,
    default: false,
  },
  data() {
    return {
      navList: [
        { id: "pageInfo", name: "페이지 정보", iconPath: mdiInformationSlabCircleOutline, },
        { id: "viewSetting", name: "레이아웃", iconPath: mdiLandPlots },
        { id: "component", name: "컴포넌트", iconPath: mdiRhombusSplit },
        { id: "dataset", name: "데이터", iconPath: mdiDatabaseCogOutline, },
      ],
      optionList: [
        { id: "layoutOption", name: "레이아웃", },
        { id: "titleOption", name: "타이틀", },
        { id: "componentOption", name: "컴포넌트", },
      ],
      activeTab: "pageInfo", // default 페이지 정보

      // 최상위 레이아웃 정보 담는 객체
      splitInfo: _.cloneDeep(this.$getDefaultJobGroup().customSplitter),
      splitInfo_dumy: _.cloneDeep(this.$getDefaultJobGroup().customSplitter),
      jobGroup: {},
      getDataTable: {},
      columnList: [],

      // 게시판 정보
      customTitle: null, // 제목
      customComment: null, // 설명

      selectLayout: {},
      arrowPath: mdiChevronLeft,
      accordion: false,
      horizontalImg: require("../../../resources/img/icon/hor_b.png"),
      verticalImg: require("../../../resources/img/icon/ver_b.png"),
      dotPath: mdiDotsVertical,
      tablePath: mdiTableLarge,
      chartPath: mdiChartLine,
      dataPath: mdiDatabase,
      attribute: false,
      dataItm: [],
      diagramList: [],
      chartComponent: [
        {
          src: require("../../../resources/img/chartIcon/column_chart_v.png"),
          type: "chart",
          id: "column_chart_v",
          name: "세로형 막대 차트",
        },
        {
          src: require("../../../resources/img/chartIcon/column_chart_h.png"),
          type: "chart",
          id: "column_chart_h",
          name: "가로형 막대 차트",
        },
        {
          src: require("../../../resources/img/chartIcon/clustered_chart_v.png"),
          type: "chart",
          id: "clustered_chart_v",
          name: "세로형 클러스터 차트",
        },
        {
          src: require("../../../resources/img/chartIcon/clustered_chart_h.png"),
          type: "chart",
          id: "clustered_chart_h",
          name: "가로형 클러스터 차트",
        },
        {
          src: require("../../../resources/img/chartIcon/stacked_bar_chart.png"),
          type: "chart",
          id: "stacked_bar_chart",
          name: "적층 막대 차트",
        },
        {
          src: require("../../../resources/img/chartIcon/line_chart.png"),
          type: "chart",
          id: "line_chart",
          name: "선 차트",
        },
        {
          src: require("../../../resources/img/chartIcon/mix_chart.png"),
          type: "chart",
          id: "mix_chart",
          name: "혼합 차트",
        },
        {
          src: require("../../../resources/img/chartIcon/pie_chart.png"),
          type: "chart",
          id: "pie_chart",
          name: "파이 차트",
        },
        {
          src: require("../../../resources/img/chartIcon/dounet_chart.png"),
          type: "chart",
          id: "dounet_chart",
          name: "도넛 차트",
        },
        {
          src: require("../../../resources/img/chartIcon/semicircle_chart.png"),
          type: "chart",
          id: "semicircle_chart",
          name: "반원 차트",
        },
        {
          src: require("../../../resources/img/chartIcon/bubble_chart.png"),
          type: "chart",
          id: "bubble_chart",
          name: "버블 차트",
        },
        {
          src: require("../../../resources/img/chartIcon/word_chart.png"),
          type: "chart",
          id: "word_chart",
          name: "단어 차트",
        },
        {
          src: require("../../../resources/img/chartIcon/stacked_column_chart.png"),
          type: "chart",
          id: "stacked_column_chart",
          name: "세로형 적층 막대 차트",
        },
        {
          src: require("../../../resources/img/chartIcon/node_line_chart.png"),
          type: "chart",
          id: "node_line_chart",
          name: "노드 라인 차트",
        },
        {
          src: require("../../../resources/img/chartIcon/liin_chart_back.png"),
          type: "chart",
          id: "liin_chart_back",
          name: "라인 백그라운드 차트",
        },
      ],
      activeIndex: null,
      dataCount: 1,
      isModalOpen: false,
      activeOption: "레이아웃",
      trashPath: mdiTrashCanOutline,

      // x, y축 (객체 형식으로 데이터 수정 필요)
      createChartData: _.cloneDeep(this.$getDefaultJobGroup().componentData),
      clickComponentParentInfo: {},
      rowData: [], // 선택한 다이어그램의 데이터 테이블을 담는 객체
      clickDiagramInfo: {}, // 선택한 다이어그램의 정보를 담는 객체

      pageId: null,
      isLoading: false,
      isUpdatePage: false,

      public_at: true,
    };
  },
  methods: {
    // 탭 전환
    showTab(type, current) {
      if (type == 'nav') {
        this.activeTab = current;
      } else if (type == 'opt') {
        this.activeOption = current;
      }
    },
    accordionToggle: function () {
      this.accordion = !this.accordion;
      if (!this.accordion) {
        this.arrowPath = mdiChevronLeft;
      } else {
        this.arrowPath = mdiChevronRight;
      }
    },
    setModal: function () {
      this.isModalOpen = true;
    },
    closeModal: function () {
      this.isModalOpen = false;
    },
    attributeSelected: function () {
      this.attribute = !this.attribute;
    },

    dataAdd: function () {
      this.dataItm.push("Data" + this.dataCount);
      this.dataCount++;
    },

    // 컴포넌트 추가
    addComponent: async function (index, type, id, name) {
      this.activeIndex = index;
      if (id == "bubble_chart") {
        this.$showAlert("메세지", "해당 차트는 현재 지원하지 않습니다.");
        return;
      }
      if (
        await this.$showConfirm(
          "컴포넌트 추가",
          id + "컴포넌트를 추가하시겠습니까?"
        )
      ) {
        if (this.selectLayout.children.length > 0) {
          this.$showAlert("메세지", "레이아웃이 존재합니다.");
          return;
        }
        if (this.selectLayout == null) {
          this.$showAlert("메세지", "선택된 레이아웃이 없습니다.");
          return;
        }
        this.selectLayout.component = {};
        this.selectLayout.se = "component";
        let component = _.cloneDeep(this.$getDefaultJobGroup().component);
        let chartData = _.cloneDeep(this.$getDefaultJobGroup().componentData);
        let jobGroup = _.cloneDeep(this.$getDefaultJobGroup().jobGroup);

        // 차트 생성 데이터 세팅 (chartName, componentName)
        chartData.chart_knd = id;
        chartData.component_nm = "ChartCmmn";
        chartData.component_type = type;

        component.component_itm = chartData;
        component.jobInfo = [];
        component.jobInfo.push(jobGroup);

        this.selectLayout.component = component;
      } else {
        this.getSelectLayoutChart();
      }
    },
    getSelectLayoutChart: function () {
      // 현재 선택된 컴포넌트 차트 정보로 변경
      if (this.selectLayout.se == "component") {
        if (!this.selectLayout.component.component_itm.chart_knd) {
          this.activeIndex = null;
          return;
        }
        this.chartComponent.forEach((item, index) => {
          if (item.id === this.selectLayout.component.component_itm.chart_knd) {
            this.activeIndex = index;
          }
        });
      }
    },

    isActiveIndex: function (index) {
      return this.activeIndex === index;
    },

    // 선택된 레이어웃 반환
    changeselectLayout: function (selectLayout) {
      this.selectLayout = selectLayout;
      // 차트 리스트 중 인덱스 찾아서 activeIndex에 할당
      this.getSelectLayoutChart();
    },

    // 클릭한 요소의 부모 정보를 받아오는 이벤트
    parentInfo: function (info) {
      this.clickComponentParentInfo = info;
    },

    // 레이아웃 아이콘 클릭에 따른 이벤트
    addSplitterLayout: async function (e, buttonType) {
      const vm = this;
      // vertical-btn, Horizon-btn 클릭에 따른 layoutVal 값 변경
      const clickBtn = e.currentTarget.id;

      let layoutVal = "horizontal";

      // 레이아웃 확장
      let extend = false;
      // 기존 active 제거
      if (this.activeElement) {
        this.activeElement.classList.remove("active-layout");
      }
      // 클릭된 요소에 active-layout 클래스 추가
      const targetClass = e.currentTarget.classList;
      targetClass.add("active-layout");

      this.activeElement = e.currentTarget;
      if (clickBtn == "horizontal-btn") {
        layoutVal = "horizontal";
      } else if (clickBtn == "vertical-btn") {
        layoutVal = "vertical";
      }

      // 버튼 클릭에 따른 버튼 이미지 변경
      if (buttonType === "horizontal") {
        this.verticalImg = require("../../../resources/img/icon/ver_b.png");
        this.horizontalImg = require("../../../resources/img/icon/hor_a.png");
      } else if (buttonType === "vertical") {
        this.horizontalImg = require("../../../resources/img/icon/hor_b.png");
        this.verticalImg = require("../../../resources/img/icon/ver_a.png");
      }

      // 유효성 검사
      if (this.selectLayout.layout_nm == null) {
        this.$showAlert("메세지", "선택된 레이아웃이 없습니다.");
        return;
      } else if (
        this.selectLayout.children.length > 0 ||
        this.selectLayout.se == "component"
      ) {
        if (
          await this.$showConfirm(
            "메세지",
            "선택된 레이아웃을 분할하시겠습니까?"
          )
        ) {
          extend = true;
        } else {
          return;
        }
      }

      // 선택된 객체 세팅
      const temp_layout = _.cloneDeep(this.selectLayout);
      this.selectLayout.se = "splitter";
      this.selectLayout.layout_type = _.cloneDeep(layoutVal);
      this.selectLayout.layout_size1 = 50;
      this.selectLayout.layout_size2 = 50;

      let tempChilds = [];
      // 자식요소 추가
      if (extend) {
        tempChilds = _.cloneDeep(this.selectLayout.children);
        this.selectLayout.children = [];
        this.selectLayout.layout_nm = Math.random()
          .toString(36)
          .substring(2, 15);
      }
      for (let i = 0; i < 2; i++) {
        let tempChild = _.cloneDeep(this.$getDefaultJobGroup().customSplitter);
        tempChild.depth = this.selectLayout.depth + 1;
        tempChild.parents_splitter_id = this.selectLayout.layout_nm;
        tempChild.position_idx = i;
        tempChild.styleSheet.borderStyle = _.cloneDeep(
          this.$getDefaultJobGroup().borderStyle
        );
        tempChild.styleSheet.background_style = _.cloneDeep(
          this.$getDefaultJobGroup().background_style
        );
        if (extend && i == 0) {
          tempChild.layout_nm = temp_layout.layout_nm;
          tempChild.se = temp_layout.se;
          tempChild.component = _.cloneDeep(this.selectLayout.component);
          tempChild.layout_type = temp_layout.layout_type;
          this.selectLayout.component = null;
          tempChild.children = tempChilds;
          this.selectLayout.children.push(tempChild);
        } else {
          tempChild.layout_nm = Math.random().toString(36).substring(2, 15);
          tempChild.se = "splitter";
          tempChild.children = [];
          this.selectLayout.children.push(tempChild);
        }
      }
    },

    registerLayout: function () {
      let vm = this;
      // 유효성 검사
      if (vm.customTitle == null || vm.customTitle == "") {
        vm.$showAlert("메세지", "제목은 필수입력입니다.");
        return;
      }
      if (vm.splitInfo.component == null && vm.splitInfo.children.length == 0) {
        vm.$showAlert("메세지", "레이아웃 또는 차트를 추가해야합니다.");
        return;
      }
      if (vm.pageId) {
        // 저장 로직 구현
        let vm = this;
        // 캡처할 요소
        let element = document.getElementById("splitter-container");

        // html2canvas 사용하여 element 캡처
        html2canvas(element).then((canvas) => {
          // 캔버스를 Blob 데이터로 변환
          canvas.toBlob(function (blob) {
            let imgUrl = blob;

            let formData = new FormData();
            formData.append("img", imgUrl, "capture.png"); // Blob 데이터 사용

            formData.append("page_id", vm.pageId);
            formData.append("ttl", vm.customTitle);
            formData.append("cn", vm.customComment);
            formData.append("mdfcn_id", store.state.loginUser.user_id);
            formData.append("splitInfo", JSON.stringify(vm.splitInfo)); // JSON 문자열로 변환
            formData.append(
              "jobFlow",
              JSON.stringify({ jobGroup: vm.diagramList })
            ); // JSON 문자열로 변환
            formData.append("public_at", vm.public_at);

            axios({
              url: "/custom/customUpdate",
              method: "post",
              headers: {
                "Content-Type": "multipart/form-data",
              },
              data: formData,
            })
              .then(function (response) {
                if (response.data.checkMessage.success) {
                  vm.$showAlert("메세지", "페이지 수정에 성공하였습니다.");
                  vm.$router.push({
                    path: "/customSelectOne.page",
                    query: { page_id: vm.pageId },
                  });
                } else {
                  vm.$showAlert("메세지", "수정에 실패하였습니다.");
                }
              })
              .catch(function (error) {
                if (error.response.data.code == "COMPONENT_DATA_NOT_FOUND") {
                  vm.$showAlert(
                    "메세지",
                    "데이터를 추가하지 않은 컴포넌트가 존재합니다."
                  );
                }
              });
          });
        });
      } else {
        // canvas로 화면 이미지 저장하여 같이 저장
        let vm = this;
        // 캡처할 요소
        let element = document.getElementById("splitter-container");

        // html2canvas 사용하여 element 캡처
        html2canvas(element).then((canvas) => {
          // 캔버스를 Blob 데이터로 변환
          canvas.toBlob(function (blob) {
            let imgUrl = blob;

            let formData = new FormData();
            formData.append("img", imgUrl, "capture.png"); // Blob 데이터 사용

            formData.append("ttl", vm.customTitle);
            formData.append("cn", vm.customComment);
            formData.append("wrt_id", store.state.loginUser.user_id);
            formData.append("splitInfo", JSON.stringify(vm.splitInfo)); // JSON 문자열로 변환
            formData.append(
              "jobFlow",
              JSON.stringify({ jobGroup: vm.diagramList })
            ); // JSON 문자열로 변환
            formData.append("public_at", vm.public_at);

            axios({
              url: "/custom/insert",
              method: "post",
              headers: {
                "Content-Type": "multipart/form-data",
              },
              data: formData,
            })
              .then(function (response) {
                if (response.data.checkMessage.success) {
                  let createPageId = response.data.resultData.pageId;
                  vm.$showAlert("메세지", "페이지 등록에 성공하였습니다.");
                  vm.$router.push({
                    path: "/customSelectOne.page",
                    query: { page_id: createPageId },
                  });
                } else {
                  vm.$showAlert("메세지", "등록에 실패하였습니다.");
                }
              })
              .catch(function (error) {
                if (error.response.data.code == "COMPONENT_DATA_NOT_FOUND") {
                  vm.$showAlert(
                    "메세지",
                    "데이터를 추가하지 않은 컴포넌트가 존재합니다."
                  );
                }
              });
          });
        });
      }
    },

    // 초기화
    init: async function () {
      const defaultJobGroupData = await this.$getDefaultJobGroup();

      this.splitInfo = _.cloneDeep(defaultJobGroupData.customSplitter);
      this.splitInfo_dumy = _.cloneDeep(defaultJobGroupData.customSplitter);

      this.splitInfo.layout_nm = "split_0";
      this.splitInfo.se = "splitter";
      this.splitInfo.position_idx = 1;
      this.splitInfo.depth = 0;
      this.splitInfo.styleSheet.borderStyle = _.cloneDeep(
        defaultJobGroupData.borderStyle
      );
      this.splitInfo.styleSheet.background_style = _.cloneDeep(
        defaultJobGroupData.background_style
      );

      this.splitInfo_dumy.layout_nm = "dumy";
      this.splitInfo_dumy.se = "splitter";
      this.splitInfo_dumy.children.push(this.splitInfo);

      this.selectLayout = this.splitInfo;
      // 데이터 관리 초기화
      this.diagramList = [];
    },
    initClickEvent: async function () {
      if (
        await this.$showConfirm(
          "초기화",
          "초기화 하시겠습니까? 데이터가 모두 삭제됩니다."
        )
      ) {
        this.init();
      }
    },
    // 축 데이터 가져오기
    handlerAxisData: function (axis) {
      let vm = this;
      let changeData = _.cloneDeep(vm.selectLayout.component.component_itm);

      changeData.categoryAxis = axis.dataX;
      changeData.valueAxis = axis.dataY;

      // 축 데이터를 이용한 차트 데이터 생성
      changeData.data_list = chartDataTransform.createData(
        vm.rowData,
        changeData.categoryAxis,
        changeData.valueAxis,
        "null"
      );

      vm.selectLayout.component.component_itm = changeData;
      // 선택한 데이터 테이블 정보 컴포넌트에 저장
      //같은 데이터 테이블 정보가 있는지 확인하고 없으면 넣고 있으면 넣지 않음
      let selectedJob = this.clickDiagramInfo;
      this.selectLayout.component.jobInfo[0] = selectedJob;
      // if(this.createChartData.);
    },
    // 다이어그램 데이터 테이블 정보 가져오기
    getDiagramDataInfo: function (data) {
      this.clickDiagramInfo = data;
      if (data.dataTable != null) {
        this.rowData = data.dataTable.rowData;
      }
    },
    changeSelectCal: function (cal) {
      let changeData = _.cloneDeep(this.selectLayout.component.component_itm);

      changeData.chart_cal = cal;
      this.selectLayout.component.component_itm = changeData;
    },
    getCustomData: function () {
      const vm = this;
      this.isUpdatePage = true;

      axios({
        url: "/custom/customPageUpdateSelect",
        method: "post",
        headers: {
          "Content-Type": "application/json; charset=UTF-8",
        },
        // 객체 형태로 감싸서 데이터 전송
        data: { page_id: vm.pageId },
      })
        .then(function (response) {
          let resPageInfo = response.data.resultData.pageInfo;
          let resdiagramList = response.data.resultData.diagramList;
          let resSplitterInfo = response.data.resultData.splitterInfo;

          vm.customTitle = resPageInfo.ttl;
          vm.customComment = resPageInfo.cn;

          vm.splitInfo = resSplitterInfo;

          vm.splitInfo_dumy.layout_nm = "dumy";
          vm.splitInfo_dumy.se = "splitter";
          vm.splitInfo_dumy.children.push(vm.splitInfo);

          vm.diagramList = resdiagramList;

          vm.selectLayout = vm.splitInfo;
          vm.isLoading = false;
          vm.public_at = resPageInfo.public_at;
          vm.getSelectLayoutChart();
        })
        .catch(function (error) {
          vm.isLoading = false;
          vm.$showAlert(
            "데이터 현황관리 차트 연결",
            "데이터 현황관리 차트 연결 오류, 관리자에게 문의하세요."
          );
          vm.$router.go(-1); // 오류 시 이전 페이지로 이동
        });
    },
    // 레이아웃 삭제
    deleteSplitterLayout: async function () {
      if (!this.selectLayout.layout_nm) {
        this.$showAlert("메세지", "삭제할 레이아웃이 없습니다.");
        return;
      }
      if (!this.selectLayout.parents_splitter_id) {
        this.$showAlert("메세지", "최상위 레이아웃은 삭제할 수 없습니다.");
        return;
      }
      if (
        await this.$showConfirm(
          "레이아웃 삭제",
          "선택한 레이아웃을 삭제하시겠습니까?"
        )
      ) {
        let parentLayout = this.findParentLayout(
          this.splitInfo,
          this.selectLayout.parents_splitter_id
        );
        //선택한 레이아웃의 형제정보 찾기
        let otherIdx = parentLayout.children.findIndex(
          (item) => item.layout_nm !== this.selectLayout.layout_nm
        );
        let otherSplit = parentLayout.children[otherIdx];
        //otherSplit의 component, children 정보 가져오기
        let otherComponent = otherSplit.component;
        let otherChildren = otherSplit.children;
        let layoutSize1 = otherSplit.layout_size1;
        let layoutSize2 = otherSplit.layout_size2;
        let layoutType = otherSplit.layout_type;
        let se = otherSplit.se;
        let size = otherSplit.size;
        let styleSheet = otherSplit.styleSheet;

        // 부모 레이아웃에 다른 split의 정보 넣어 주기
        parentLayout.component = otherComponent;
        parentLayout.children = otherChildren;
        parentLayout.layout_size1 = layoutSize1;
        parentLayout.layout_size2 = layoutSize2;
        parentLayout.layout_type = layoutType;
        parentLayout.se = se;
        parentLayout.size = size;
        parentLayout.styleSheet = styleSheet;

        // 자식에게서 가져온 자식의 자식 정보의 부모 정보 변경
        if (parentLayout.children.length > 0) {
          parentLayout.children.forEach((item) => {
            item.parents_splitter_id = parentLayout.layout_nm;
          });
        }
      }
    },

    // 삭제할 레이아웃의 부모 레이아웃을 찾는 재귀 함수
    findParentLayout: function (splitInfo, selectParentLayoutId) {
      const vm = this;

      // splitInfo가 배열인 경우 각 요소에 대해 재귀적으로 함수를 호출
      if (Array.isArray(splitInfo)) {
        for (let i = 0; i < splitInfo.length; i++) {
          let result = this.findParentLayout(
            splitInfo[i],
            selectParentLayoutId
          );
          if (result) return result; // 일치하는 부모 레이아웃을 찾으면 반환
        }
      } else {
        // 현재 splitInfo 객체의 layout_nm이 찾고자 하는 selectParentLayoutId와 일치하는지 확인
        if (splitInfo.layout_nm === selectParentLayoutId) {
          return splitInfo; // 일치하는 경우 현재 객체 반환
        }

        // 현재 객체의 자식들에 대해 재귀적으로 탐색
        if (splitInfo.children && splitInfo.children.length > 0) {
          return this.findParentLayout(
            splitInfo.children,
            selectParentLayoutId
          );
        }
      }

      // 일치하는 요소를 찾지 못한 경우
      return null;
    },
    moveBack: async function () {
      if (await this.$showConfirm("이전으로", "이전으로 돌아가시겠습니까?")) {
        this.$router.go(-1);
      }
    },
    updateSplitInfo: function (splitInfo) {
      this.splitInfo = splitInfo;
    },
  },
  watch: {
    splitInfo: {
      handler: function (newVal, oldVal) {
        this.splitInfo_dumy = _.cloneDeep(
          this.$getDefaultJobGroup().customSplitter
        );
        this.splitInfo_dumy.layout_nm = "dumy";
        this.splitInfo_dumy.se = "splitter";
        this.splitInfo_dumy.children.push(newVal);
      },
      deep: true,
    },
    splitInfo_dumy: { deep: true },
  },
  components: {
    SplitterLayout,
    JobContainer: JobContainer,
    SvgIcon: SvgIcon,
    TreeItem: TreeItem,
    BackgroundOption: BackgroundOption,
    CellOption: CellOption,
    FontOption: FontOption,
    StyleSheet: StyleSheet,
    TitleStyleSheet: TitleStyleSheet,
    VueFlowZoneGroup: VueFlowZoneGroup,
  },
  created: function () {
    this.pageId = this.$route.query.page_id;
    this.jobGroup = this.$getDefaultJobGroup().jobGroup;
    this.activeTab = "pageInfo";

    if (this.pageId != null && this.pageId != undefined) {
      this.getCustomData(); // 기존 데이터 가져오기
    } else {
      this.init();
    }
  }
};
</script>
<style scoped>
#splitter-container {
  width: 100%;
  height: calc(100% - 50px);
  margin-bottom: 20px;
}

#SplitterLayout {
  width: 100%;
  height: 100%;
}

#splitter-container.active {
  border: 3px dotted red;
}

.padding-1 {
  padding: 1rem;
}

#customComment {
  height: 99px;
}

.table-padding {
  padding: 15px 0;
}

.paletteLi {
  display: inline-block;
  margin-right: 10px;
}

.img-wrap {
  position: relative;
}

.img-wrap:hover .img-hover {
  display: flex;
}

.img-wrap .img-hover {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #213f9999;
  display: none;
  align-items: center;
  justify-content: center;
}

.img-wrap .img-hover span {
  padding: 10px;
  text-align: center;
  font-size: 1.5em;
  color: #FFFFFF;
  word-break: keep-all;
}
</style>