<!-- 2024.02.16 PJH -->
<template>
  <div style="width: 100%; height: 100%; position:relative">
    <div class="setting-modal cursor" @click="modalOpen"
      style="width:30px; height:30px; position:absolute; top:1%; right:1%;z-index:2;"> <svg-icon type="mdi" :path="path"
        :color="'#fff'"></svg-icon></div>
    <!-- unity iframe 삽입 -->
    <div data-type="column" :id="parent.layoutNm + '-Value'" @click="optionChangeClick"
      style="width: 100%; height: 100%; ">
      <iframe ref="unity1" data-type="column" src="http://192.168.0.81:8080/" frameborder="0"
        style="width: 100%; height: 100%">
      </iframe>
    </div>
  </div>

  <!-- 모달 -->
  <div v-show="isModal" 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="modalClose">X</button>
        </div>
      </div>
      <div class="modal-content-monthly">
        <div class="flex-column justify-between">
          <div class="flex50">
            <iframe ref="unity2" id="unityIframe" src="http://192.168.0.81:8080/" frameborder="0"
              style="width: 100%; height: 100%">
            </iframe>
          </div>
          <div class="flex50 content">
            <div class="mb20">
              <div class="flex justify-between align-center mb20">
                <h2>센서 추가</h2>
                <button class="green-btn small-btn" @click="insertPoint()">
                  추가
                </button>
              </div>
              <table class="form-table">
                <tbody>
                  <tr>
                    <th class="text-lf" style="width: 20%">모델 명</th>
                    <td>
                      <select v-model="projectSelect" id="projectSelect" name="projectSelect" class="full-select"
                        @change="changeProject()">
                        <option value="">모델 명을 선택해 주세요.</option>
                        <option v-for="(project, index) of projects" :value="project.projectId" :key="index">
                          {{ project.projectName }}
                        </option>
                      </select>
                    </td>
                  </tr>
                  <tr>
                    <th class="text-lf" style="width: 20%">컬럼 명</th>
                    <td>
                      <select v-model="sensorSelect" id="sensorSelect" name="sensorSelect" class="full-select">
                        <option value="">컬럼 명을 선택해 주세요.</option>
                        <option v-for="(sensor, index) of notUseSensorList" :value="sensor.sensorId" :key="index">
                          {{ sensor.sensorName }}
                        </option>
                      </select>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
            <div style="height: calc(100% - 111px)">
              <div class="flex justify-between align-center mb20">
                <h2>센서 목록</h2>
                <button class="red-btn small-btn" @click="deletePoint()">
                  삭제
                </button>
              </div>
              <div class="list" style="overflow-y: auto">
                <table class="modal-table">
                  <tbody>
                    <tr v-for="(sensor, index) of useSensorList" :key="index">
                      <td class="pb5 pt5">
                        <div class="flex align-center check-wrap">
                          <input type="checkbox" :id="sensor.pointId" v-model="deletePointIdList" :value="sensor.pointId"
                            class="cyberpunk-checkbox" />
                          <label @clicked="select" @click="readPoint(sensor.pointId)" class="cyberpunk-checkbox-label"
                            :for="sensor.pointId">
                            {{ sensor.sensorName }}({{ sensor.pointId }})
                          </label>
                        </div>
                      </td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="modal-end flex justify-end">
        <button class="darkg-border-btn small-btn" @click="savePoint()">
          저장
        </button>
      </div>
    </div>
  </div>
</template>

<script>
import SvgIcon from "@jamescoyle/vue-icon";
import { mdiCog } from "@mdi/js";
export default {
  props: {
    parent: {
      type: Object,
      required: true,
    },
    optionChangeClick: {
      type: Function,
    },
    componentOptn: {
      type: Object,
      required: true,
    },
  },
  data() {
    return {
      projects: [],
      objects: [],
      points: [],
      sensors: [],
      grassPapers: [],

      nowSensorId: "",
      readPointId: "",
      sensorSelect: "",
      projectSelect: "project1",
      useSensorList: [],
      notUseSensorList: [],
      deletePointIdList: [],

      oldPoints: [],
      oldSensors: [],
      oldProjectSelect: "",
      path: mdiCog
    };
  },
  methods: {
    fetchData: function () {
      let projectData = [
        { projectId: "project1", projectName: "모델1" },
        { projectId: "project2", projectName: "모델2" },
      ];
      this.projects = projectData;

      let objectData = [
        {
          projectId: "project1",
          objectId: "object1",
          objectName: "오브젝트1",
          presetId: "preset5",
          position: { x: 0, y: 0.5, z: 0 },
          rotation: { x: 0, y: 0, z: 0 },
        },
        {
          projectId: "project2",
          objectId: "object2",
          objectName: "오브젝트2",
          presetId: "preset1",
          position: { x: 0, y: 0.5, z: 0 },
          rotation: { x: 0, y: 0, z: 0 },
        },
      ];
      this.objects = objectData;

      let pointData = [];
      this.points = pointData;

      let sensorData = [
        {
          sensorId: "component5",
          sensorName: "tb_datetime",
          sensorUse: false,
        },
        {
          sensorId: "component6",
          sensorName: "pr:32PI1-9009:av",
          sensorUse: false,
        },
        {
          sensorId: "component7",
          sensorName: "pr:LIA-4001:av",
          sensorUse: false,
        },
        { sensorId: "component8", sensorName: "pr:PM2-BWRL", sensorUse: false },
        {
          sensorId: "component9",
          sensorName: "pr:PM2-MSC1",
          sensorUse: false,
        },
        {
          sensorId: "component10",
          sensorName: "pr:PM2-PMRL",
          sensorUse: false,
        },
        {
          sensorId: "component13",
          sensorName: "pr:PM3-S1SC",
          sensorUse: false,
        },
        {
          sensorId: "component14",
          sensorName: "pr:60FIC-6031:me",
          sensorUse: false,
        },
        { sensorId: "component16", sensorName: "22PI-8017", sensorUse: false },
        {
          sensorId: "component17",
          sensorName: "pr:PM3-BWRL",
          sensorUse: false,
        },
        {
          sensorId: "component18",
          sensorName: "pr:PM3-MSC1",
          sensorUse: false,
        },
        { sensorId: "sensor1", sensorName: "pr:PM3-PMRL", sensorUse: false },
        {
          sensorId: "sensor2",
          sensorName: "pr:32PIC-5019:me",
          sensorUse: false,
        },
        {
          sensorId: "sensor3",
          sensorName: "pr:32FIC-7001:me",
          sensorUse: false,
        },
        {
          sensorId: "sensor4",
          sensorName: "pr:60FIC-6023:me",
          sensorUse: false,
        },
        {
          sensorId: "sensor5",
          sensorName: "pr:22LIC-3001:me",
          sensorUse: false,
        },
        {
          sensorId: "sensor6",
          sensorName: "pr:22FI-2101:av",
          sensorUse: false,
        },
        {
          sensorId: "sensor7",
          sensorName: "pr:22FI-2102:av",
          sensorUse: false,
        },
        {
          sensorId: "sensor8",
          sensorName: "pr:22FI-2103:av",
          sensorUse: false,
        },
      ];
      this.sensors = sensorData;
    },
    modalOpen: function () {
      this.isModal = true;
      this.select(null);
      this.readPointId = "";
      this.deletePointIdList = [];
      this.selectNotUseSensorList();
      this.selectUseSensorList();
      // this.loadProject();
      this.changeProject();
      this.oldPoints = this.points;
      this.oldProjectSelect = this.projectSelect;
    },
    modalClose: function () {
      this.isModal = false;
      this.select(null);
      this.readPointId = "";
      this.deletePointIdList = [];
      this.points = this.oldPoints;
      this.projectSelect = this.oldProjectSelect;
      // [DB대체] 작업 내용 초기화
      for (const sensor of this.sensors) {
        sensor["sensorUse"] = false;
      }
      for (const point of this.points) {
        for (const sensor of this.sensors) {
          if (point["sensorId"] == sensor["sensorId"]) {
            sensor["sensorUse"] = true;
          }
        }
      }
      // this.loadProject();
      this.changeProject();
    },

    changeProject() {
      this.selectGetProject(this.projectSelect);
      this.selectUseSensorList();
      this.selectNotUseSensorList();
    },

    // web > unity send message function
    sendMessageToUnity(message) {
      if (this.isModal == true) {
        this.$refs.unity2.contentWindow.postMessage(
          JSON.stringify(message),
          "http://192.168.0.81:8080/"
        );
      } else {
        this.$refs.unity1.contentWindow.postMessage(
          JSON.stringify(message),
          "http://192.168.0.81:8080/"
        );
      }
    },
    // web > unity send message function
    sendMessageToUnity(message) {
      if (this.isModal == true) {
        this.$refs.unity2.contentWindow.postMessage(
          JSON.stringify(message),
          "http://192.168.0.81:8080/"
        );
      } else {
        this.$refs.unity1.contentWindow.postMessage(
          JSON.stringify(message),
          "http://192.168.0.81:8080/"
        );
      }
    },

    // project 불러오기(command: getProject)
    loadProject() {
      const message = {
        command: "getProject",
        projectId: "project1",
        objectList: [
          {
            command: "getObj",
            projectId: "project1",
            objectId: "object1",
            presetId: "preset5",
            position: { x: 0, y: 0.5, z: 0 },
            rotation: { x: 0, y: 0, z: 0 },
            pointList: this.getPointSelectList("object1"),
          },
        ],
      };
      this.sendMessageToUnity(message);
    },
    // [DB대체] objectId로 point list 출력(command: getPoint)
    getPointSelectList(objectId) {
      const pointList = [];
      for (const point of this.points) {
        if (point["objectId"] == objectId) {
          let points = {
            command: "getPoint",
            objectId: objectId,
            pointId: point["pointId"],
            position: {
              x: point["position"]["x"],
              y: point["position"]["y"],
              z: point["position"]["z"],
            },
          };
          pointList.push(points);
        }
      }
      return pointList;
    },
    // [DB대체] 사용중인 sensor list 출력
    selectUseSensorList() {
      let sensorFilter = this.selectSensorList(this.projectSelect);
      const sensorList = [];
      for (const sensor of sensorFilter) {
        if (sensor["sensorUse"] == true) {
          for (const point of this.points) {
            if (point["sensorId"] == sensor["sensorId"]) {
              sensor["pointId"] = point["pointId"];
            }
          }
          sensorList.push(sensor);
        }
      }
      this.useSensorList = sensorList;
    },
    // [DB대체] 사용하지 않는 sensor list 출력
    selectNotUseSensorList() {
      const sensorList = [];
      for (const sensor of this.sensors) {
        if (sensor["sensorUse"] == false) {
          sensorList.push(sensor);
        }
      }
      this.notUseSensorList = sensorList;
    },
    // [DB대체] 사용하지 않는 point id 찾기(가장 낮은 번호)
    selectNotUsePointId() {
      let allPointList = [];
      for (let i = 1; i <= this.sensors.length; i++) {
        allPointList.push("point" + i);
      }
      let usePointList = [];
      for (const point of this.points) {
        usePointList.push(point["pointId"]);
      }
      let filterList = allPointList
        .filter((item) => !usePointList.includes(item))
        .concat(usePointList.filter((item) => !allPointList.includes(item)));
      return filterList[0];
    },

    // [DB대체] pointId로 points 검색(개수 출력)
    countPointId(pointId) {
      let count = 0;
      for (const point of this.points) {
        if (point["pointId"] == pointId) {
          count++;
        }
      }
      return count;
    },
    // [DB대체] pointId로 sensorId 출력
    selectSensorId(pointId) {
      for (const point of this.points) {
        if (point["pointId"] == pointId) {
          return point["sensorId"];
        }
      }
    },
    // [DB대체] sensorId로 pointId 출력
    selectPointId(sensorId) {
      for (const point of this.points) {
        if (point["sensorId"] == sensorId) {
          return point["pointId"];
        }
      }
    },
    // [DB대체] sensorId로 sensorUse 출력
    selectSensorUse(sensorId) {
      for (const sensor of this.sensors) {
        if (sensor["sensorId"] == sensorId) {
          return sensor["sensorUse"];
        }
      }
    },
    // [DB대체] projectId로 getProject 출력
    selectGetProject(projectId) {
      let message = {};
      for (const project of this.projects) {
        if (project["projectId"] == projectId) {
          message = project;
          message["command"] = "getProject";
          message["objectList"] = this.selectObjectList(projectId);
        }
      }
      this.sendMessageToUnity(message);
    },
    // [DB대체] projectId로 getObj 출력
    selectObjectList(projectId) {
      let objectList = [];
      for (const object of this.objects) {
        if (object["projectId"] == projectId) {
          let message = object;
          message["command"] = "getObj";
          message["pointList"] = this.getPointSelectList(object["objectId"]);
          objectList.push(message);
        }
      }
      return objectList;
    },
    // [DB대체] projectId로 sensorList 출력
    selectSensorList(projectId) {
      let objectList = [];
      for (const object of this.objects) {
        if (object["projectId"] == projectId) {
          objectList.push(object);
        }
      }

      let pointList = [];
      for (const point of this.points) {
        for (const object of objectList) {
          if (point["objectId"] == object["objectId"]) {
            pointList.push(point);
          }
        }
      }

      let sensorList = [];
      for (const sensor of this.sensors) {
        for (const point of pointList) {
          if (sensor["sensorId"] == point["sensorId"]) {
            sensorList.push(sensor);
          }
        }
      }

      return sensorList;
    },
    // [DB대체] projectId로 objectId 출력
    selectObjetId(projectId) {
      for (const object of this.objects) {
        if (object["projectId"] == projectId) {
          return object["objectId"];
        }
      }
    },

    // 추가 버튼 클릭 시 실행 함수
    insertPoint() {
      this.nowSensorId = this.sensorSelect;
      if (this.sensorSelect == "") {
        alert("추가할 센서를 선택해 주세요.");
      } else {
        if (this.selectSensorUse(this.sensorSelect) == true) {
          alert("이미 추가된 센서입니다.");
        } else {
          const pointId = this.selectNotUsePointId();
          const message = {
            command: "createPoint",
            objectId: this.selectObjetId(this.projectSelect),
            pointId,
          };
          this.sendMessageToUnity(message);
        }
      }
    },
    // 삭제 버튼 클릭 시 실행 함수
    deletePoint() {
      if (this.deletePointIdList == "") {
        alert("삭제할 포인트를 선택해 주세요.");
      } else {
        for (const point of this.deletePointIdList) {
          const message = {
            command: "deletePoint",
            pointId: point,
          };
          this.sendMessageToUnity(message);
        }
      }
    },
    // 저장 버튼 클릭 시 실행 함수
    savePoint() {
      this.oldPoints = [];
      this.isModal = false;
      // this.loadProject();
      this.select(null);
      this.readPointId = "";
      this.deletePointIdList = [];
      this.changeProject();
    },

    readPoint(pointId) {
      if (this.countPointId(pointId) == 0) {
        pointId = this.selectPointId(pointId);
      }
      const message = {
        command: "readPoint",
        pointId,
      };
      this.sendMessageToUnity(message);
    },

    select(id) {
      this.selected = id;
    },
  },
  watch: {
    points(newValue, oldValue) {
      this.selectNotUseSensorList();
      this.selectUseSensorList();
    },
  },
  computed: {},
  components: {
    'SvgIcon':SvgIcon},
  mounted() {
    this.fetchData();
    // unity > web message
    window.addEventListener("message", (e) => {
      const receiveData = JSON.parse(e.data);
      switch (receiveData["command"]) {
        // unityOn 커맨드
        case "unityOn":
          this.loadProject();
          break;
        // returnData 커맨드
        case "returnData":
          if (receiveData["result"] == true) {
            switch (receiveData["type"]) {
              case "getProject":
                break;
              case "readProject":
              case "readObj":
                this.select(null);
                this.readPointId = "";
                this.deletePointIdList = [];
                break;
              // 포인트 생성
              case "createPoint":
                // [DB대체] point json에 입력 값 저장
                this.points = [
                  ...this.points,
                  {
                    objectId: receiveData["objectId"],
                    pointId: receiveData["pointId"],
                    sensorId: this.nowSensorId,
                    position: {
                      x: receiveData["position"]["x"],
                      y: receiveData["position"]["y"],
                      z: receiveData["position"]["z"],
                    },
                  },
                ];
                // [DB대체] sensor json에 사용 여부 저장
                for (const sensor of this.sensors) {
                  if (sensor["sensorId"] == this.nowSensorId) {
                    sensor["sensorUse"] = true;
                  }
                }
                this.readPointId = receiveData["pointId"];
                this.sensorSelect = "";
                this.deletePointIdList = [];
                break;
              case "readPoint":
                this.select(this.selectSensorId(receiveData["pointId"]));
                this.readPointId = receiveData["pointId"];
                this.deletePointIdList = [
                  ...this.deletePointIdList,
                  receiveData["pointId"],
                ];
                break;
              // 포인트 삭제
              case "deletePoint":
                // [DB대체] sensor json에 사용 여부 저장
                for (const sensor of this.sensors) {
                  if (
                    sensor["sensorId"] ==
                    this.selectSensorId(receiveData["pointId"])
                  ) {
                    sensor["sensorUse"] = false;
                  }
                }
                // [DB대체] point json에 입력 값 삭제
                for (const point of this.points) {
                  if (point["pointId"] == receiveData["pointId"]) {
                    this.points = this.points.filter(function (item) {
                      return item !== point;
                    });
                  }
                }
                this.readPointId = "";
                this.sensorSelect = "";
                this.useSensorList = "";
                this.deletePointIdList = [];

                this.selectNotUseSensorList();
                this.selectUseSensorList();
                break;
              // 미등록 속성
              default:
                alert("등록되지 않은 반환값입니다.");
            }
          } else {
            // return false
            alert("내용 적용을 실패했습니다.");
          }
          break;
        // 미등록 커맨드
        default:
          alert("등록되지 않은 커맨드입니다.");
      }
    });
  },
};
</script>