<template>
  <div class="host-center gradient-background-circles">
    <!-- 顶部导航 -->
    <GeneralHeader
      :isHomePage="true"
      :showLanguageList="true"
      :title="t('host_center')"
      color="black"
      style="box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); z-index: 999"
    />

    <!-- 主要内容 -->
    <div style="padding: 16px; position: relative; z-index: 2">
      <!-- 身份 -->
      <div class="section-title">
        {{ t('my_account') }}
        <img src="../../assets/icon/identity/host.png" alt="" class="title-icon" />
      </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"
              style="width: 100%; height: 100%; object-fit: cover; border-radius: 25px"
              @error="handleImageError"
            />
            <span v-else style="color: white; font-size: 20px; font-weight: 600">{{
              getAvatarPlaceholder()
            }}</span>
          </div>

          <!-- 信息 -->
          <div class="user-info">
            <div
              style="
                margin: 0 0 4px 0;
                font-weight: 600;
                color: #333;
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
                width: 100%;
              "
            >
              {{ userInfo.userNickname || userInfo.name }}
            </div>
            <div style="margin: 0; font-size: 0.9em; color: #666">
              {{ t('user_id_prefix') }} {{ userInfo.id }}
            </div>
          </div>

          <!-- 跳转按钮 -->
          <button
            style="
              width: 1.5em;
              border: none;
              background: none;

              display: flex;
              justify-content: center;
              align-items: center;
            "
            @click="goToNotification"
          >
            <img
              v-smart-img
              src="../../assets/icon/Aslan/edit.png"
              alt=""
              style="display: block; width: 70%; object-fit: contain"
            />
          </button>
        </div>

        <!-- 我的薪资 -->
        <div style="margin-bottom: 10px">
          <div style="display: flex; justify-content: space-between; margin-bottom: 5px">
            <div style="font-weight: 600">{{ t('my_salary') }}</div>
            <button
              style="
                font-weight: 500;
                color: rgba(0, 0, 0, 0.4);
                border: 0;
                background-color: transparent;
                cursor: pointer;
              "
              @click="showDatePicker"
            >
              {{ t('personal_salary') }} >
            </button>
          </div>
        </div>

        <!-- 历史薪资 -->
        <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 10px">
          <div class="salary-item">
            <div class="salary-label">{{ t('history_salary') }}</div>
            <div class="salary-value">${{ historySalary.toFixed(2) }}</div>
          </div>
          <div class="salary-item">
            <div class="salary-label">{{ t('current_salary') }}</div>
            <div class="salary-value">${{ 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; margin-bottom: 10px">
          <div style="font-weight: 600">{{ t('todays_task') }}</div>
          <button
            style="
              font-weight: 500;
              color: rgba(0, 0, 0, 0.4);
              border: 0;
              background-color: transparent;
              cursor: pointer;
            "
            @click="goToPlatformPolicy"
          >
            {{ t('platform_policy') }} >
          </button>
        </div>
        <div style="display: flex; justify-content: space-between">
          <div class="task-item">
            <div class="task-label">{{ t('host_type') }}</div>
            <div class="task-value">{{ taskInfo.anchorType }}</div>
          </div>
          <div class="task-item">
            <div class="task-label">{{ t('minutes') }}</div>
            <div class="task-value">{{ taskInfo.minutesProgress }}/{{ taskInfo.minutesTotal }}</div>
          </div>
          <div class="task-item">
            <div class="task-label">{{ t('gift_task') }}</div>
            <div class="task-value">{{ taskInfo.giftTask }}</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 style="display: flex; align-items: center; gap: 2vw; margin: 0 1%">
        <!-- 兑换按钮 -->
        <button
          class="action-btn"
          style="background: linear-gradient(135deg, #f1eca6 2.82%, #ffd22f 99.15%), #fff"
          @click="exchangeGoldCoins"
        >
          {{ t('exchange') }}
        </button>

        <!-- 转账按钮 -->
        <button
          class="action-btn"
          style="background: linear-gradient(135deg, #a6aaf1 2.82%, #592fff 99.15%), #fff"
          @click="goToTransfer"
        >
          {{ t('transfer') }}
        </button>

        <!-- 提现按钮 -->
        <button
          v-if="withdrawEnabled"
          class="action-btn"
          style="background: linear-gradient(135deg, #a6f1b2 2.82%, #2fff3d 99.15%), #fff"
          @click="goToWithdraw"
        >
          {{ t('withdraw') }}
        </button>
      </div>
    </div>

    <!-- 弹窗遮罩层 -->
    <maskLayer :maskLayerShow="maskLayerShow" @click="maskLayerShow = false">
      <!-- 资料不足提示弹窗 -->
      <div
        style="
          width: 100vw;
          height: 100vh;
          display: flex;
          justify-content: center;
          align-items: center;
        "
        @click="maskLayerShow = false"
      >
        <div
          style="
            width: 80%;
            border-radius: 12px;
            background: #fff;
            padding: 12px;
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 2vw;
          "
          @click.stop
        >
          <div style="color: rgba(0, 0, 0, 0.8); font-weight: 700; font-size: 1.2em">
            {{ t('prompt') }}
          </div>
          <div style="color: rgba(0, 0, 0, 0.8); font-weight: 600">
            {{ t('fill_info_tips') }}
          </div>
          <div style="color: rgba(0, 0, 0, 0.4); font-weight: 600; font-size: 0.8em">
            {{ t('card_issue_tips') }}
          </div>
          <div
            style="
              display: flex;
              justify-content: center;
              align-items: center;
              border-radius: 999999px;
              background:
                linear-gradient(180deg, #d3acff 0%, rgba(222, 172, 255, 0) 58.38%),
                linear-gradient(152deg, #c670ff 7.01%, #7726ff 92.99%), #ff4768;
              box-shadow:
                -1px 0 5px 0 rgba(255, 255, 255, 0.7) inset,
                -3.5px 0 7.5px 0 rgba(255, 255, 255, 0.2) inset,
                1px 0 5px 0 rgba(255, 255, 255, 0.7) inset,
                3.5px 0 7.5px 0 rgba(255, 255, 255, 0.2) inset;

              color: #fff;
              font-weight: 800;
              padding: 8px 12px;
              width: 50%;
            "
            @click="goToImprove"
          >
            {{ t('to_improve') }}
          </div>
        </div>
      </div>
    </maskLayer>
  </div>
</template>

<script setup>
import { computed, onMounted, reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { setDocumentDirection } from '@/locales/i18n'
import { usePageInitializationWithConfig } from '@/utils/pageConfig.js'
import { getUserId } from '@/utils/userStore.js'
import { clearSelectedPayee } from '@/utils/payeeStore.js'
import { useIdentityStore } from '@/stores/identity.js'

import { getTeamMemberWork } from '@/api/teamBill.js'
import {
  getUserIdentity, // 获取用户身份
  getBankBalance, // 获取余额
  getBankCardList, // 获取正在使用的银行卡
  getWithdrawInfoList, // 获取申请提现信息
  useBankCard, // 设置默认银行卡
  withdrawApply, //提现
  apiGetWithdrawEnabled, // 获取提现权限
} from '@/api/wallet.js'

import GeneralHeader from '@/components/GeneralHeader.vue'
import workReportBox from '@/components/workReportBox.vue'
import maskLayer from '@/components/MaskLayer.vue'

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

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

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

const loadingProgressInfo = reactive({ value: false })

const historySalary = ref(0)

const bankCardList = ref([]) // 银行卡列表
const usedBankCard = ref(null) //正在使用的银行卡

const bankCardInfo = ref(null)
const checkStatus = computed(() => {
  return bankCardInfo.value == null || usedBankCard.value == null
})

const withdrawEnabled = ref(false) // 提现权限
const maskLayerShow = ref(false) // 弹窗遮罩层显示状态

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

// 前往历史薪资
const showDatePicker = () => {
  router.push('/history-salary')
}

// 前往政策
const goToPlatformPolicy = () => {
  router.push('/platform-policy?from=hostcenter')
}

// 前往主播设置
const goToNotification = () => {
  router.push('/host-setting')
}

// 前往金币兑换
const exchangeGoldCoins = () => {
  router.push('/exchange-gold-coins')
}

// 前往转账
const goToTransfer = () => {
  router.push('/transfer')
}

// 前往提现
const goToWithdraw = () => {
  if (checkStatus.value) {
    maskLayerShow.value = true
    return
  }
  router.push('/cash-withdraw')
}

// 前往完善信息
const goToImprove = () => {
  router.push('/host-setting')
}

// 获取成员工作数据
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

      historySalary.value = data.historySalary

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

        // 格式化状态
        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 || '–'

        const userIdentity = await getUserIdentity()

        // 更新数据
        Object.assign(progressInfo, {
          date: latestTarget.billTitle,
          status: formatStatus(latestTarget.status),
          target: level,
          salary:
            formatSalaryValue(
              userIdentity.body?.agent
                ? (latestTarget.target?.settlementResult?.ownSalary || 0) +
                    (latestTarget.target?.settlementResult?.memberSalary || 0)
                : userIdentity.body?.anchor
                  ? latestTarget.target?.settlementResult?.memberSalary
                  : null,
            ) || '-',
          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 getBankCards = async () => {
  try {
    const resBankCards = await getBankCardList()
    console.log('银行卡列表:', resBankCards)
    if (resBankCards.status && resBankCards.body) {
      // 处理银行卡列表数据
      bankCardList.value = resBankCards.body

      const usedCard = bankCardList.value.find((card) => card.use)
      if (usedCard) {
        usedBankCard.value = usedCard
      } else {
        // 没有使用中的银行卡
        usedBankCard.value = null
      }
    }
  } catch (error) {
    console.error('获取银行卡列表失败:', error)
  }
}

// 获取提现信息列表
const getWithdrawInfoListData = async () => {
  try {
    const resWithdrawInfoList = await getWithdrawInfoList()
    console.log('提现信息列表:', resWithdrawInfoList)
    if (resWithdrawInfoList.status && resWithdrawInfoList.body?.length > 0) {
      let imgList = JSON.parse(resWithdrawInfoList.body[0].passportFrontUrl)
      let previewUrls = imgList.map((item) => item)
      bankCardInfo.value = { previewUrls, ...resWithdrawInfoList.body[0] }
    }
  } catch (error) {
    console.error('获取提现信息列表失败:', error)
    showError(error.response?.errorMsg)
  }
}

// 获取提现权限
const getWithdrawEnabled = async () => {
  try {
    const resWithdrawEnabled = await apiGetWithdrawEnabled()
    if (resWithdrawEnabled.body && resWithdrawEnabled.status) {
      withdrawEnabled.value = resWithdrawEnabled.body
    }
  } catch (error) {
    console.error('获取提现信息列表失败:', error)
    showError(error.response?.errorMsg)
  }
}

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

onMounted(() => {
  identityStore.setIdentity('HOST')
  clearSelectedPayee() //清除选中的收款人
  getBankCards() // 获取正在使用的银行卡
  getWithdrawInfoListData() // 获取提现信息列表
  getWithdrawEnabled() // 获取提现权限
})
</script>

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

.host-center {
  width: 100vw;
  min-height: 100vh;
  background-color: #ffffff;
  background-image: url(../../assets/images/Aslan/secondBg.png);
}

.section-title {
  margin: 0 1%;
  margin-bottom: 12px;
  font-weight: 600;
  display: flex;
  align-items: center;
  font-size: 1.3em;
}

.title-icon {
  height: 20px;
  margin-left: 10px;
}

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

.user-info {
  flex: 1;
  min-width: 0;
}

.salary-item {
  display: flex;
  flex-direction: column;
}

.salary-label {
  font-weight: 500;
  color: rgba(0, 0, 0, 0.4);
  margin-bottom: 5px;
}

.salary-value {
  font-weight: 600;
}

.task-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  flex: 1;
}

.task-label {
  font-weight: 600;
  margin-bottom: 5px;
}

.task-value {
  font-weight: 600;
}

.action-btn {
  flex: 1;
  min-width: 0;

  border-radius: 4px;
  box-shadow: 0 0 4px 0 rgba(0, 0, 0, 0.25);
  color: white;

  height: 36px;
  border: none;
  font-size: 1em;
  font-weight: 600;
  text-align: center;
  line-height: 1.2;
  transition: all 0.2s;
  width: 100%;
  cursor: pointer;
}

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

@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'] .section-title {
  text-align: right;
}

[dir='rtl'] .avatar {
  margin-right: 0;
  margin-left: 12px;
}

[dir='rtl'] .title-icon {
  margin-left: 0;
  margin-right: 10px;
}

[dir='rtl'] .user-info {
  text-align: right;
}
</style>
