<template>
  <div class="card">
    <div class="card-body">
      <h2 class="card-title">접근제어관리</h2>
      <div class="flex align-top">
        <div class="sch-form-wrap search">
          <div class="tbl-wrap table-scroll">
            <table id="myTable" class="tbl data">
              <thead>
                <tr>
                  <th>권한목록</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(item, idx) of authorLists" :key="idx" @click="findMenuAuthorList(item.authorCode)">
                  <td v-if="item.useAt === 'Y'" :class="{ 'selected': selectedAuthor == item.authorCode }">{{ item.authorNm }}</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
        <div style="width: 100%;">
          <div class="tbl-wrap chk-area">
            <table id="myTable" class="tbl data">
              <thead>
                <tr>
                  <th>메뉴명</th>
                  <th>전체</th>
                  <th>읽기</th>
                  <th>쓰기</th>
                  <th>수정</th>
                  <th>삭제</th>
                </tr>
              </thead>
              <tbody>
                <template v-if="menuAuthorLists.length > 0">
                  <tr v-for="(item, idx) in menuAuthorLists" :key="idx">
                    <td :style="getMenuStyle(item)"> {{ item.menuNm }} </td>
                    <td>
                      <div class="form-check">
                        <input type="checkbox" :id="`all_${idx}`" :checked="isAllChecked(item)" @change="toggleAll(idx)" />
                        <label :for="`all_${idx}`"></label>
                      </div>
                    </td>
                    <td>
                      <div class="form-check">
                        <input type="checkbox" :id="`redng_${idx}`" :checked="item.redng === 'Y'" @change="updatePermission(idx, 'redng', $event)" />
                        <label :for="`redng_${idx}`"></label>
                      </div>
                    </td>
                    <td>
                      <div class="form-check">
                        <input type="checkbox" :id="`write_${idx}`" :checked="item.write === 'Y'" @change="updatePermission(idx, 'write', $event)" />
                        <label :for="`write_${idx}`"></label>
                      </div>
                    </td>
                    <td>
                      <div class="form-check">
                        <input type="checkbox" :id="`updt_${idx}`" :checked="item.updt === 'Y'" @change="updatePermission(idx, 'updt', $event)" />
                        <label :for="`updt_${idx}`"></label>
                      </div>
                    </td>
                    <td>
                      <div class="form-check">
                        <input type="checkbox" :id="`delete_${idx}`" :checked="item.delete === 'Y'" @change="updatePermission(idx, 'delete', $event)" />
                        <label :for="`delete_${idx}`"></label>
                      </div>
                    </td>
                  </tr>
                </template>
                <template v-else>
                  <tr>
                    <td colspan="6">조회된 정보가 없습니다.</td>
                  </tr>
                </template>
              </tbody>
            </table>
          </div>
          <div>
            <button type="button" class="btn sm secondary" @click="fnUpdate">저장</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
// API
import { findAuthorsProc } from '../../../../resources/api/author'
import { findMenuAuthorsProc, updateMenuAuthorsProc } from '../../../../resources/api/menuAuthor'

export default {
  data() {
    return {
      selectedAuthor: null,
      authorLists: [], // 권한 목록 정보
      menuAuthorLists: [], // 메뉴 권한 목록 정보
    }
  },

  mounted() {
    this.findAuthorList(); // 권한 목록 조회
  },

  methods: {
    // 권한 목록 조회
    async findAuthorList() {
      try {
        const response = await findAuthorsProc();
        const result = response.data.data;

        this.authorLists = result.authors;
      } catch (error) {
        if (error.response) {
          alert(error.response.data.message);
        } else {
          alert("에러가 발생했습니다.");
        }
        console.error(error.message);
      };
    },

    // 메뉴 권한 목록 조회
    async findMenuAuthorList(code) {
      try {
        this.selectedAuthor = code;

        const response = await findMenuAuthorsProc(this.selectedAuthor);
        const result = response.data.data;

        this.menuAuthorLists = result.menuAuthors;
      } catch (error) {
        if (error.response) {
          alert(error.response.data.message);
        } else {
          alert("에러가 발생했습니다.");
        }
        console.error(error.message);
      };
    },

    // 메뉴 스타일 계산 (들여쓰기)
    getMenuStyle(item) {
      const depth = item.dp || 1;
      return {
        paddingLeft: (depth - 1) * 20 + 'px'
      };
    },

    // 개별 권한 업데이트
    updatePermission(index, permission, event) {
      this.menuAuthorLists[index][permission] = event.target.checked ? 'Y' : 'N';
    },

    // 전체 선택/해제
    toggleAll(index) {
      const item = this.menuAuthorLists[index];
      const allChecked = this.isAllChecked(item);
      const newValue = allChecked ? 'N' : 'Y';

      // 모든 권한을 동일하게 설정
      item.redng = newValue;
      item.write = newValue;
      item.updt = newValue;
      item.delete = newValue;
    },

    // 전체 선택 상태 확인 (모든 권한이 'Y'인지 체크)
    isAllChecked(item) {
      return item.redng === 'Y' && item.write === 'Y' && item.updt === 'Y' && item.delete === 'Y';
    },

    // 수정 (모든 메뉴 권한 저장)
    async fnUpdate() {
      try {
        let data = [];
        for (let menuAuthor of this.menuAuthorLists) {
          data.push({
            authorCode: menuAuthor.authorCode,
            menuId: menuAuthor.menuId,
            redng: menuAuthor.redng,
            write: menuAuthor.write,
            updt: menuAuthor.updt,
            delete: menuAuthor.delete,
          });
        }

        const response = await updateMenuAuthorsProc(data);
        const result = response.data.data;

        alert("수정되었습니다.");

        this.findMenuAuthorList(this.selectedAuthor); // 목록 조회
      } catch (error) {
        if (error.response) {
          alert(error.response.data.message);
        } else {
          alert("에러가 발생했습니다.");
        }
        console.error(error.message);
      };
    },
  }
}
</script>
<style scoped>
tr {
  cursor: pointer;
}

.tbl-wrap #myTable .selected {
  color: #FFFFFF;
  background-color: #213F9A;
}

.menu-indent {
  color: #6c757d;
  margin-right: 5px;
}
</style>