<template>
  <div class="admin-page">
    <div class="admin-shell gradient-background-circles">
      <GeneralHeader
        :isHomePage="true"
        :showLanguageList="true"
        :title="t('admin_center')"
        color="black"
        style="box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); z-index: 999"
      />

      <main class="admin-content">
        <section class="leader-panel">
          <div class="section-kicker">{{ t('my_leader') }}</div>
          <div class="leader-card">
            <div class="leader-avatar">
              <img
                :src="userInfo.userAvatar || ''"
                class="avatar-image"
                alt=""
                @error="handleAvatarImageError"
              />
            </div>
            <div class="leader-meta">
              <div class="leader-name">{{ userInfo.userNickname || '-' }}</div>
              <div class="muted-text">
                {{ t('user_id_prefix') }} {{ userInfo.account || '-' }}
              </div>
            </div>
          </div>
        </section>

        <section class="admin-card role-card">
          <div class="section-title-row">
            <div>
              <div class="section-kicker">{{ t('my_role') }}</div>
              <div class="section-title">{{ t('admin') }}</div>
            </div>
            <button class="icon-action" type="button" v-touch-tap="gotoPolicy">
              <img src="../../assets/icon/Aslan/detail.png" alt="" class="icon-image flipImg" />
            </button>
          </div>

          <div class="task-summary">
            <div>{{ t('task_completion_status') }}</div>
            <strong>({{ taskData.completedTaskCount || 0 }})</strong>
          </div>

          <div v-if="taskData.tasks" class="task-list">
            <div class="task-period">
              {{ taskData.cycleStartDate }}-{{ taskData.cycleEndDate }}
            </div>
            <div v-for="task in taskData.tasks" :key="task.taskType" class="task-row">
              <span>{{ taskName(task) }}</span>
              <strong>{{ taskCompletedText(task) }}</strong>
            </div>
          </div>
        </section>

        <section class="admin-card income-card">
          <div class="income-summary">
            <div>
              <div class="income-title">
                {{ t('team_earnings_this_period') }} ${{ teamSummary.teamEarningsThisPeriod || 0 }}
              </div>
              <div class="muted-text">
                {{ t('available_salaries') }} ${{ availableIncome?.availableBalance || 0 }}
              </div>
            </div>
            <button class="round-action" type="button" v-touch-tap="gotoIncome">
              <img src="../../assets/icon/Aslan/arrowBlack.png" alt="" class="flipImg" />
            </button>
          </div>

          <div class="team-list">
            <div class="team-row">
              <div class="team-copy">
                <div class="team-title">
                  {{ t('my_bd_leader_teams') }}({{ teamSummary.bdLeaderTeams?.count || 0 }})
                </div>
                <div class="muted-text">
                  {{ t('total_income') }} ${{ teamSummary.bdLeaderTeams?.totalIncome || 0 }}
                </div>
              </div>
              <div class="team-actions">
                <button
                  class="square-action"
                  type="button"
                  v-touch-tap="() => gotoPage('/invite-bd-leader')"
                >
                  <img src="../../assets/icon/Aslan/addUser.png" alt="" class="flipImg" />
                </button>
                <button
                  class="square-action"
                  type="button"
                  v-touch-tap="() => gotoPage('/my-BDLeader-teams')"
                >
                  <img src="../../assets/icon/Aslan/list.png" alt="" class="flipImg" />
                </button>
              </div>
            </div>

            <div class="team-row">
              <div class="team-copy">
                <div class="team-title">
                  {{ t('my_bd_teams') }}({{ teamSummary.bdTeams?.count || 0 }})
                </div>
                <div class="muted-text">
                  {{ t('total_income') }} ${{ teamSummary.bdTeams?.totalIncome || 0 }}
                </div>
              </div>
              <div class="team-actions">
                <button
                  class="square-action"
                  type="button"
                  v-touch-tap="() => gotoPage('/invite-bd')"
                >
                  <img src="../../assets/icon/Aslan/addUser.png" alt="" class="flipImg" />
                </button>
                <button
                  class="square-action"
                  type="button"
                  v-touch-tap="() => gotoPage('/my-BD-teams')"
                >
                  <img src="../../assets/icon/Aslan/list.png" alt="" class="flipImg" />
                </button>
              </div>
            </div>

            <div class="team-row">
              <div class="team-copy">
                <div class="team-title">
                  {{ t('my_agency_teams') }}({{ teamSummary.agencyTeams?.count || 0 }})
                </div>
                <div class="muted-text">
                  {{ t('total_income') }} ${{ teamSummary.agencyTeams?.totalIncome || 0 }}
                </div>
              </div>
              <div class="team-actions">
                <button
                  class="square-action"
                  type="button"
                  v-touch-tap="() => gotoPage('/invite-agency')"
                >
                  <img src="../../assets/icon/Aslan/addUser.png" alt="" class="flipImg" />
                </button>
                <button
                  class="square-action"
                  type="button"
                  v-touch-tap="() => gotoPage('/my-agency-teams')"
                >
                  <img src="../../assets/icon/Aslan/list.png" alt="" class="flipImg" />
                </button>
              </div>
            </div>

            <div class="team-row">
              <div class="team-copy">
                <div class="team-title">
                  {{ t('number_of_recharge_agents_invited') }}({{
                    teamSummary.rechargeTeams?.count || 0
                  }})
                </div>
                <div class="muted-text">
                  {{ t('total_recharge') }}: ${{ teamSummary.rechargeTeams?.totalIncome || 0 }}
                </div>
              </div>
              <div class="team-actions">
                <button
                  class="square-action"
                  type="button"
                  v-touch-tap="() => gotoPage('/invite-recharge-agency')"
                >
                  <img src="../../assets/icon/Aslan/addUser.png" alt="" class="flipImg" />
                </button>
                <button
                  class="square-action"
                  type="button"
                  v-touch-tap="() => gotoPage('/my-recharge-agency')"
                >
                  <img src="../../assets/icon/Aslan/list.png" alt="" class="flipImg" />
                </button>
              </div>
            </div>
          </div>
        </section>

        <section class="quick-actions">
          <button class="quick-action" type="button" v-touch-tap="send">
            <span>{{ t('send_welcome_gift') }}</span>
            <img src="../../assets/icon/Aslan/arrowBlack.png" alt="" class="flipImg" />
          </button>

          <button
            v-if="teamPermissionCheck.hasUserEditingPermission"
            class="quick-action"
            type="button"
            v-touch-tap="() => gotoAppPage('editingUser')"
          >
            <span>{{ t('user_editing') }}</span>
            <img src="../../assets/icon/Aslan/arrowBlack.png" alt="" class="flipImg" />
          </button>

          <button
            v-if="teamPermissionCheck.hasRoomEditingPermission"
            class="quick-action"
            type="button"
            v-touch-tap="() => gotoAppPage('editingRoom')"
          >
            <span>{{ t('room_editing') }}</span>
            <img src="../../assets/icon/Aslan/arrowBlack.png" alt="" class="flipImg" />
          </button>
        </section>
      </main>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { setDocumentDirection } from '@/locales/i18n'
import { gotoAppPage } from '@/utils/appBridge.js'
import { getUserId } from '@/utils/userStore.js'
import { usePageInitializationWithConfig } from '@/utils/pageConfig.js'
import { handleAvatarImageError } from '@/utils/image/imageHandler.js'
import { useIdentityStore } from '@/stores/identity.js'
import { showError } from '@/utils/toast.js'

import {
  apiTaskList, //获取任务列表
  apiGetTeamSummary, // 查询BD团队总览
  apiGetTeamPermissionCheck, // 检查权限
} from '@/api/admin.js'
import {
  apiGetBankBalance, //获取当前余额
} from '@/api/wallet.js'

import GeneralHeader from '@/components/GeneralHeader.vue'

const { t, locale } = useI18n()
const router = useRouter()
const identityStore = useIdentityStore()

// 监听语言变化并设置文档方向
locale.value && setDocumentDirection(locale.value)

const taskData = ref({}) //任务项目数据
const availableIncome = ref({})
const teamSummary = ref({}) //团队总览
const teamPermissionCheck = ref({}) //团队权限检查

// 任务名称
const taskName = (task) => {
  if (task.taskType == 'MIC_USAGE') {
    return t('mic_usage_time')
  } else if (task.taskType == 'WORKING_DAYS') {
    return t('working_days_desc')
  } else if (task.taskType == 'NEW_BD_LEADERS') {
    return t('new_bd_leaders_bound')
  } else if (task.taskType == 'NEW_BDS') {
    return t('new_bds_bound')
  } else if (task.taskType == 'NEW_AGENCIES') {
    return t('new_agencies_bound')
  }
}

// 任务完成情况
const taskCompletedText = (task) => {
  if (task.taskType == 'MIC_USAGE') {
    return `(${task.completedCount}/${task.targetCount}h)`
  } else {
    return `(${task.completedCount}/${task.targetCount})`
  }
}

const send = () => {
  router.push({ path: '/item-distribution' })
}

// 前往收益处理页面
const gotoIncome = () => {
  router.push({ path: '/available-income' })
}

// 前往政策页面
const gotoPolicy = () => {
  router.push({ path: '/admin-policy' })
}

// 前往页面
const gotoPage = (path) => {
  router.push({ path: path })
}

// 获取任务列表
const getTaskList = async () => {
  let data = {
    userId: getUserId(),
  }
  const resInvitedList = await apiTaskList(data)
  console.log('任务列表:', resInvitedList)
  if (resInvitedList.status && resInvitedList.body) {
    taskData.value = resInvitedList.body
  }
}

// 获取银行余额
const fetchBankBalance = async () => {
  try {
    const response = await apiGetBankBalance('ADMIN_SALARY')

    if (response.status && response.body) {
      availableIncome.value = response.body || {}
    }
  } catch (error) {
    console.error('Failed to fetch bank balance:', error)
    showError(t('failed_to_load_balance'))
  }
}

// 查询团队总览
const getTeamSummary = async () => {
  const resTeamSummary = await apiGetTeamSummary()
  console.log('团队总览:', resTeamSummary)
  if (resTeamSummary.status && resTeamSummary.body) {
    teamSummary.value = resTeamSummary.body
  }
}

// 检查权限
const getTeamPermissionCheck = async () => {
  const resTeamPermissionCheck = await apiGetTeamPermissionCheck()
  console.log('权限列表:', resTeamPermissionCheck)
  if (resTeamPermissionCheck.status && resTeamPermissionCheck.body) {
    teamPermissionCheck.value = resTeamPermissionCheck.body
  }
}

// 初始化数据
const init = () => {
  getTaskList() // 获取任务列表
  fetchBankBalance() // 获取银行余额
  getTeamSummary() // 查询BD团队总览
  getTeamPermissionCheck() // 检查权限
}

const { userInfo } = usePageInitializationWithConfig('ADMIN_CENTER', {
  forceRefresh: true, // 强制刷新
  needsTeamInfo: true,
  needsBankBalance: false,
  onDataLoaded: () => {},
})

onMounted(() => {
  init()
  identityStore.setIdentity('ADMIN')
})
</script>

<style scoped>
* {
  color: rgba(0, 0, 0, 0.8);
  box-sizing: border-box;
}

.admin-page {
  position: relative;
  height: 100vh;
  overflow-y: auto;
  background: #f5f7fb;
}

.admin-page::-webkit-scrollbar {
  display: none;
}

.admin-shell {
  width: 100vw;
  min-height: 100vh;
  background-image: url(../../assets/images/Aslan/secondBg.png);
  background-size: 100% auto;
  background-repeat: no-repeat;
}

.admin-content {
  position: relative;
  z-index: 2;
  display: flex;
  flex-direction: column;
  gap: 14px;
  padding: 18px 16px 26px;
}

.admin-card,
.leader-panel,
.quick-action {
  background: rgba(255, 255, 255, 0.96);
  border: 1px solid rgba(212, 218, 232, 0.9);
  border-radius: 18px;
  box-shadow: 0 10px 26px rgba(37, 45, 65, 0.08);
}

.leader-panel {
  padding: 16px;
}

.leader-card {
  display: flex;
  align-items: center;
  gap: 14px;
  margin-top: 10px;
}

.leader-avatar {
  width: 68px;
  height: 68px;
  flex: 0 0 68px;
  padding: 3px;
  border-radius: 50%;
  background: linear-gradient(135deg, #bb92ff, #6fb1ff);
}

.avatar-image {
  display: block;
  width: 100%;
  height: 100%;
  border-radius: 50%;
  object-fit: cover;
  background: #eef2f7;
}

.leader-meta {
  min-width: 0;
  flex: 1;
}

.leader-name {
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-size: 1.35em;
  font-weight: 800;
}

.section-kicker {
  color: rgba(31, 41, 55, 0.58);
  font-size: 0.98em;
  font-weight: 700;
}

.section-title-row,
.income-summary,
.team-row,
.quick-action {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
}

.section-title {
  margin-top: 3px;
  color: #111827;
  font-size: 1.32em;
  font-weight: 800;
}

.role-card,
.income-card {
  padding: 16px;
}

.icon-action,
.round-action,
.square-action,
.quick-action {
  border: 0;
  -webkit-tap-highlight-color: transparent;
  touch-action: manipulation;
}

.icon-action,
.round-action,
.square-action {
  display: flex;
  align-items: center;
  justify-content: center;
  flex: 0 0 auto;
  background: #f4f2ff;
}

.icon-action {
  width: 46px;
  height: 46px;
  border-radius: 14px;
}

.icon-image {
  display: block;
  width: 24px;
}

.task-summary {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 14px;
  padding: 12px 0;
  border-top: 1px solid rgba(229, 231, 235, 0.9);
  border-bottom: 1px solid rgba(229, 231, 235, 0.9);
  font-size: 1.08em;
  font-weight: 700;
}

.task-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
  padding-top: 12px;
}

.task-period {
  font-size: 1.02em;
  font-weight: 700;
}

.task-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 10px;
  color: rgba(31, 41, 55, 0.62);
  font-size: 0.98em;
  font-weight: 650;
}

.income-title {
  color: #111827;
  font-size: 1.2em;
  font-weight: 800;
  line-height: 1.35;
}

.muted-text {
  color: rgba(31, 41, 55, 0.56);
  font-size: 1em;
  font-weight: 650;
  line-height: 1.35;
}

.round-action {
  width: 48px;
  height: 48px;
  border-radius: 50%;
}

.round-action img,
.square-action img,
.quick-action img {
  display: block;
  width: 24px;
}

.team-list {
  display: flex;
  flex-direction: column;
  margin-top: 14px;
  border-top: 1px solid rgba(229, 231, 235, 0.9);
}

.team-row {
  min-height: 72px;
  padding: 12px 0;
  border-bottom: 1px solid rgba(229, 231, 235, 0.78);
}

.team-row:last-child {
  border-bottom: 0;
}

.team-copy {
  min-width: 0;
  flex: 1;
}

.team-title {
  overflow-wrap: anywhere;
  color: #1f2937;
  font-size: 1.08em;
  font-weight: 800;
  line-height: 1.35;
}

.team-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.square-action {
  width: 44px;
  height: 44px;
  border-radius: 13px;
}

.quick-actions {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.quick-action {
  width: 100%;
  min-height: 58px;
  padding: 0 16px;
  font-size: 1.08em;
  font-weight: 800;
  text-align: start;
}

.quick-action:active,
.icon-action:active,
.round-action:active,
.square-action:active {
  transform: scale(0.97);
}

@media screen and (max-width: 360px) {
  * {
    font-size: 12px;
  }
}

@media screen and (min-width: 360px) {
  * {
    font-size: 14px;
  }
}

@media screen and (min-width: 768px) {
  * {
    font-size: 24px;
  }
}

[dir='rtl'] .flipImg {
  transform: scaleX(-1);
}
</style>
