<template>
  <div class="content admin-style overflow-y">
    <div class="admin-page-title point-font2 mb30">
      <p>관리자 관리</p>
    </div>
    <details open class="form-table-style mb30">
      <summary class="point-font2">
        <p class="summary-style pl10">기본정보</p>
      </summary>
      <div class="pt10 pb10">
        <table class="form-table">
          <colgroup>
            <col width="50%" />
            <col width="50%" />
          </colgroup>
          <tr>
            <td>
              <div class="gd-12 pl0">
                <label for="" class="form-title point-font2 mb10">아이디</label>
                <input
                  type="text"
                  class="full-input"
                  v-model="mberVO.lgnId"
                  disabled
                />
              </div>
            </td>
            <td>
              <div class="gd-12 pr0">
                <label for="" class="form-title point-font2 mb10">이름</label>
                <input
                  type="text"
                  class="full-input"
                  v-model="mberVO.mbrEncptFlnm"
                  disabled
                />
              </div>
            </td>
          </tr>
          <tr>
            <td>
              <div class="gd-12 pl0">
                <label for="" class="form-title point-font2 mb10">
                  권한
                </label>
                <input
                  type="text"
                  class="full-input"
                  v-model="mberVO.authrtNm"
                  disabled
                />
              </div>
            </td>
            <td>
              <div class="gd-12 pr0">
                <label for="" class="point-font2 mb10"> 소속기관 </label>
                <input
                  type="text"
                  class="full-input"
                  v-model="mberVO.ogdpInstNm"
                  disabled
                />
              </div>
            </td>
          </tr>
          <tr>
            <td colspan="2">
              <div class="gd-12 pl0">
                <label for="" class="form-title point-font2 mb10">이메일</label>
                <div class="flex align-center">
                  <div class="gd-2 pl0">
                    <input
                      type="text"
                      class="full-input"
                      v-model="email.id"
                      disabled
                    />
                  </div>
                  <div>@</div>
                  <div class="gd-2">
                    <select
                      class="full-select"
                      v-model="email.select"
                      disabled
                    >
                      <option value="">선택해주세요</option>
                      <option value="self">직접입력</option>
                      <option value="naver.com">naver.com</option>
                      <option value="google.com">google.com</option>
                      <option value="hanmail.net">hanmail.net</option>
                      <option value="nate.com">nate.com</option>
                      <option value="kakao.com">kakao.com</option>
                    </select>
                  </div>
                  <div class="gd-2">
                    <input
                      type="text"
                      class="full-input"
                      v-model="email.address"
                      v-show="email.select == 'self'"
                      disabled
                    />
                  </div>
                </div>
              </div>
            </td>
          </tr>
        </table>
      </div>
    </details>

    <div class="flex justify-end align-center no-gutters">
      <div class="gd-1 mr10">
        <button class="large-btn darkg-border-btn" @click="fnList">목록</button>
      </div>
      <div class="gd-1 mr10">
        <button
          class="large-btn blue-border-btn"
          @click="fnUpdate()"
          v-if="pageAuth.mdfcnAuthrtYn == 'Y'"
        >
          정보수정
        </button>
      </div>
      <div class="gd-1 mr10">
        <button
          class="large-btn red-border-btn"
          @click="fnDelete()"
          v-if="pageAuth.delAuthrtYn == 'Y'"
        >
          삭제
        </button>
      </div>
      <div class="gd-1 mr10">
        <button
          class="large-btn green-border-btn"
          @click="isPwModalOpen = true"
          v-if="pageAuth.mdfcnAuthrtYn == 'Y'"
        >
          비밀번호 변경
        </button>
      </div>
      <div class="gd-1">
        <button
          class="large-btn orange-border-btn"
          @click="otpReset()"
          v-if="pageAuth.mdfcnAuthrtYn == 'Y'"
        >
          OTP초기화
        </button>
      </div>
    </div>
  </div>

  <!-- 모달: 비밀번호 변경 -->
  <Modal :showModal="isPwModalOpen" :className="'medium-modal auto-height'" >
      <template v-slot:header>
        <p class="page-sub-title">비밀번호 변경하기</p>
        <button class="close-btn" @click="fnModalClose">
          <svg-icon type="mdi" :path="closePath"></svg-icon>
        </button>
      </template>
      <div class="table-zone">
        <table>
            <colgroup>
                <col width="35%" />
                <col width="65%" />
            </colgroup>
            <tbody>
              <tr>
                <th class="text-rg pd10">변경할 비밀번호</th>
                <td class="text-lf">
                        <input type="password" ref="newPswd"  class="full-input" placeholder="영문, 숫자, 특수문자 조합된 6~20자리" id="newPw"
                        v-model="pswd.newPswd" autocomplete="off" minlength="6"
                maxlength="20" />
                </td>
              </tr>
              <tr>
                  <th class="text-rg pd10">변경할 비밀번호 확인</th>
                  <td class="text-lf">
                          <input type="password" ref="newPswdChk"  class="full-input" 
                                 id="newPw_check" v-model="pswd.newPswdChk" autocomplete="off" minlength="6" maxlength="20"  placeholder="비밀번호 확인을 입력하세요." @keyup.enter="fnUpdatePswd()" />
                          <div>
                              <p v-if="(pswd.newPswd === pswd.newPswdChk) && pswd.newPswdChk">비밀번호 일치합니다.</p>
                              <p v-if="(pswd.newPswd !== pswd.newPswdChk) && pswd.newPswdChk">비밀번호가 일치하지 않습니다.</p>
                          </div>
                  </td>
              </tr>
            </tbody>
        </table>
      </div>
      <template v-slot:footer>
        <div class="gd-2 pr0">
          <button class="large-btn red-border-btn" @click="fnModalClose">
            취소
          </button>
        </div>
        <div class="gd-2 pr0">
          <button class="large-btn blue-border-btn" @click="fnUpdatePswd()" v-if="pageAuth.mdfcnAuthrtYn == 'Y'">
            변경
          </button>
        </div>
      </template>
    </Modal>
</template>

<script>
// api
import { findByMbr, deleteAdmProc, updatePswdProc, otpResetProc } from "../../../../../resources/api/mbrInfo";
import Modal from "../../../../component/modal/Modal.vue";
import { mdiWindowClose } from "@mdi/js";
export default {
  data() {
    return {
      closePath:mdiWindowClose,
      // 페이지 권한 객체
      pageAuth: JSON.parse(localStorage.getItem("vuex")).pageAuth,

      // id
      pageId: this.$route.query.pageId,

      // 상세조회 정보 담는 객체
      mberVO: {},
      email: {
        id: null,
        select: "",
        address: null,
      },
      
      //비밀번호 정보 객체
      pswd: {
        newPswd: null,
        newPswdChk: null,
      },

      //비밀번호 변경 모달
      isPwModalOpen: false,
      //비밀번호 유효성검사 에러표시
      errorPwd: false
    };
  },
  created() {
    // 조회(상세)
    this.fnViewDetail();
  },
  methods: {
    // 목록
    fnList() {
      this.$router.push({
        name: "admAdminManagementSelectList",
      });
    },
    // 조회(상세)
    fnViewDetail() {
      this.axiosViewDetail();
    },
    // 수정
    fnUpdate() {
      this.$router.push({
        name: "admAdminManagementInsert",
        query: { pageId: this.pageId },
      });
    },
    // 삭제
    fnDelete() {
      if (confirm(this.$getCmmnMessage("cnf002"))) {
        this.axiosDelete();
      } else {
        return;
      }
    },

    // 비밀번호 변경
    fnUpdatePswd() {
      if (this.$isEmpty(this.pswd.newPswd)) {
          alert("변경할 비밀번호를 입력해주세요.")
          return;
      } else if (this.$isEmpty(this.pswd.newPswdChk)) {
          alert("비밀번호 확인을 입력해주세요.")
          return;
      } else if (this.pswd.newPswd !== this.pswd.newPswdChk) {
          alert("비밀번호가 불일치합니다.");
          return;
      } else if (!this.$pwCheck(this.pswd.newPswd)) {
          alert('비밀번호는 영문, 숫자, 특수문자를 포함한 6~20자이어야 합니다.')
          return;
      }

      var isUpdate = confirm(this.$getCmmnMessage("cnf004", "해당 관리자의 비밀번호를 "));

      if (isUpdate) {
        this.axiosUpdatePswd();
      } else {
        return;
      }
    },

    // 이메일 분리
    emailSplit(data) {
      const email = data.mbrEncptEmad.split("@");
      this.email.id = email[0];
      switch (email[1]) {
        case "naver.com":
        case "google.com":
        case "hanmail.net":
        case "nate.com":
        case "kakao.com":
          this.email.select = email[1];
          break;
        default:
          this.email.select = "self";
          this.email.address = email[1];
          break;
      }
    },

    // axios: 조회(상세)
    async axiosViewDetail() {
      // 데이터 세팅
      const data = { mbrId: this.pageId };
      // 실행
      try {
        const response = await findByMbr(data);

        // axios 결과
        // alert(response.data.message);

        // 객체 삽입
        this.mberVO = response.data.data;
        this.emailSplit(response.data.data);
      } catch (error) {
        const errorData = error.response.data;
        if (errorData.message != null && errorData.message != "") {
          alert(error.response.data.message);
        } else {
          // alert("에러가 발생했습니다.\n관리자에게 문의해주세요.");
          alert(this.$getCmmnMessage('err005'));
        }
      }
    },
    // axios: 삭제
    async axiosDelete() {
      // 데이터 세팅
      let data = { 'mbrId' : this.mberVO.mbrId 
                  ,'authrtNm' : this.mberVO.authrtNm};
      // 실행
      this.$store.commit('setLoading', true);
      try {
        const response = await deleteAdmProc(data);

        // axios 결과
        alert(this.$getCmmnMessage("msg003"));

        // 목록
        this.fnList();
      } catch (error) {
        const errorData = error.response.data;
        if (errorData.message != null && errorData.message != "") {
          alert(error.response.data.message);
        } else {
          // alert("에러가 발생했습니다.\n관리자에게 문의해주세요.");
          alert(this.$getCmmnMessage('err005'));
        }
      } finally {
        this.$store.commit('setLoading', false);
      }
    },

    // 비밀번호 변경
    async axiosUpdatePswd() {

      // 데이터 세팅
      let data = {
        mbrId : this.mberVO.mbrId ,
        newMbrEncptPswd : this.pswd.newPswd
      }

      this.$store.commit('setLoading', true);
      try {
        const response = await updatePswdProc(data);

        // axios 결과
        alert(this.$getCmmnMessage("msg004", "비밀번호 수정이 "));

        // 모달닫기
        this.isPwModalOpen = false;
        //비밀번호input 비우기
        this.pswd.newPswd = null;
        this.pswd.newPswdChk = null;
      } catch (error) {
        const errorData = error.response.data;
        if (errorData.message != null && errorData.message != "") {
          alert(error.response.data.message);
        } else {
          // alert("에러가 발생했습니다.\n관리자에게 문의해주세요.");
          alert(this.$getCmmnMessage('err005'));
        }
      } finally {
        this.$store.commit('setLoading', false);
      }
    },

    // 비밀번호 검증
    pswdCheck() {
      if (this.pswd.newPswd != null && this.pswd.newPswd != "") {
        
        if (
          !this.$pwCheck(this.pswd.newPswd) ||
          !this.pswd.newPswd ||
          this.pswd.newPswd.length < 6 ||
          this.pswd.newPswd.length > 20
        ) {
          this.errorPwd = true;
        } else if (this.pswd.newPswd != null && this.pswd.newPswd != "") {
          this.errorPwd = false;
        }
      } else {
        this.errorPwd = null;
      }
    },

    //OTP 초기화
    async otpReset() {
      // 데이터 세팅
      let data = {
        mbrId : this.mberVO.mbrId,
      }

      this.$store.commit('setLoading', true);
      try {
        const response = await otpResetProc(data);

        // axios 결과
        alert(this.$getCmmnMessage("msg004", "OTP초기화가 "));

        // 모달닫기
        this.isPwModalOpen = false;
        //비밀번호input 비우기
        this.pswd.newPswd = null;
        this.pswd.newPswdChk = null;
        this.errorPwd = true;
      } catch (error) {
        const errorData = error.response.data;
        if (errorData.message != null && errorData.message != "") {
          alert(error.response.data.message);
        } else {
          // alert("에러가 발생했습니다.\n관리자에게 문의해주세요.");
          alert(this.$getCmmnMessage('err005'));
        }
      } finally {
        this.$store.commit('setLoading', false);
      }
    },

    // 모달 닫기
    fnModalClose() {
      this.isPwModalOpen = false;
      this.pswd = {
        newPswd: null,
        newPswdChk: null
      };
    },
  },
  watch: {
    "pswd.newPswd"() {
      this.pswdCheck();
    },
  },
  computed: {},
  components: {
    Modal: Modal,
  },
  mounted() {},
};
</script>
