<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="#9970ff"
              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">
                    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">
                    <v-img
                      max-width="100"
                      max-height="100"
                      :src="item.profileUrl"
                      class="rounded-circle"
                    />
                  </td>
                  <td>{{ item.userType }}</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="USER"
                    label="일반회원"
                  />
                  <v-spacer />
                </v-radio-group>
              </v-col>
            </v-row>
          </v-card-text>
          <v-card-actions v-show="!is_loading">
            <v-spacer />
            <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>
  </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
    }
  },

  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'
      }

      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
    },

    async modify() {
      this.is_loading = true

      if (
        (this.user_type === 'CREATOR' && this.member.userType === '크리에이터') ||
        (this.user_type === 'USER' && 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()
    }
  }
}
</script>

<style scoped>

</style>
