<template>
  <div class="history-salary gradient-background-circles">
    <!-- 修改头部使用 GeneralHeader 组件 -->
    <GeneralHeader
      :title="t('history_salary')"
      :showBack="true"
      :showLanguageList="true"
      color="black"
      style="box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); z-index: 999"
      @help="showHelpInfo"
    />

    <!-- 内容 -->
    <div class="content">
      <!-- 历史薪资 -->
      <div
        style="
          margin: 0 1%;
          background-color: white;
          padding: 16px;
          border-radius: 12px;
          box-shadow: 0 0 4px 0 rgba(0, 0, 0, 0.25);
          display: flex;
          justify-content: space-between;
          align-items: center;
        "
      >
        <div style="display: flex; flex-direction: column; gap: 10px">
          <div>{{ t('history_salary') }}</div>
          <div style="font-weight: 600">${{ totalSalary }}</div>
        </div>
        <img src="../assets/icon/help.png" alt="" class="info-btn" @click.stop="showHelpInfo" />
      </div>

      <!-- 工作报告 -->
      <div style="margin-bottom: 20px">
        <div style="margin: 10px 1%; font-weight: 600; color: rgba(0, 0, 0, 0.4)">
          {{ t('work_report') }}
        </div>

        <!-- 加载状态 -->
        <div v-if="loading" class="loading-container">
          <div class="loading-spinner"></div>
          <p>{{ t('loading') }}...</p>
        </div>

        <!-- 报告列表 -->
        <div
          v-else-if="workReports.length > 0"
          style="display: flex; flex-direction: column; gap: 12px"
        >
          <!-- 进度信息 -->
          <workReportBox
            v-for="report in workReports"
            :key="report.id"
            :type="report.status"
            :date="report.date"
            :target="report.target"
            :salary="report.salary"
            :income="report.income"
            :days="report.timeDays"
            more="true"
            @showMore="showReportDetail(report)"
          ></workReportBox>
        </div>

        <!-- 空数据状态 -->
        <div v-else class="empty-state">
          <div class="empty-icon">📋</div>
          <p>{{ t('no_data_available') }}</p>
        </div>
      </div>
    </div>

    <!-- 遮罩层 -->
    <div v-if="showDetailModal || showHelpModal" class="modal-overlay" @click="closeModal">
      <!-- 详情模态框 -->
      <div v-if="showDetailModal" style="position: fixed; bottom: 0; width: 100%">
        <div
          style="
            background: white;
            border-radius: 16px 16px 0 0;
            max-height: 80vh;
            overflow: hidden;
            display: flex;
            flex-direction: column;
            gap: 10px;
            padding: 20px;
          "
          @click.stop
        >
          <div style="display: flex; justify-content: center; align-items: center">
            <div style="margin: 0; font-size: 18px; font-weight: 600; color: #333">
              {{ t('salary_details') }}
            </div>
          </div>

          <!-- 日期和类型 -->
          <div style="display: flex; justify-content: space-between; align-items: center">
            <div style="color: rgba(0, 0, 0, 0.5); font-weight: 600; font-size: 1.3em">
              {{ selectedReport?.date }}
            </div>
            <div
              style="
                margin: 4px;
                padding: 0 8px;
                border-radius: 4px;
                display: flex;
                align-items: center;
              "
              :style="{ boxShadow }"
            >
              <div style="font-weight: 500" :style="{ color }">
                {{ typeShowText }}
              </div>
            </div>
          </div>

          <div
            v-if="dailyTargets.length > 0"
            style="font-size: 16px; font-weight: 600; color: #333"
          >
            {{ t('monthly_salary') }}:
          </div>

          <!-- 等级卡片 -->
          <div
            v-if="selectedReport"
            style="
              box-shadow: 0 0 4px 0 rgba(0, 0, 0, 0.25);
              border-radius: 8px;
              padding: 12px;
              margin: 0 4px;
            "
          >
            <div>
              <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 10px">
                <div class="text-700">{{ t('target') }}: {{ selectedReport.target }}</div>
                <div class="text-700">{{ t('salary') }}: ${{ selectedReport.salary }}</div>
                <div class="text-700">{{ t('time_days') }}: {{ selectedReport.timeDays }}</div>
                <div class="text-700">{{ t('total_income') }}: {{ selectedReport.income }}</div>
              </div>
            </div>
          </div>

          <div
            v-if="dailyTargets.length > 0"
            style="font-size: 16px; font-weight: 600; color: #333"
          >
            {{ t('daily_salary') }}:
          </div>

          <div style="overflow-y: auto" class="salaryList">
            <!-- 每日薪资列表 -->

            <div
              v-if="dailyTargets.length > 0"
              style="display: flex; flex-direction: column; gap: 8px; padding: 4px"
            >
              <div
                v-for="daily in dailyTargets"
                :key="daily.dateNumber"
                style="box-shadow: 0 0 4px 0 rgba(0, 0, 0, 0.25); border-radius: 8px; padding: 10px"
              >
                <div class="text-700" style="color: rgba(0, 0, 0, 0.4); margin-bottom: 8px">
                  {{ formatDateNumber(daily.dateNumber) }}
                </div>
                <div style="display: flex; justify-content: space-between; align-items: center">
                  <div class="text-700">{{ t('income') }}: {{ daily.acceptGiftValue }}</div>

                  <div style="font-size: 14px">
                    <span class="text-700">{{ t('time') }}:</span>
                    <span
                      class="text-700"
                      style="font-weight: 600"
                      :class="{
                        'time-value': formatOnlineTime(daily.onlineTime) == 120,
                      }"
                    >
                      {{ formatOnlineTime(daily.onlineTime) }}/120
                    </span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 帮助模态框 -->
      <div v-if="showHelpModal" class="modal-item">
        <div
          style="
            background-color: white;
            border-radius: 12px;
            width: 90%;
            max-width: 400px;
            max-height: 80vh;
            overflow: hidden;
            display: flex;
            flex-direction: column;
          "
          @click.stop
        >
          <div
            style="
              display: flex;
              justify-content: center;
              align-items: center;
              padding: 16px;
              position: relative;
            "
          >
            <div style="margin: 0; font-size: 18px; font-weight: 600; color: #333">
              {{ t('help') }}
            </div>
            <div @click="closeModal" class="closeBt">×</div>
          </div>

          <div class="help-modal-body">
            <p>{{ t('work_report_description') }}</p>
            <p>{{ t('status_description') }}</p>
            <p>{{ t('status_completed') }}</p>
            <p>{{ t('status_pending') }}</p>
            <p>{{ t('status_out_of_account') }}</p>
            <p>{{ t('status_in_progress') }}</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import GeneralHeader from '@/components/GeneralHeader.vue'
import { getTeamMemberWork, getTeamReleasePolicy } from '../api/teamBill.js'
import { getTeamId, getUserId, getUserProfile } from '@/utils/userStore.js'
import { getUserIdentity } from '@/api/wallet.js'
import workReportBox from '@/components/HostCenter/workReportBox.vue'
import { setDocumentDirection } from '@/locales/i18n'

const { t, locale } = useI18n()

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

const totalSalary = ref('0.00')
const showHelpModal = ref(false)
const loading = ref(false)
const showDetailModal = ref(false)
const selectedReport = ref(null)
const originalTargetsData = ref([]) // 保存原始数据
const policyData = ref(null) // 添加政策数据
const loadingPolicy = ref(false) // 政策加载状态

// 工作报告数据
const workReports = ref([])
const dailyTargets = ref([])

// 样式
const color = ref('')
const boxShadow = ref('')

const typeShowText = ref('')

// 更新展示类型
const updateTypeShowText = (status) => {
  console.log('更新展示类型')

  if (status == 'In Progress') {
    typeShowText.value = t('in_progress')
  } else if (status == 'Pending') {
    typeShowText.value = t('pending')
  } else if (status == 'Completed') {
    typeShowText.value = t('completed')
  } else if (status == 'Out of account') {
    typeShowText.value = t('out_of_account')
  }
}

watch(
  () => selectedReport.value?.status,
  (newStatus) => {
    console.log('newStatus:', newStatus)
    updateTypeShowText(newStatus)
    if (newStatus == 'In Progress') {
      boxShadow.value = '0 0 1px 0 #6085FF'
      color.value = 'rgba(61, 115, 255, 1)'
    }
    if (newStatus == 'Pending') {
      boxShadow.value = '0 0 1px 0 #FF6062'
      color.value = 'rgba(255, 61, 64, 1)'
    }
    if (newStatus == 'Completed') {
      boxShadow.value = '0 0 1px 0 #60FF65'
      color.value = 'rgba(61, 255, 84, 1)'
    }
    if (newStatus == 'Out Of Account') {
      boxShadow.value = '0 0 1px 0 #6A6161'
      color.value = 'rgba(174, 174, 174, 1)'
    }
    return
  }
)

// 获取政策数据
const fetchPolicyData = async () => {
  try {
    loadingPolicy.value = true
    const teamId = getTeamId()
    if (!teamId) {
      console.warn('No team ID available')
      return
    }

    const response = await getTeamReleasePolicy(teamId)
    if (response && response.status && response.body) {
      policyData.value = response.body
      console.debug('Policy data loaded:', policyData.value)
    }
  } catch (error) {
    console.error('Failed to fetch policy data:', error)
  } finally {
    loadingPolicy.value = false
  }
}

// 根据政策数据和礼物价值计算等级
const getLevelFromPolicy = (giftValue) => {
  if (!policyData.value?.policy || !giftValue) {
    return 1 // 默认等级
  }

  const numValue = parseFloat(giftValue)
  if (isNaN(numValue)) {
    return 1
  }

  // 按target从大到小排序，找到第一个小于等于giftValue的level
  const sortedPolicy = [...policyData.value.policy].sort((a, b) => {
    return parseFloat(b.target) - parseFloat(a.target)
  })

  for (const policy of sortedPolicy) {
    if (numValue >= parseFloat(policy.target)) {
      return policy.level
    }
  }

  // 如果都不匹配，返回最低等级
  return Math.min(...policyData.value.policy.map((p) => p.level))
}

// 获取工作报告数据
const fetchWorkReports = async (userId) => {
  try {
    loading.value = true
    const response = await getTeamMemberWork(userId)

    if (response.status && response.body) {
      // 将 targets 数据转换为 workReports 格式
      const targets = response.body.targets || []
      originalTargetsData.value = targets // 保存原始数据

      const userIdentity = await getUserIdentity()

      workReports.value = targets.map((target) => ({
        id: target.id,
        date: `${target.billBelong.toString().substring(0, 4)}.${target.billBelong
          .toString()
          .substring(4, 6)}`,
        status: getStatusText(target.status),
        income: target.target?.acceptGiftValue,
        target: getLevelFromPolicy(target.target?.acceptGiftValue), // 使用政策数据计算等级
        salary:
          formatSalaryValue(
            userIdentity.body?.agent
              ? (target.target?.settlementResult?.ownSalary || 0) +
                  (target.target?.settlementResult?.memberSalary || 0)
              : userIdentity.body?.anchor
              ? target.target?.settlementResult?.memberSalary
              : null
          ) || '-',
        totalSalary: formatSalaryValue(target.target?.settlementResult?.totalSalary) || '-',
        timeDays: target.target?.effectiveDay || '-',
        hasDetails:
          target.target && target.target.dailyTargets && target.target.dailyTargets.length > 0,
        originalData: target, // 保存原始数据用于详情显示
      }))

      // 计算总薪资 - 根据用户身份选择对应的薪资字段
      const totalAmount = targets.reduce((sum, target) => {
        let salary = 0

        // 根据用户身份决定使用哪个薪资字段
        if (userIdentity.body?.agent) {
          // agent 为 true 时，使用 ownSalary
          salary = parseFloat(
            (target.target?.settlementResult?.ownSalary || 0) +
              (target.target?.settlementResult?.memberSalary || 0)
          )
        } else if (userIdentity.body?.anchor) {
          // anchor 为 true 时，使用 memberSalary
          salary = parseFloat(target.target?.settlementResult?.memberSalary || 0)
        }

        return sum + salary
      }, 0)

      totalSalary.value = totalAmount.toFixed(2)
    }
  } catch (error) {
    console.error('Failed to fetch work reports:', error)
    // 保持默认数据作为fallback
    workReports.value = [
      {
        id: 1,
        date: '2025.07',
        status: 'In Progress',
        target: '-',
        salary: '-',
        timeDays: '-',
        diamond: '-',
      },
    ]
  } finally {
    loading.value = false
  }
}

// 格式化薪资数值（与 TeamBillView 保持一致）
const formatSalaryValue = (value) => {
  if (!value || value === '0' || value === 0) return '0.00'
  const numValue = parseFloat(value)
  return numValue.toFixed(2)
}

// 格式化状态文本（与 TeamBillView 保持一致）
const getStatusText = (status) => {
  const statusMap = {
    SETTLED: t('completed'),
    UNPAID: t('in_progress'),
    HANG_UP: t('out_of_account'),
    PAY_OUT: t('completed'),
  }
  return statusMap[status] || status
}

// 显示报告详情
const showReportDetail = (report) => {
  selectedReport.value = report

  if (report.originalData && report.originalData.target) {
    const targetData = report.originalData.target

    // 直接设置每日目标数据
    dailyTargets.value = targetData.dailyTargets || []
  }

  showDetailModal.value = true
}

// 格式化在线时间（为 Daily Salary 显示分钟数）
const formatOnlineTime = (minutes) => {
  const mins = Math.min(parseInt(minutes), 120) || 0
  return mins
}

// 格式化日期数字
const formatDateNumber = (dateNumber) => {
  if (!dateNumber) return ''
  const dateStr = dateNumber.toString()
  if (dateStr.length !== 8) return dateStr

  const year = dateStr.substring(0, 4)
  const month = dateStr.substring(4, 6)
  const day = dateStr.substring(6, 8)
  return `${year}.${month}.${day}`
}

// 显示帮助信息
const showHelpInfo = () => {
  showHelpModal.value = true
}

// 关闭遮罩层
const closeModal = () => {
  showHelpModal.value = false
  showDetailModal.value = false
  selectedReport.value = null
  dailyTargets.value = []
}

// 组件挂载时获取数据
onMounted(async () => {
  // 先获取政策数据，再获取工作报告
  await fetchPolicyData()
  await fetchWorkReports(getUserId())
})
</script>

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

.closeBt {
  position: absolute;
  right: 10px;
  color: black;

  display: flex;
  align-items: center;
  justify-content: center;
}

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

.time-value {
  color: #2fff3d;
}

.history-salary {
  font-family: -apple-system, BlinkMacSystemFont, sans-serif;
}

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

/* Host Salary 卡片 */
.host-salary-card {
  background-color: white;
  padding: 20px;
  border-radius: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.salary-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.salary-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 500;
  color: #666;
}

.info-btn {
  width: 16px;
  aspect-ratio: 1/1;
  transition: all 0.2s;
}

.info-btn:active {
  background-color: #7c3aed;
  border-color: #7c3aed;
}

.salary-amount {
  font-size: 32px;
  font-weight: 700;
  color: #333;
  margin: 0;
}

/* 加载状态 */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 40px 20px;
  color: #666;
}

.loading-spinner {
  width: 32px;
  height: 32px;
  border: 3px solid #f3f3f3;
  border-top: 3px solid #8b5cf6;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 12px;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

/* 空数据状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 40px 20px;
  color: #666;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 12px;
}

/* 报告项目 */
.report-item {
  background-color: white;
  padding: 16px;
  border-radius: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.report-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.report-date {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.status-badge {
  padding: 6px 16px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 600;
  color: white;
}

.status-badge.in-progress {
  background-color: #3b82f6;
}

.status-badge.pending {
  background-color: #ef4444;
}

.status-badge.completed {
  background-color: #10b981;
}

.status-badge.out-of-account {
  background-color: #9ca3af;
}

/* 报告详情 */
.report-details {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.detail-row {
  display: flex;
  justify-content: space-between;
  gap: 20px;
}

.detail-item {
  flex: 1;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.detail-label {
  font-size: 14px;
  color: #666;
  font-weight: 500;
}

.detail-value {
  font-size: 14px;
  color: #333;
  font-weight: 600;
}

.total-salary {
  color: #10b981 !important;
  font-weight: 700;
}

/* More 按钮 */
.more-btn {
  display: flex;
  align-items: center;
  gap: 4px;
  background: none;
  border: none;
  color: #8b5cf6;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: color 0.2s;
}

.more-btn:hover {
  color: #7c3aed;
}

.arrow {
  font-weight: bold;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #666;
  padding: 0;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 等级卡片样式 */

.level-header {
  margin-bottom: 12px;
}

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

.text-700 {
  font-weight: 700;
}

.help-modal-body {
  padding: 0 20px 20px;
  overflow-y: auto;
}

.help-section {
  margin-bottom: 20px;
}

.help-section:last-child {
  margin-bottom: 0;
}

.help-description {
  font-size: 14px;
  line-height: 1.5;
  color: #555;
  margin: 0;
  padding: 12px;
  background-color: #f0f9ff;
  border-radius: 8px;
  border-left: 4px solid #3b82f6;
}

.help-section h4 {
  margin: 0 0 12px 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.status-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.status-item {
  display: flex;
  gap: 8px;
  padding: 12px;
  background-color: #f9fafb;
  border-radius: 8px;
  border: 1px solid #e5e7eb;
}

.status-number {
  font-weight: 600;
  color: #8b5cf6;
  flex-shrink: 0;
}

.status-name {
  font-weight: 600;
  color: #333;
  flex-shrink: 0;
  min-width: 100px;
}

.status-desc {
  color: #666;
  line-height: 1.4;
  flex: 1;
}

/* 弹窗样式 */
.modal-overlay {
  position: fixed;
  inset: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-item {
  display: flex;
  align-items: center;
  justify-content: center;
}

.modal {
  background: white;
  padding: 24px;
  border-radius: 16px;
  width: 100%;
  max-width: 320px;
}

.modal h3 {
  margin: 0 0 20px 0;
  font-size: 18px;
  text-align: center;
  color: #333;
}

.salary-breakdown {
  margin-bottom: 20px;
}

.breakdown-item {
  display: flex;
  justify-content: space-between;
  padding: 8px 0;
  font-size: 14px;
  color: #666;
  border-bottom: 1px solid #f0f0f0;
}

.breakdown-total {
  display: flex;
  justify-content: space-between;
  padding: 12px 0 8px 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
  border-top: 2px solid #e0e0e0;
  margin-top: 8px;
}

.modal button {
  width: 100%;
  padding: 12px;
  background-color: #3b82f6;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
}

.modal button:active {
  background-color: #2563eb;
}

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

/* RTL支持 */
[dir='rtl'] .info-btn {
  /* transform: scaleX(-1); */
}

[dir='rtl'] .closeBt {
  left: 10px;
  right: auto;
}
</style>
