<template>
  <div>
    <v-toolbar dark>
      <v-spacer />
      <v-toolbar-title>크리에이터 리스트</v-toolbar-title>
      <v-spacer />
    </v-toolbar>

    <br>

    <v-container>
      <v-row>
        <v-col>
          <v-text-field
            v-model="utm_source"
            label="예) youtube, google"
          />
        </v-col>
        <v-col>
          <v-text-field
            v-model="utm_medium"
            label="예) email, cpc"
          />
        </v-col>
        <v-col>
          <v-text-field
            v-model="utm_campaign"
            label="예) 화이트데이"
          />
        </v-col>
        <v-col cols="2" />
        <v-col cols="4">
          <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 class="text-left total-creator">
          전체 <span>{{ total_creator_count }}</span> 명
        </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 accounts"
                  :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
                      :disabled="is_loading"
                      @click="shareCreatorChannel(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>
  </div>
</template>

<script>
import * as api from "@/api/member";
import * as dynamicLink from "@/api/firebase_dynamic_link";

export default {
  name: "CounselorList",

  data() {
    return {
      is_loading: false,
      page: 1,
      total_page: 0,
      total_creator_count: 0,
      search_word: '',
      accounts: [],
      account: {},
      utm_source: '',
      utm_medium: '',
      utm_campaign: '',
    }
  },

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

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

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

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

    async searchAccount() {
      if (this.search_word.length === 0) {
        await this.getAccounts()
      } else if (this.search_word.length < 2) {
        this.notifyError('검색어를 2글자 이상 입력하세요.')
      } else {
        this.is_loading = true
        try {
          const res = await api.searchCreator(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.accounts = 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.getAccounts()
      } else {
        await this.searchAccount()
      }
    },

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

          const total_page = Math.ceil(data.totalCount / 20)
          this.total_creator_count = data.totalCount;
          this.accounts = 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 shareCreatorChannel(item) {
      this.is_loading = true
      try {
          const linkData = await dynamicLink.shareCreatorChannel(item, this.utm_source, this.utm_medium, this.utm_campaign);
          if (linkData.status === 200) {
            await navigator.clipboard.writeText(linkData.data.shortLink)
            this.notifySuccess("링크가 복사되었습니다.")
          } else {
            this.notifyError("링크를 생성하지 못했습니다.")
          }
      } finally {
         this.is_loading = false
      }
    },
  }
}
</script>

<style>
.total-creator {
  padding-bottom: 0;
}

.total-creator > span {
  color: #3bb9f1;
}
</style>
