<template>
  <div class="host-center gradient-background-circles">
    <!-- 顶部导航 -->
    <MobileHeader title="Host Center" :isHomePage="true" />

    <!-- 主要内容 -->
    <div class="content">
      <!-- 身份 -->
      <div
        style="
          margin: 0 1%;
          margin-bottom: 12px;
          font-weight: 600;
          display: flex;
          align-items: center;
          font-size: 1.3em;
        "
      >
        My account
        <img src="../assets/icon/host.png" alt="" height="20px" style="margin-left: 10px" />
      </div>

      <!-- 用户信息卡片 -->
      <div
        style="
          background-color: white;
          padding: 16px;
          border-radius: 12px;
          box-shadow: 0 0 4px 0 rgba(0, 0, 0, 0.25);
          margin: 0 1%;
          margin-bottom: 12px;
          display: flex;
          flex-direction: column;
          justify-content: space-between;
        "
      >
        <!-- 头像信息 -->
        <div style="display: flex; align-items: center; margin-bottom: 12px">
          <div class="avatar">
            <img
              v-if="userInfo.userAvatar"
              :src="userInfo.userAvatar"
              :alt="userInfo.name"
              @error="handleImageError"
            />
            <span v-else class="avatar-placeholder">{{ getAvatarPlaceholder() }}</span>
          </div>
          <div style="flex: 1">
            <div style="margin: 0 0 4px 0; font-size: 16px; font-weight: 600; color: #333">
              {{ userInfo.userNickname || userInfo.name }}
            </div>
            <div style="margin: 0; font-size: 14px; color: #666">ID: {{ userInfo.id }}</div>
          </div>
          <button
            style="width: 32px; height: 32px; border: none; background: none; font-size: 16px"
            @click="goToNotification"
          >
            <img src="../assets/icon/edit.png" alt="" width="70%" />
          </button>
        </div>
        <!-- 我的薪资 -->
        <div>
          <div style="display: flex; justify-content: space-between; margin-bottom: 5px">
            <div style="font-weight: 600">My salary:</div>
            <button
              style="
                font-weight: 500;
                color: rgba(0, 0, 0, 0.4);
                border: 0;
                background-color: transparent;
              "
              @click="showDatePicker"
            >
              Personal Salary >
            </button>
          </div>
        </div>

        <!-- 历史薪资 -->
        <div style="display: grid; grid-template-columns: repeat(2, 1fr)">
          <div>
            <div style="font-weight: 500; color: rgba(0, 0, 0, 0.4); margin-bottom: 5px">
              History Salary:
            </div>
            <div style="font-weight: 600">${{ salaryInfo.hostSalary }}</div>
          </div>
          <div>
            <div style="font-weight: 500; color: rgba(0, 0, 0, 0.4); margin-bottom: 5px">
              Current Salary:
            </div>
            <div style="font-weight: 600">${{ salaryInfo.currentSalary }}</div>
          </div>
        </div>
      </div>

      <!-- 今日任务 -->
      <div
        style="
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          gap: 5px;
          background-color: white;
          padding: 3%;
          border-radius: 12px;
          margin: 0 1%;
          margin-bottom: 12px;
          box-shadow: 0 0 4px 0 rgba(0, 0, 0, 0.25);
        "
      >
        <div style="display: flex; justify-content: space-between">
          <div style="font-weight: 600">Today's Task:</div>
          <button
            style="
              font-weight: 500;
              color: rgba(0, 0, 0, 0.4);
              border: 0;
              background-color: transparent;
            "
            @click="goToPlatformPolicy"
          >
            Platform Policy >
          </button>
        </div>
        <div style="display: flex">
          <div style="flex: 1">
            <div
              style="
                width: max-content;
                display: flex;
                flex-direction: column;
                align-items: center;
                gap: 5px;
              "
            >
              <div style="font-weight: 600">Anchor Type</div>
              <div style="font-weight: 600">{{ taskInfo.anchorType }}</div>
            </div>
          </div>
          <div
            style="flex: 1; display: flex; flex-direction: column; align-items: center; gap: 5px"
          >
            <div style="font-weight: 600">Minutes</div>
            <div style="font-weight: 600">
              {{ taskInfo.minutesProgress }}/{{ taskInfo.minutesTotal }}
            </div>
          </div>
          <div style="flex: 1; display: flex; justify-content: flex-end">
            <div
              style="
                width: max-content;
                display: flex;
                flex-direction: column;
                align-items: center;
                gap: 5px;
              "
            >
              <div style="font-weight: 600">Gift Task</div>
              <div style="font-weight: 600">{{ taskInfo.giftTask }}</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 进度信息 -->
      <workReportBox
        style="margin-bottom: 10px"
        :type="progressInfo.status"
        :date="progressInfo.date"
        :target="progressInfo.target"
        :salary="progressInfo.salary"
        :income="progressInfo.income"
        :days="progressInfo.timeDays"
      ></workReportBox>

      <!-- 操作按钮 -->
      <div class="action-buttons">
        <button class="action-btn exchange-btn" @click="exchangeGoldCoins">Exchange</button>
        <button class="action-btn transfer-btn" @click="transfer">Transfer</button>
        <!--
        <button class="action-btn withdraw-btn" @click="cashWithdraw">
          Cash<br>Withdraw
        </button>
        -->
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, reactive } from 'vue'
import { useRouter } from 'vue-router'
import MobileHeader from '../components/MobileHeader.vue'
import { usePageInitializationWithConfig } from '@/utils/pageConfig.js'
import { isInApp } from '@/utils/appBridge.js'
import { getTeamMemberWork } from '@/api/teamBill.js'
import { getUserId } from '@/utils/userStore.js'
import { clearSelectedPayee } from '../utils/payeeStore.js'
import workReportBox from '@/components/HostCenter/workReportBox.vue'

const router = useRouter()

// 进度信息
const progressInfo = reactive({
  date: '–',
  status: '–',
  target: '–',
  salary: '–',
  timeDays: '–',
  hostSalary: '–',
  agentSalary: '–',
  total: '–',
})
const loadingProgressInfo = reactive({ value: false })

// 获取成员工作数据
const fetchMemberWorkData = async () => {
  try {
    loadingProgressInfo.value = true
    const userId = getUserId()

    if (!userId) {
      console.warn('No user ID available')
      return
    }

    const response = await getTeamMemberWork(userId)
    if (response && response.status && response.body) {
      const data = response.body

      // 取第一条target数据（最新的工作数据）
      if (data.targets && data.targets.length > 0) {
        const latestTarget = data.targets[0]

        // 格式化日期：202508 -> 08/2025
        const billBelong = latestTarget.billBelong.toString()
        const year = billBelong.substring(0, 4)
        const month = billBelong.substring(4, 6)

        // 格式化状态
        const formatStatus = (status) => {
          const statusMap = {
            SETTLED: 'Completed',
            UNPAID: 'In Progress',
            HANG_UP: 'Out of Account',
            PAY_OUT: 'Completed',
          }
          return statusMap[status] || status
        }

        // 获取level值
        const level =
          latestTarget.target?.settlementResult?.level || latestTarget.target?.level || '–'

        // 更新数据
        Object.assign(progressInfo, {
          date: `${month}.${year}`,
          status: formatStatus(latestTarget.status),
          target: level,
          salary: latestTarget.target?.settlementResult?.ownSalary?.toFixed(2) || '–',
          income: latestTarget.target?.settlementResult?.acceptGiftValue,
          timeDays: latestTarget.target?.effectiveDay || '–',
        })
      } else {
        console.warn('No targets data available')
      }
    } else {
      console.warn('No member work data available')
    }
  } catch (error) {
    console.error('Failed to fetch member work data:', error)
  } finally {
    loadingProgressInfo.value = false
  }
}

const showDatePicker = () => {
  router.push('/history-salary')
}

const goToPlatformPolicy = () => {
  router.push('/platform-salary')
}

const goToNotification = () => {
  router.push('/host-setting')
}

const exchangeGoldCoins = () => {
  router.push('/exchange-gold-coins')
}

const transfer = () => {
  router.push('/transfer')
}

const { appConnected, userInfo, salaryInfo, taskInfo, handleImageError, getAvatarPlaceholder } =
  usePageInitializationWithConfig('HOST_CENTER', {
    needsTeamInfo: true,
    onDataLoaded: () => {
      fetchMemberWorkData() // 新增：获取成员工作数据
    },
  })

onMounted(() => {
  clearSelectedPayee() //清除选中的收款人
})
</script>

<style scoped>
* {
  color: rgba(0, 0, 0, 0.8);
  font-family: 'SF Pro Text';
}

.content {
  padding: 16px;
  position: relative;
  z-index: 2;
}

@keyframes pulse {
  0%,
  100% {
    opacity: 1;
  }
  50% {
    opacity: 0.5;
  }
}

.avatar {
  width: 50px;
  height: 50px;
  border-radius: 25px;
  background-color: #8b5cf6;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 20px;
  font-weight: 600;
  margin-right: 12px;
  overflow: hidden;
  position: relative;
}

.avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 25px;
}

.avatar .avatar-placeholder {
  color: white;
  font-size: 20px;
  font-weight: 600;
}

/* 任务区域头部样式 */
.task-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.task-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

/* 任务表格 */
.task-table {
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  overflow: hidden;
  margin-bottom: 12px;
}

/* 操作按钮 */
.action-buttons {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 12px;
}

.action-btn {
  padding: 14px 12px;
  border: none;
  border-radius: 12px;
  font-size: 14px;
  font-weight: 600;
  text-align: center;
  line-height: 1.2;
  transition: all 0.2s;
  width: 100%;
}

.action-btn:active {
  transform: scale(0.98);
}

.exchange-btn {
  background: linear-gradient(135deg, #f1eca6 2.82%, #ffd22f 99.15%), #fff;
  box-shadow: 0 0 4px 0 rgba(0, 0, 0, 0.25);
  color: white;
}

.transfer-btn {
  background: linear-gradient(135deg, #a6aaf1 2.82%, #592fff 99.15%), #fff;
  box-shadow: 0 0 4px 0 rgba(0, 0, 0, 0.25);
  color: white;
}

.withdraw-btn {
  color: white;
}

@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;
  }
}
</style>
