<template>
  <div class="container">
    <div class="page-titleZone flex justify-between align-center align-center">
      <p class="main-title flex80">알림관리</p>
      <PageNavigation />
    </div>
    <div class="content-wrap">
      <div class="content-box flex justify-between">
        <div class="left-content flex20 phone-mockup">
          <div class="speaker">
            <span></span>
            <span></span>
          </div>
          <div class="text-areaZone">
            <textarea
              name=""
              id=""
              cols="30"
              rows="10"
              v-model="text"
              class="push-text"
            ></textarea>
          </div>
          <div class="user-list">
            <p class="user-title">
              <svg-icon
                type="mdi"
                :width="15"
                :height="15"
                :path="path"
              ></svg-icon>
              최근 수신자 명단
            </p>
            <ul>
              <li v-for="(item, idx) in resultList" :key="idx">
                {{ item["userNm"] }}
              </li>
            </ul>
          </div>
        </div>
        <div class="right-content flex80">
          <ul class="tab-nav flex justify-between">
            <li @click="showTab('tab1')" class="flex50">
              <a href="#tab01" :class="{ activeTab: activeTab === 'tab1' }"
                >사용자</a
              >
            </li>
            <li @click="showTab('tab2')" class="flex50">
              <a href="#tab02" :class="{ activeTab: activeTab === 'tab2' }"
                >Log</a
              >
            </li>
          </ul>
          <ul class="tab-content">
            <li v-show="activeTab === 'tab1'" class="content-box">
              <div class="user-zone">
                <div class="flex justify-end">
                  <div class="search-bar">
                    <div class="flex justify-end align-center">
                      <select name="" id="" class="square-select">
                        <option value="all">전체</option>
                      </select>
                      <div class="search-square">
                        <input
                          type="text"
                          class="square-input"
                          placeholder="Search"
                        />
                        <button class="square-button">
                          <svg-icon
                            type="mdi"
                            :path="searchPath"
                            class="square-icon"
                          ></svg-icon>
                        </button>
                      </div>
                    </div>
                  </div>
                </div>
                <div class="table-zone">
                  <div class="list-info flex justify-between align-center">
                    <div class="count-zone">
                      <p>
                        총 <span>{{ allowUserList.length }}</span
                        >건 중 <span>0</span>건 선택
                      </p>
                    </div>
                    <div class="cunt-selectZone">
                      <select name="" id="">
                        <option value="">10개 보기</option>
                        <option value="">20개 보기</option>
                      </select>
                    </div>
                  </div>
                  <table class="list-table">
                    <colgroup>
                      <col style="width: 10%" />
                      <col style="width: 10%" />
                      <col style="width: 20%" />
                      <col style="width: 20%" />
                      <col style="width: 20%" />
                      <!-- <col style="width:20%" /> -->
                    </colgroup>
                    <thead>
                      <tr>
                        <th><input type="checkbox" name="" id="" /></th>
                        <th>No</th>
                        <th>이름</th>
                        <th>아이디</th>
                        <th>부서</th>
                        <!-- <th>직급</th> -->
                      </tr>
                    </thead>
                    <tbody>
                      <tr v-for="(item, idx) in allowUserList" :key="idx">
                        <td><input type="checkbox" name="" id="" /></td>
                        <td>{{ idx + 1 }}</td>
                        <td>{{ item["userNm"] }}</td>
                        <td>{{ item["userId"] }}</td>
                        <td>{{ item["deptNm"] }}</td>
                      </tr>
                    </tbody>
                  </table>
                </div>
                <div class="flex justify-end align-center">
                  <button class="red-border-btn small-btn">멤버 삭제</button>
                  <button class="blue-border-btn small-btn" @click="openModal">
                    멤버 추가
                  </button>
                </div>
                <PaginationButton
                  v-model:currentPage="search.currentPage"
                  :perPage="search.perPage"
                  :totalCount="search.totalRows"
                  :maxRange="5"
                />
              </div>
            </li>
            <li v-show="activeTab === 'tab2'" class="content-box">
              <div class="log-zone">
                <ul class="log-content">
                  <li v-for="(item, idx) in resultList" :key="idx">
                    <div class="flex justify-between align-center">
                      <p>{{ item["message"] }}</p>
                      <p>{{ item["sendTime"] }}</p>
                    </div>
                  </li>
                </ul>
              </div>
            </li>
          </ul>
        </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">X</button>
        </div>
      </div>
      <div class="modal-content-monthly">
        <div class="flex justify-end">
          <div class="search-bar">
            <div class="flex justify-end align-center">
              <select name="" id="" class="square-select">
                <option value="all">전체</option>
              </select>
              <div class="search-square">
                <input type="text" class="square-input" placeholder="Search" />
                <button class="square-button">
                  <svg-icon
                    type="mdi"
                    :path="searchPath"
                    class="square-icon"
                  ></svg-icon>
                </button>
              </div>
            </div>
          </div>
        </div>
        <div class="table-zone">
          <table class="list-table">
            <colgroup>
              <col style="width: 10%" />
              <col style="width: 10%" />
              <col style="width: 20%" />
              <col style="width: 20%" />
              <col style="width: 20%" />
            </colgroup>
            <thead>
              <tr>
                <th>
                  <input
                    type="checkbox"
                    name="allSelect"
                    id="allSelect"
                    v-model="allSelected"
                    @change="selectAll"
                  />
                </th>
                <th>No</th>
                <th>이름</th>
                <th>아이디</th>
                <th>부서</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(item, idx) in denyUserList" :key="idx">
                <td>
                  <input
                    type="checkbox"
                    name=""
                    id=""
                    v-model="item.selected"
                    @change="handlerSelectMember(item['userId'])"
                  />
                </td>
                <td>{{ idx + 1 }}</td>
                <td>{{ item["userNm"] }}</td>
                <td>{{ item["userId"] }}</td>
                <td>{{ item["deptNm"] }}</td>
              </tr>
            </tbody>
          </table>
        </div>
        <PaginationButton
          v-model:currentPage="search.currentPage"
          :perPage="search.perPage"
          :totalCount="search.totalRows"
          :maxRange="5"
        />
      </div>
      <div class="modal-end flex justify-end">
        <button class="orange-btn small-btn" @click="closeModal">취소</button>
        <button class="blue-btn small-btn" @click="addMemberFunc">
          멤버추가
        </button>
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import PageNavigation from "../../component/PageNavigation.vue";
import PaginationButton from "../../component/PaginationButton.vue";
import SvgIcon from "@jamescoyle/vue-icon";
import { mdiPhoneIncoming, mdiMagnify } from "@mdi/js";

export default {
  data() {
    return {
      path: mdiPhoneIncoming,
      activeTab: "tab1",
      isModalOpen: false,
      searchPath: mdiMagnify,
      text: "compressor('sensor1')의 범위값의 변동이 있습니다. 확인하여 주십시오.",

      search: this.$getDefaultSerchVO(),

      // 웹 푸시 허용 사용자 목록
      allowUserList: [],

      // 웹 푸시 미허용 사용자 목록
      denyUserList: [],

      // 웹 푸시 토큰 목록
      tokenList: [],

      // 웹 푸시 결과 목록
      resultList: [],

      // 선택 리스트
      allSelected: false,
      selectUserList: [],
    };
  },
  methods: {
    showTab: function (tabName) {
      this.activeTab = tabName;
    },
    openModal: function () {
      this.isModalOpen = true;
    },
    closeModal: function () {
      this.isModalOpen = false;
    },

    // 웹 푸시 허용 사용자 목록 조회
    async selectAllowPushUserList() {
      const vm = this;
      axios({
        url: "/push/selectPushUserList",
        method: "post",
        headers: {
          "Content-Type": "application/json; charset=UTF-8",
        },
        data: {
          using: "Y",
        },
      })
        .then(function (response) {
          vm.allowUserList = response.data.resultData["pushUserList"];
        })
        .catch(function (error) {
          alert("허용 사용자 목록 조회에 오류가 발생했습니다.");
        });
    },

    // 웹 푸시 미허용 사용자 목록 조회
    async selectDenyPushUserList() {
      const vm = this;
      axios({
        url: "/push/selectPushUserList",
        method: "post",
        headers: {
          "Content-Type": "application/json; charset=UTF-8",
        },
        data: {
          using: "N",
        },
      })
        .then(function (response) {
          vm.denyUserList = response.data.resultData["pushUserList"];
        })
        .catch(function (error) {
          alert("미허용 사용자 목록 조회에 오류가 발생했습니다.");
        });
    },

    // 웹 푸시 결과 목록 조회
    async selectPushResultList() {
      const vm = this;
      axios({
        url: "/push/selectPushResultList",
        method: "get",
        headers: {
          "Content-Type": "application/json; charset=UTF-8",
        },
        data: {},
      })
        .then(function (response) {
          vm.resultList = response.data.resultData["pushResultList"];
        })
        .catch(function (error) {
          alert("웹 푸시 결과 목록 조회에 오류가 발생했습니다.");
        });
    },

    // 웹 푸시 토큰 목록 조회
    async selectPushTokenList() {
      const vm = this;
      axios({
        url: "/push/selectPushTokenList",
        method: "post",
        headers: {
          "Content-Type": "application/json; charset=UTF-8",
        },
        data: {
          using: "Y",
        },
      })
        .then(function (response) {
          vm.tokenList = response.data.resultData["pushTokenList"];
        })
        .catch(function (error) {
          alert("토큰 목록 조회에 오류가 발생했습니다.");
        });
    },
    // 전체 선택 기능 구현
    selectAll() {
      // 전체 선택 기능 구현
      if (this.allSelected) {
        this.denyUserList.forEach((user) => {
          user.selected = this.allSelected;
          this.selectUserList.push(user.userId);
        });
      } else {
        this.denyUserList.forEach((user) => (user.selected = false));
        this.selectUserList = [];
      }
    },
    // 개별 선택 기능 구현
    handlerSelectMember(userId) {
      // 선택한 사용자의 id가 selectUserList 배열에 존재하는지 확인
      const isUserCheck = this.selectUserList.includes(userId);
      if (isUserCheck) {
        // 존재한다면 해당 사용자의 id를 배열에서 제거하고 isPush 속성을 false로 변경
        this.selectUserList = this.selectUserList.filter(
          (user) => user !== userId
        );
        const user = this.denyUserList.find((user) => user.id === userId);
        if (user) {
          user.isPush = false;
        }
      } else {
        // 존재하지 않는다면 해당 사용자의 id를 배열에 추가하고 isPush 속성을 true로 변경
        this.selectUserList.push(userId);
        const user = this.denyUserList.find((user) => user.id === userId);
        if (user) {
          user.isPush = true;
        }
      }
    },
    // 멤버 추가 버튼 클릭 시 api 호출
    addMemberFunc() {
      const vm = this;
      axios({
        url: "/push/user",
        method: "post",
        headers: {
          "Content-Type": "application/json; charset=UTF-8",
        },
        data: vm.selectUserList,
      })
        .then(function (response) {
          vm.selectAllowPushUserList();
          vm.selectDenyPushUserList();
          alert("멤버를 추가하였습니다.");
        })
        .catch(function (error) {
          alert("멤버를 추가할 수 없습니다.");
        });
    },
  },
  components: {
    SvgIcon: SvgIcon,
    PageNavigation: PageNavigation,
    PaginationButton: PaginationButton,
  },
  mounted() {
    this.selectAllowPushUserList();
    this.selectDenyPushUserList();
    this.selectPushTokenList();
    this.selectPushResultList();
  },
};
</script>
