<template>
  <div>
    <v-toolbar dark>
      <v-spacer />
      <v-toolbar-title>회원리스트</v-toolbar-title>
      <v-spacer />
    </v-toolbar>

    <br>

    <v-container>
      <v-row>
        <v-col cols="8" />
        <v-col>
          <v-text-field
            v-model="search_word"
            label="이메일 혹은 닉네임을 입력하세요"
            @keyup.enter="search"
          >
            <v-btn
              slot="append"
              color="#3bb9f1"
              dark
              @click="search"
            >
              검색
            </v-btn>
          </v-text-field>
        </v-col>
      </v-row>
      <v-row>
        <v-col>
          <v-simple-table class="elevation-10">
            <template>
              <thead>
                <tr>
                  <th class="text-center">
                    회원번호
                  </th>
                  <th class="text-center">
                    이메일
                  </th>
                  <th class="text-center">
                    닉네임
                  </th>
                  <th class="text-center">
                    이미지
                  </th>
                  <th class="text-center">
                    회원타입
                  </th>
                  <th class="text-center">
                    로그인 타입
                  </th>
                  <th class="text-center">
                    OS
                  </th>
                  <th class="text-center">
                    성인인증
                  </th>
                  <th class="text-center">
                    가입일
                  </th>
                  <th class="text-center">
                    이용중지/탈퇴일
                  </th>
                  <th class="text-center">
                    관리
                  </th>
                </tr>
              </thead>
              <tbody>
                <tr
                  v-for="item in memberList"
                  :key="item.id"
                >
                  <td>{{ item.id }}</td>
                  <td>{{ item.email }}</td>
                  <td>{{ item.nickname }}</td>
                  <td align="center">
                    <div>
                      <v-img
                        max-width="100"
                        max-height="100"
                        :src="item.profileUrl"
                        class="rounded-circle"
                      />
                      <br>
                      <a
                        :href="item.profileUrl"
                        class="v-btn v-btn--outlined"
                      >
                        Download Image
                      </a>
                    </div>
                  </td>
                  <td>{{ item.userType }}</td>
                  <td>{{ item.loginType }}</td>
                  <td>
                    <div v-if="item.container === 'aos'">
                      Android
                    </div>
                    <div v-else>
                      iOS
                    </div>
                  </td>
                  <td>
                    <div v-if="item.auth">
                      O
                    </div>
                    <div v-else>
                      X
                    </div>
                  </td>
                  <td>{{ item.signUpDate }}</td>
                  <td>{{ item.signOutDate }}</td>
                  <td>
                    <v-btn
                      dark
                      @click="showPopupDialog(item)"
                    >
                      수정
                    </v-btn>
                  </td>
                </tr>
              </tbody>
            </template>
          </v-simple-table>
        </v-col>
      </v-row>
      <v-row class="text-center">
        <v-col>
          <v-pagination
            v-model="page"
            :length="total_page"
            circle
            @input="next"
          />
        </v-col>
      </v-row>
    </v-container>

    <v-row>
      <v-dialog
        v-model="show_popup_dialog"
        max-width="1000px"
        persistent
      >
        <v-card>
          <v-card-title>계정 상세</v-card-title>
          <v-card-text>
            <v-row align="center">
              <v-col cols="4">
                이메일 :
              </v-col>
              <v-col cols="8">
                {{ email }}
              </v-col>
            </v-row>
          </v-card-text>
          <v-card-text>
            <v-row align="center">
              <v-col cols="4">
                닉네임 :
              </v-col>
              <v-col cols="8">
                {{ nickname }}
              </v-col>
            </v-row>
          </v-card-text>
          <v-card-text>
            <v-row align="center">
              <v-col cols="4">
                권한
              </v-col>
              <v-col cols="8">
                <v-radio-group
                  v-model="user_type"
                  row
                >
                  <v-spacer />
                  <v-radio
                    value="CREATOR"
                    label="크리에이터"
                  />
                  <v-radio
                    value="AGENT"
                    label="에이전트"
                  />
                  <v-radio
                    value="USER"
                    label="일반회원"
                  />
                  <v-radio
                    value="CONTENT_MANAGER"
                    label="콘텐츠 관리자"
                  />
                  <v-spacer />
                </v-radio-group>
              </v-col>
            </v-row>
          </v-card-text>
          <v-card-actions v-show="!is_loading">
            <v-btn
              color="error"
              text
              @click="showBlockReasonDialog"
            >
              차단
            </v-btn>
            <v-spacer />
            <v-btn
              color="blue darken-1"
              text
              @click="confirmResetPassword"
            >
              비밀번호 재설정
            </v-btn>
            <v-btn
              color="blue darken-1"
              text
              @click="cancel"
            >
              취소
            </v-btn>
            <v-btn
              color="blue darken-1"
              text
              @click="modify"
            >
              수정
            </v-btn>
          </v-card-actions>
        </v-card>
      </v-dialog>
    </v-row>

    <v-row>
      <v-dialog
        v-model="show_confirm_reset_password_dialog"
        max-width="400px"
        persistent
      >
        <v-card>
          <v-card-title>
            {{ nickname }}님의 비밀번호를 재설정 하시겠습니까?
          </v-card-title>
          <v-card-actions v-show="!is_loading">
            <v-spacer />
            <v-btn
              color="blue darken-1"
              text
              @click="resetPassword"
            >
              비밀번호 재설정
            </v-btn>
            <v-spacer />
            <v-btn
              color="blue darken-1"
              text
              @click="cancel"
            >
              취소
            </v-btn>
            <v-spacer />
          </v-card-actions>
        </v-card>
      </v-dialog>
    </v-row>

    <v-row>
      <v-dialog
        v-model="show_block_reason_dialog"
        max-width="500px"
        persistent
      >
        <v-card>
          <v-card-title>차단(탈퇴) 사유 입력</v-card-title>
          <v-card-text>
            <v-textarea
              v-model="block_reason"
              label="사유를 입력해주세요"
              outlined
              hide-details
            />
          </v-card-text>
          <v-card-actions v-show="!is_loading">
            <v-spacer />
            <v-btn
              color="error"
              text
              @click="confirmBlock"
            >
              차단
            </v-btn>
            <v-btn
              color="blue darken-1"
              text
              @click="cancelBlock"
            >
              취소
            </v-btn>
          </v-card-actions>
        </v-card>
      </v-dialog>
    </v-row>

    <v-row>
      <v-dialog
        v-model="show_confirm_block_dialog"
        max-width="500px"
        persistent
      >
        <v-card>
          <v-card-title class="text-h6">
            '{{ nickname }}' 계정과 본인인증 정보, 같은 본인인증 정보를 사용하는 모든 계정을 차단합니다.
          </v-card-title>
          <v-card-actions v-show="!is_loading">
            <v-spacer />
            <v-btn
              color="error"
              text
              @click="blockMember"
            >
              차단
            </v-btn>
            <v-btn
              color="blue darken-1"
              text
              @click="cancelBlock"
            >
              취소
            </v-btn>
          </v-card-actions>
        </v-card>
      </v-dialog>
    </v-row>
  </div>
</template>

<script>
import * as api from '@/api/member'

export default {
  name: "MemberList",

  data() {
    return {
      is_loading: false,
      page: 1,
      total_page: 0,
      search_word: '',
      memberList: [],
      member: null,
      email: null,
      nickname: null,
      user_type: null,
      show_popup_dialog: false,
      show_confirm_reset_password_dialog: false,
      show_block_reason_dialog: false,
      show_confirm_block_dialog: false,
      block_reason: '',
    }
  },

  async created() {
    await this.getMemberList()
  },

  methods: {
    notifyError(message) {
      this.$dialog.notify.error(message)
    },

    notifySuccess(message) {
      this.$dialog.notify.success(message)
    },

    async search() {
      this.page = 1
      await this.searchMember()
    },

    async searchMember() {
      if (this.search_word.length === 0) {
        await this.getMemberList()
      } else if (this.search_word.length < 2) {
        this.notifyError('검색어를 2글자 이상 입력하세요.')
      } else {
        this.is_loading = true
        try {
          const res = await api.searchMember(this.search_word, this.page)
          if (res.status === 200 && res.data.success === true) {
            const data = res.data.data

            const total_page = Math.ceil(data.totalCount / 20)
            this.memberList = data.items

            if (total_page <= 0)
              this.total_page = 1
            else
              this.total_page = total_page
          } else {
            this.notifyError(res.data.message || '알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.')
          }

          this.is_loading = false
        } catch (e) {
          this.notifyError('알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.')
          this.is_loading = false
        }
      }
    },

    async next() {
      if (this.search_word.length < 2) {
        this.search_word = ''
        await this.getMemberList()
      } else {
        await this.searchMember()
      }
    },

    async getMemberList() {
      this.is_loading = true
      try {
        const res = await api.getMemberList(this.page)
        if (res.status === 200 && res.data.success === true) {
          const data = res.data.data

          const total_page = Math.ceil(data.totalCount / 20)
          this.memberList = data.items

          if (total_page <= 0)
            this.total_page = 1
          else
            this.total_page = total_page
        } else {
          this.notifyError(res.data.message || '알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.')
        }

        this.is_loading = false
      } catch (e) {
        this.notifyError('알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.')
        this.is_loading = false
      }
    },

    showPopupDialog(member) {
      this.member = member

      if (member.userType === '일반회원') {
        this.user_type = 'USER'
      } else if (member.userType === '크리에이터') {
        this.user_type = 'CREATOR'
      } else if (member.userType === '에이전트') {
        this.user_type = 'AGENT'
      } else if (member.userType === '콘텐츠 관리자') {
        this.user_type = 'CONTENT_MANAGER'
      }

      this.email = member.email
      this.nickname = member.nickname

      this.show_popup_dialog = true
    },

    cancel() {
      this.member = null
      this.email = null
      this.nickname = null
      this.user_type = null
      this.show_popup_dialog = false
      this.show_confirm_reset_password_dialog = false
      this.show_block_reason_dialog = false
      this.show_confirm_block_dialog = false
      this.block_reason = ''
    },

    showBlockReasonDialog() {
      this.show_popup_dialog = false
      this.show_block_reason_dialog = true
    },

    cancelBlock() {
      this.show_block_reason_dialog = false
      this.show_confirm_block_dialog = false
      this.block_reason = ''
      this.show_popup_dialog = true
    },

    confirmBlock() {
      if (this.block_reason.length === 0) {
        this.notifyError('차단 사유를 입력해주세요.')
        return
      }
      this.show_block_reason_dialog = false
      this.show_confirm_block_dialog = true
    },

    async blockMember() {
      this.is_loading = true
      try {
        const res = await api.blockMember(this.member.id, this.block_reason)
        if (res.status === 200 && res.data.success === true) {
          this.notifySuccess('차단되었습니다.')
          this.cancel()

          this.page = 1
          await this.getMemberList()
        } else {
          this.notifyError(res.data.message || '알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.')
        }

        this.is_loading = false
      } catch (e) {
        this.notifyError('알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.')
        this.is_loading = false
      }
    },

    async modify() {
      this.is_loading = true

      if (
        (this.user_type === 'CREATOR' && this.member.userType === '크리에이터') ||
        (this.user_type === 'USER' && this.member.userType === '일반회원') ||
        (this.user_type === 'AGENT' && this.member.userType === '에이전트') ||
        (this.user_type === 'CONTENT_MANAGER' && this.member.userType === '콘텐츠 관리자')
      ) {
        this.notifyError("변경사항이 없습니다.")
      } else {
        try {
          const res = await api.updateMember(this.member.id, this.user_type)
          if (res.status === 200 && res.data.success === true) {
            this.page = 1
            this.total_page = 0
            this.search_word = ''

            this.memberList = []
            await this.getMemberList()
          } else {
            this.notifyError(res.data.message || '알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.')
          }
        } catch (e) {
          this.notifyError("알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.")
        }
      }

      this.is_loading = false
      this.cancel()
    },

    confirmResetPassword() {
      this.show_popup_dialog = false
      this.show_confirm_reset_password_dialog = true
    },

    async resetPassword() {
      this.is_loading = true
      try {
        const res = await api.resetPassword(this.member.id)
        if (res.status === 200 && res.data.success === true) {
          this.notifySuccess(res.data.message)
          this.cancel()

          this.page = 1
          await this.getMemberList()
        } else {
          this.notifyError(res.data.message || '알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.')
        }

        this.is_loading = false
      } catch (e) {
        this.notifyError('알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.')
        this.is_loading = false
      }
    }
  }
}
</script>

<style scoped>
</style>
