<template>
  <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="close">
            <svg-icon type="mdi" :width="20" :height="20" :path="closePath"></svg-icon>
          </button>
        </div>
      </div>
      <div class="modal-content-monthly">
        <!-- <JobContainer :jobGroup="diagram" @getDataTable="getResult" /> -->
        <div class="text-rg mb10"><button class="blue-border-btn small-btn" @click="fnOpenAddModal">아이템 추가</button></div>
        <div class="data-list" style="height: 100px;">
          <ul class="flex">
            <li v-for="(item, idx) in crrentJobGroup" :key="idx" class="flex50">
              <div class="item flex justify-between align-center">
                <p>{{ idx + 1 + ". " + fnFindTypeName(item.type) }}</p>
                <div>
                  <button class="blue-border-btn set-btn" @click="fnOpenSetupModal(idx)">설정</button>
                  <button class="red-border-btn set-btn" @click="deleteConnect(idx)">삭제</button>
                </div>
              </div>
            </li>
          </ul>
        </div>
        <!-- 노드 셋업 모달 -->
        <DatabaseConnection v-if="selectNode.type == 'dbConnection'" :openPopup="isSetupModalOpen" :jobItem="selectNode" @closePopup="fnCloseSetupModal" @saveNodeData="fnUpdateSetup" />
        <datasetSelecter v-if="selectNode.type === 'datasetRead'" :openPopup="isSetupModalOpen" :jobItem="selectNode" @closePopup="fnCloseSetupModal" @saveNodeData="fnUpdateSetup" />
        <DataFilter v-if="selectNode.type == 'dataFilter'" :openPopup="isSetupModalOpen" :jobItem="selectNode" :nodes="crrentJobGroup" :edges="fnFindEdges()" @fnCloseModal="fnCloseSetupModal" @fnSaveSetup="fnUpdateSetup" />
      </div>
      <div class="modal-end flex justify-end">
        <button class="blue-btn small-btn" @click="execModel">저장</button>
        <button class="blue-border-btn small-btn" @click="close">취소</button>
      </div>
    </div>
  </div>
  <!-- 아이템 추가 모달 -->
  <div v-show="isAddModalOpen" class="modal-wrapper">
    <div class="modal-container small-modal">
      <div class="modal-title">
        <div class="flex justify-between align-center">
          <h2>아이템 선택</h2>
          <button class="close-btn" @click="itmSelectModal = false">X</button>
        </div>
      </div>
      <div class="modal-content-monthly">
        <select class="square-select full-select" v-model="selectItem">
          <option v-for="(item, idx) of nodeTypes" :key="idx" :value="item.id">{{ item.name }}</option>
        </select>
      </div>
      <div class="modal-end flex justify-end">
        <button class="blue-btn small-btn" @click="fnAddNodeCheckBtn">확인</button>
        <button class="blue-border-btn small-btn" @click="fnCloseAddModal">취소</button>
      </div>
    </div>
  </div>
</template>
<script>
import SvgIcon from "@jamescoyle/vue-icon";
import { mdiClose, mdiTrashCan, mdiCog } from "@mdi/js";
import JobContainer from "../../component/connection/jobContainer.vue";
// 모달용
import DatabaseConnection from "../connection/itm/databaseConnection.vue";
import FileSelect from "../connection/itm/fileSelect.vue";
import datasetSelecter from "../../component/connection/itm/datasetSelecter.vue";

export default {
  props: {
    isModalOpen: {
      type: Boolean,
      default: false,
    },
    diagram: {
      type: Object,
      default: {},
    },
  },
  data() {
    return {
      activeTab: "tab1",
      modalType: "tab-modal",
      closePath: mdiClose,

      // 노드 추가
      isAddModalOpen: false, // 노드 추가 모달 열림 여부(true:열림/false:닫힘)
      originalNodeTypeList: [],
      nodeTypeList: [],
      selectItem: "datasetRead", // 노드 추가값
      // 노드 수정
      isSetupModalOpen: false, // 노드 설정 모달 열림 여부(true:열림/false:닫힘)
      nodeTypes: [
        { id: "dbConnection", name: "DB 조회" },
        { id: "datasetRead", name: "데이터셋 조회" },
        { id: "dataFilter", name: "데이터 필터" },
      ],
      selectNode: {}, // 선택된 아이템
      selectNodeIndex: null, // 선택된 아이템 인덱스

      crrentJobGroup: [],

      popupToggls: [],
      itmSelectModal: false,
      defaultJobGroup: Object,
      defaultJobItm: Object,
      delPath: mdiTrashCan,
      setPath: mdiCog,
    };
  },
  methods: {
    close() {
      this.$emit("close", false);

      // 초기화
      this.crrentJobGroup = [];
      this.selectNode = {};
      this.selectNodeIndex = null;
    },
    // ***** ***** 모달용 메소드
    fnFindTypeName(id) {
      for (let node of this.nodeTypes) {
        if (node.id == id) {
          return node.name
        }
      }
      return null
    },

    // 노드 추가
    fnOpenAddModal() {
      this.isAddModalOpen = true;
    },
    // 노드 추가 모달 닫기
    fnCloseAddModal() {
      this.isAddModalOpen = false;
      this.selectItem = "datasetRead"; // 초기화
    },
    // 아이템 추가
    fnAddNodeCheckBtn() {
      // DB수집 개수 확인 (2개 이상인 경우 아이템 추가 취소)
      if (this.selectItem == "datasetRead") {
        for (let jobItm of this.crrentJobGroup) {
          if (jobItm.type == "datasetRead") {
            this.$showAlert("오류", "더이상 DB수집 아이템을 추가할 수 없습니다.");
            return;
          }
        }
      }
      var type = this.selectItem;
      let newItm = JSON.parse(JSON.stringify(this.$getDefaultJobGroup().jobItem));
      newItm.type = type;
      newItm.indx = this.crrentJobGroup.length + 1;


      if (type == "dbConnection") { // DB 조회
        newItm.itm = Object.assign({}, this.$getDefaultJobGroup().connectionDb);
      } else if (type == "datasetRead") { // 데이터셋 조회
        newItm.itm = Object.assign({}, this.$getDefaultJobGroup().DatasetPost);
      } else if (type == "dataFilter") { // 데이터 필터
        newItm.itm = Object.assign({}, this.$getDefaultJobGroup().dataFilter);
        newItm.itm.match_type = true;
      }

      if (this.crrentJobGroup.length > 0 && this.diagram.datasetPost_id == null) {
        newItm.front_dataTable = this.crrentJobGroup[this.crrentJobGroup.length - 1].dataTable;
      }

      this.crrentJobGroup.push(newItm);

      // 아이템 선택 모달 닫기
      this.fnCloseAddModal();
    },

    // 노드 설정 모달 열기
    fnOpenSetupModal(idx) {
      let nodes = this.crrentJobGroup;
      this.selectNode = nodes[idx];
      this.selectNodeIndex = idx;
      this.isSetupModalOpen = true;
    },
    // 노드 설정 모달 닫기
    fnCloseSetupModal() {
      this.selectNode = {}; // 초기화
      this.selectNodeIndex = null; // 초기화
      this.isSetupModalOpen = false;
    },
    // 노드 설정 저장 후 닫기
    fnUpdateSetup(jobItem) {
      let nodes = this.crrentJobGroup;
      nodes[this.selectNodeIndex] = jobItem;
      this.fnCloseSetupModal();
    },

    getDefaultJobGroup: function () {
      if (this.diagram == null) {
        this.crrentJobGroup = JSON.parse(JSON.stringify(this.diagram));
      }
      this.defaultJobGroup = JSON.parse(JSON.stringify(this.$getDefaultJobGroup().jobGroup));
      this.defaultJobItm = JSON.parse(JSON.stringify(this.$getDefaultJobGroup().jobItem));
    },

    execModel: function () {
      if (this.crrentJobGroup.length > 0) {
        this.diagram.dataTable = this.crrentJobGroup[this.crrentJobGroup.length - 1].dataTable;
      } else {
        this.diagram.dataTable = [];
      }
      this.diagram.jobItm = this.crrentJobGroup;
      this.$emit("updateData", this.diagram);
      this.close();
    },

    deleteConnect: function (indx) {
      this.crrentJobGroup.splice(indx, 1);
    },
  },
  mounted() {
    this.getDefaultJobGroup();
  },
  watch: {
    isModalOpen() {
      if (this.diagram.jobItm != null && this.diagram.jobItm != []) {
        this.crrentJobGroup = JSON.parse(JSON.stringify(this.diagram.jobItm));
      }
    },
  },
  components: {
    SvgIcon: SvgIcon,
    FileSelect: FileSelect,
    JobContainer: JobContainer,
    datasetSelecter: datasetSelecter,
    DatabaseConnection: DatabaseConnection,
  },
};
</script>