<template>
  <div class="fullPage">
    <div class="bg 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"
      />

      <!-- 主要内容 -->
      <div
        style="
          padding: 16px;

          display: flex;
          flex-direction: column;
          gap: 8px;
        "
      >
        <!-- 用户信息卡片 -->
        <div
          style="
            background-color: white;
            border-radius: 12px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

            padding: 16px;
            border: 1px solid #e5e7eb;

            display: flex;
            flex-direction: column;
            gap: 10px;
          "
        >
          <!-- 标题 -->
          <div style="font-weight: 600">{{ t('my_leader') }}</div>

          <!-- 用户信息 -->
          <div style="display: flex; align-items: center; gap: 4px">
            <!-- 头像 -->
            <div
              style="
                width: 3.5em;
                align-self: stretch;

                display: flex;
                align-items: center;
                justify-content: center;
              "
            >
              <img
                :src="userInfo.userAvatar || ''"
                style="
                  display: block;
                  width: 100%;
                  aspect-ratio: 1/1;
                  object-fit: cover;
                  border-radius: 50%;
                "
                @error="handleAvatarImageError"
              />
            </div>

            <!-- 基本信息 -->
            <div
              style="
                flex: 1;
                min-width: 0;
                align-self: stretch;
                display: flex;
                flex-direction: column;
                justify-content: space-around;
                gap: 4px;
              "
            >
              <div
                style="
                  font-weight: 700;
                  width: 100%;
                  overflow: hidden;
                  text-overflow: ellipsis;
                  white-space: nowrap;
                "
              >
                {{ userInfo.userNickname || '-' }}
              </div>
              <div style="color: rgba(0, 0, 0, 0.4); font-size: 0.8em; font-weight: 500">
                {{ t('user_id_prefix') }} {{ userInfo.account || '-' }}
              </div>
            </div>
          </div>
        </div>

        <!-- 角色模块 -->
        <div
          style="
            background-color: white;
            border-radius: 12px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

            padding: 16px;
            border: 1px solid #e5e7eb;

            display: flex;
            flex-direction: column;
            gap: 4px;
          "
        >
          <!-- 标题 -->
          <div style="font-weight: 600; color: #1f2937">{{ t('my_role') }}</div>

          <!-- 角色身份 -->
          <div style="display: flex; justify-content: space-between; align-items: center">
            <div style="font-size: 1.1em; font-weight: 600">{{ t('admin') }}</div>
            <img
              src="../../assets/icon/detail.png"
              alt=""
              style="display: block; width: 1.5em"
              class="flipImg"
              @click="gotoPolicy"
            />
          </div>

          <!-- 分割线 -->
          <div style="border-bottom: 1px solid #e6e6e6"></div>

          <!-- 已完成任务 -->
          <div style="display: flex; justify-content: space-between; align-items: center">
            <div style="font-weight: 600">{{ t('task_completion_status') }}</div>
            <div style="font-weight: 600">({{ taskData.completedTaskCount || 0 }})</div>
          </div>

          <div v-if="taskData.tasks" style="display: flex; flex-direction: column; gap: 4px">
            <div style="font-weight: 500">
              {{ taskData.cycleStartDate }}-{{ taskData.cycleEndDate }}
            </div>
            <!-- 任务列表与完成状态 -->
            <div
              v-for="task in taskData.tasks"
              style="display: flex; justify-content: space-between; align-items: center"
            >
              <div style="color: rgba(0, 0, 0, 0.4); font-size: 0.8em; font-weight: 500">
                {{ taskName(task) }}
              </div>
              <div style="color: rgba(0, 0, 0, 0.4); font-size: 0.8em; font-weight: 500">
                {{ taskCompletedText(task) }}
              </div>
            </div>
          </div>
        </div>

        <!-- 本期团队收入 -->
        <div
          style="
            background-color: white;
            border-radius: 12px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

            padding: 16px;
            border: 1px solid #e5e7eb;

            display: flex;
            flex-direction: column;
            gap: 4px;
          "
        >
          <!-- 总收入 -->
          <div style="display: flex; justify-content: space-between; align-items: center">
            <!-- 基本信息 -->
            <div style="display: flex; flex-direction: column; gap: 4px">
              <div style="font-weight: 600">
                {{ t('team_earnings_this_period') }} ${{ teamSummary.teamEarningsThisPeriod || 0 }}
              </div>

              <div style="color: rgba(0, 0, 0, 0.4); font-size: 0.8em; font-weight: 500">
                {{ t('available_salaries') }} ${{ availableIncome?.availableBalance || 0 }}
              </div>
            </div>

            <!-- 跳转按钮 -->
            <img
              src="../../assets/icon/arrowBlack.png"
              alt=""
              style="display: block; width: 2em"
              class="flipImg"
              @click="gotoIncome"
            />
          </div>

          <!-- 分割线 -->
          <div style="border-bottom: 1px solid #e6e6e6"></div>

          <!-- 我的BD Leader团队 -->
          <div style="display: flex; justify-content: space-between; align-items: center">
            <!-- 基本信息 -->
            <div style="display: flex; flex-direction: column; gap: 4px">
              <div style="font-weight: 600">
                {{ t('my_bd_leader_teams') }}({{ teamSummary.bdLeaderTeams?.count || 0 }})
              </div>

              <div style="color: rgba(0, 0, 0, 0.4); font-size: 0.8em; font-weight: 500">
                {{ t('total_income') }} ${{ teamSummary.bdLeaderTeams?.totalIncome || 0 }}
              </div>
            </div>

            <!-- 跳转按钮 -->
            <div style="align-self: stretch; display: flex; align-items: center; gap: 4px">
              <img
                src="../../assets/icon/addUser.png"
                alt=""
                style="display: block; width: 1.6em"
                class="flipImg"
                @click="gotoPage('/invite-bd-leader')"
              />
              <img
                src="../../assets/icon/list.png"
                alt=""
                style="display: block; width: 1.6em"
                class="flipImg"
                @click="gotoPage('/my-BDLeader-teams')"
              />
            </div>
          </div>

          <!-- 分割线 -->
          <div style="border-bottom: 1px solid #e6e6e6"></div>

          <!-- 我的BD团队 -->
          <div style="display: flex; justify-content: space-between; align-items: center">
            <!-- 基本信息 -->
            <div style="display: flex; flex-direction: column; gap: 4px">
              <div style="font-weight: 600">
                {{ t('my_bd_teams') }}({{ teamSummary.bdTeams?.count || 0 }})
              </div>

              <div style="color: rgba(0, 0, 0, 0.4); font-size: 0.8em; font-weight: 500">
                {{ t('total_income') }} ${{ teamSummary.bdTeams?.totalIncome || 0 }}
              </div>
            </div>

            <!-- 跳转按钮 -->
            <div style="align-self: stretch; display: flex; align-items: center; gap: 4px">
              <img
                src="../../assets/icon/addUser.png"
                alt=""
                style="display: block; width: 1.6em"
                class="flipImg"
                @click="gotoPage('/invite-bd')"
              />
              <img
                src="../../assets/icon/list.png"
                alt=""
                style="display: block; width: 1.6em"
                class="flipImg"
                @click="gotoPage('/my-BD-teams')"
              />
            </div>
          </div>

          <!-- 分割线 -->
          <div style="border-bottom: 1px solid #e6e6e6"></div>

          <!-- 我的Agency团队 -->
          <div style="display: flex; justify-content: space-between; align-items: center">
            <!-- 基本信息 -->
            <div style="display: flex; flex-direction: column; gap: 4px">
              <div style="font-weight: 600">
                {{ t('my_agency_teams') }}({{ teamSummary.agencyTeams?.count || 0 }})
              </div>

              <div style="color: rgba(0, 0, 0, 0.4); font-size: 0.8em; font-weight: 500">
                {{ t('total_income') }} ${{ teamSummary.agencyTeams?.totalIncome || 0 }}
              </div>
            </div>

            <!-- 跳转按钮 -->
            <div style="align-self: stretch; display: flex; align-items: center; gap: 4px">
              <img
                src="../../assets/icon/addUser.png"
                alt=""
                style="display: block; width: 1.6em"
                class="flipImg"
                @click="gotoPage('/invite-agency')"
              />
              <img
                src="../../assets/icon/list.png"
                alt=""
                style="display: block; width: 1.6em"
                class="flipImg"
                @click="gotoPage('/my-agency-teams')"
              />
            </div>
          </div>

          <!-- 分割线 -->
          <div style="border-bottom: 1px solid #e6e6e6"></div>

          <!-- 我的Recharge Agency团队 -->
          <div style="display: flex; justify-content: space-between; align-items: center">
            <!-- 基本信息 -->
            <div style="display: flex; flex-direction: column; gap: 4px">
              <div style="font-weight: 600">
                {{ t('number_of_recharge_agents_invited') }}({{
                  teamSummary.rechargeTeams?.count || 0
                }})
              </div>

              <div style="color: rgba(0, 0, 0, 0.4); font-size: 0.8em; font-weight: 500">
                {{ t('total_recharge') }}: ${{ teamSummary.rechargeTeams?.totalIncome || 0 }}
              </div>
            </div>

            <!-- 跳转按钮 -->
            <div style="align-self: stretch; display: flex; align-items: center; gap: 4px">
              <img
                src="../../assets/icon/addUser.png"
                alt=""
                style="display: block; width: 1.6em"
                class="flipImg"
                @click="gotoPage('/invite-recharge-agency')"
              />
              <img
                src="../../assets/icon/list.png"
                alt=""
                style="display: block; width: 1.6em"
                class="flipImg"
                @click="gotoPage('/my-recharge-agency')"
              />
            </div>
          </div>

          <!-- 分割线 -->
          <div style="border-bottom: 1px solid #e6e6e6"></div>
        </div>

        <!-- 赠送礼物 -->
        <div
          style="
            background-color: white;
            border-radius: 12px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

            padding: 16px;
            border: 1px solid #e5e7eb;

            display: flex;
            justify-content: space-between;
            gap: 4px;
          "
          @click="send"
        >
          <div style="font-weight: 600">{{ t('send_welcome_gift') }}</div>
          <img
            src="../../assets/icon/arrowBlack.png"
            alt=""
            style="display: block; width: 1.5em"
            class="flipImg"
          />
        </div>

        <!-- 前往用户编辑 -->
        <div
          v-if="teamPermissionCheck.hasUserEditingPermission"
          style="
            background-color: white;
            border-radius: 12px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

            padding: 16px;
            border: 1px solid #e5e7eb;

            display: flex;
            justify-content: space-between;
            gap: 4px;
          "
          @click="gotoAppPage('editingUser')"
        >
          <div style="font-weight: 600">{{ t('user_editing') }}</div>
          <img
            src="../../assets/icon/arrowBlack.png"
            alt=""
            style="display: block; width: 1.5em"
            class="flipImg"
          />
        </div>

        <!-- 前往房间编辑 -->
        <div
          v-if="teamPermissionCheck.hasRoomEditingPermission"
          style="
            background-color: white;
            border-radius: 12px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

            padding: 16px;
            border: 1px solid #e5e7eb;

            display: flex;
            justify-content: space-between;
            gap: 4px;
          "
          @click="gotoAppPage('editingRoom')"
        >
          <div style="font-weight: 600">{{ t('room_editing') }}</div>
          <img
            src="../../assets/icon/arrowBlack.png"
            alt=""
            style="display: block; width: 1.5em"
            class="flipImg"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { computed, 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/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);
}

.fullPage {
  position: relative;

  max-height: 100vh;
  overflow-y: auto;
  background-color: #ffffff;
}

.fullPage::-webkit-scrollbar {
  display: none;
}

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

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

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

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

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