<script setup lang="ts">
import type { PhoneLocationStatus } from '@af-mobile-client-vue3/components/data/XOlMap/types'
import MessageNotification from '@af-mobile-client-vue3/components/core/MessageNotification/MessageNotification.vue'
import useSettingStore from '@af-mobile-client-vue3/stores/modules/setting'
import useUserStore from '@af-mobile-client-vue3/stores/modules/user'
import { openDrivingConfigPopup } from '@af-mobile-client-vue3/utils/driving/drivingUtils'
import { mobileUtil } from '@af-mobile-client-vue3/utils/mobileUtil'
import { Dialog as vanDialog, Icon as vanIcon, Sticky as VanSticky, Switch as VanSwitch,
} from 'vant'
import { onMounted, onUnmounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import ModifyPassword from './comm/ModifyPassword.vue'

const setting = useSettingStore()
const router = useRouter()
const username = useUserStore().getUserInfo().name
const fullnames = useUserStore().getLogin().f.resources.fullnames
const roleName = useUserStore().getLogin().f.resources.f_role_name
const userInfo = useUserStore().getUserInfo()

// 修改密码弹窗显示状态
const showModifyPassword = ref(false)
// 退出登录确认弹窗显示状态
const showLogoutConfirm = ref(false)
// 在setup函数中
let intervalId: number | null = null

// 定义一个变量来存储上一次的上传结果
const lastUploadResult = ref(null)

const showLocationTag = ref(false)
const locationText = ref({
  text: '需要定位人员',
  color: 'green',
})
// 安全获取上次实时上传结果（封装 try/catch，避免初始化失败）
// 安全获取上次实时上传结果
function fetchLastRealtimeUploadResult(): void {
  mobileUtil.execute({
    param: {},
    funcName: 'getLastRealtimeUploadResult',
    callbackFunc: (res?: PhoneLocationStatus) => {
      try {
        // console.warn('获取到的上次定位信息:', res)
        // console.warn('获取到的上次定位信息:', JSON.stringify(res))

        lastUploadResult.value = res ?? null

        if (!res) {
          locationText.value.color = 'red'
        }

        if (res.status === 'error') {
          locationText.value.color = 'red'
          console.error('获取到的上次定位信息错误', JSON.stringify(res))
        }

        locationText.value.color = 'green'
      }
      catch (err) {
        console.error('处理定位回调异常:', err)
        locationText.value.color = 'red'
      }
    },
  })
}

onMounted(() => {
  if (roleName?.includes('需要定位人员')) {
    mobileUtil.execute({
      param: {},
      funcName: 'getLastRealtimeUploadResult',
      callbackFunc: (res?: PhoneLocationStatus) => {
        // console.warn('res', res)
        // console.warn('res', JSON.stringify(res))
        if (!res) {
          showLocationTag.value = false
          console.error('获取到的上次定位信息错误', JSON.stringify(res))
          return
        }

        if (res.status === 'error' && res.msg === '手机端函数调用失败!!!') {
          console.error('获取到的上次定位信息错误', JSON.stringify(res))
          showLocationTag.value = false
          locationText.value.color = 'yellow'
          return
        }
        showLocationTag.value = true
        // 无论首次结果如何，都启动定时器持续获取
        intervalId = window.setInterval(() => {
          fetchLastRealtimeUploadResult()
        }, 10000)
      },
    })
  }

  // 进入页面时同步一次“系统声音”开关状态
  syncAudioPlayEnabled()
})

onUnmounted(() => {
  // 组件卸载时清除定时器
  if (intervalId) {
    clearInterval(intervalId)
    intervalId = null
  }
})
function exit_login() {
  showLogoutConfirm.value = true
}

function confirmLogout() {
  // 清理 定时强制人脸识别
  if (setting.getSetting()?.isFaceRecognition) {
    mobileUtil.execute({
      param: {},
      funcName: 'stopPeriodicFaceVerify',
      callbackFunc: () => {
      },
    })
  }
  useUserStore().logout()
  showLogoutConfirm.value = false
}

function cancelLogout() {
  showLogoutConfirm.value = false
}

function goToAttendance() {
  router.push('/user/attendance')
}

function openModifyPassword() {
  showModifyPassword.value = true
}

const webMobileConfig = useSettingStore().getSetting()

// ========= 系统声音开关 =========
const checked = ref(true)

function handleSystemSoundSwitchChange(nextChecked: boolean) {
  mobileUtil.execute({
    param: { enabled: nextChecked },
    funcName: 'setAudioPlayEnabled',
    callbackFunc: () => {},
  })
}

function syncAudioPlayEnabled() {
  mobileUtil.execute({
    param: {},
    funcName: 'getAudioPlayEnabled',
    callbackFunc: (res?: any) => {
      if (res.status === 'success') {
        checked.value = Boolean(res?.data?.enabled)
      }
      else {
        checked.value = true
      }
    },
  })
}
</script>

<template>
  <main class="my_main">
    <!-- 顶部导航栏 -->
    <VanSticky :offset-top="0">
      <nav class="header_nav">
        <div class="header_content">
          <h1 class="main_title">
            我的
          </h1>
          <!--        <div class="setting_section"> -->
          <!--          <van-icon name="setting-o" class="setting-icon" /> -->
          <!--        </div> -->
          <div class="action_section">
            <MessageNotification />
          </div>
        </div>
      </nav>
    </VanSticky>

    <!-- 主要内容区域 -->
    <div class="content">
      <!-- 用户信息卡片 -->
      <div class="user-card">
        <div class="user-info">
          <div class="avatar-wrap">
            <img alt="default-user-profile" class="avatar" src="../../../assets/common/default-user-profile.png">
            <div class="status-dot" />
          </div>
          <div class="user-detail">
            <h2 class="username">
              {{ username }}
              <span
                v-if="showLocationTag"
                class="upload-status-tag" :class="[locationText.color]"
              >
                {{ locationText.text }}
              </span>
            </h2>
            <p class="user-role">
              {{ fullnames }}
            </p>
          </div>
        </div>
      </div>

      <!-- 工作统计 -->
      <!-- <div class="stats-card">
        <div class="stats-grid">
          <div class="stat-item">
            <div class="stat-value">
              0
            </div>
            <div class="stat-label">
              待办任务
            </div>
          </div>
          <div class="stat-item">
            <div class="stat-value">
              0
            </div>
            <div class="stat-label">
              待办流程
            </div>
          </div>
          <div class="stat-item">
            <div class="stat-value">
              0
            </div>
            <div class="stat-label">
              新消息
            </div>
          </div>
        </div>
      </div> -->

      <!-- 功能列表 -->
      <div class="menu-card">
        <div class="menu-section">
          <h3 class="menu-title">
            系统功能
          </h3>
          <div class="menu-list">
            <div v-if="webMobileConfig?.isAttendance" class="menu-item" @click="goToAttendance">
              <div class="menu-item-content">
                <van-icon name="user-o" class="menu-icon" />
                <span class="menu-text">考勤管理</span>
              </div>
              <van-icon name="arrow" class="menu-arrow" />
            </div>
            <div class="menu-item" @click="openModifyPassword">
              <div class="menu-item-content">
                <van-icon name="lock" class="menu-icon" />
                <span class="menu-text">修改密码</span>
              </div>
              <van-icon name="arrow" class="menu-arrow" />
            </div>
            <div v-if="userInfo?.drivingInfo !== undefined && userInfo?.drivingInfo !== null" class="menu-item" @click="openDrivingConfigPopup">
              <div class="menu-item-content">
                <van-icon name="logistics" class="menu-icon" />
                <span class="menu-text">修改行驶方式</span>
              </div>
              <van-icon name="arrow" class="menu-arrow" />
            </div>
            <div class="menu-item">
              <div class="menu-item-content">
                <van-icon name="volume-o" class="menu-icon" />
                <span class="menu-text">系统声音</span>
              </div>
              <VanSwitch
                v-model="checked"
                size="22px"
                @update:model-value="handleSystemSoundSwitchChange"
              />
            </div>
            <div class="menu-item" @click="exit_login">
              <div class="menu-item-content">
                <van-icon name="sign" class="menu-icon logout-icon" />
                <span class="menu-text">退出登录</span>
              </div>
              <van-icon name="arrow" class="menu-arrow" />
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 修改密码弹窗 -->
    <ModifyPassword
      v-model:visible="showModifyPassword"
    />

    <!-- 退出登录确认弹窗 -->
    <van-dialog
      v-model:show="showLogoutConfirm"
      title="确认退出"
      message="确定要退出登录吗？"
      show-cancel-button
      confirm-button-text="确认退出"
      cancel-button-text="取消"
      @confirm="confirmLogout"
      @cancel="cancelLogout"
    />
  </main>
</template>

<style scoped lang="less">
.my_main {
  background-color: #f7f8fa;

  // 顶部导航栏
  .header_nav {
    background-color: #fff;
    padding: 0 16px;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
    position: relative;
    z-index: 50;

    .header_content {
      display: flex;
      justify-content: space-between;
      align-items: center;
      height: 56px;

      .main_title {
        font-size: 1.25rem;
        font-weight: 600;
        color: #333;
        margin: 0;
      }

      .setting_section {
        padding: 8px;
        cursor: pointer;

        .setting-icon {
          font-size: 20px;
          color: #666;
        }
      }
    }
  }

  .content {
    padding: 16px;

    // 用户信息卡片
    .user-card {
      background-color: #fff;
      border-radius: 8px;
      padding: 16px;
      margin-bottom: 16px;

      .user-info {
        display: flex;
        align-items: center;

        .avatar-wrap {
          position: relative;
          margin-right: 16px;

          .avatar {
            width: 80px;
            height: 80px;
            border-radius: 50%;
            object-fit: cover;
          }

          .status-dot {
            position: absolute;
            bottom: 2px;
            right: 2px;
            width: 16px;
            height: 16px;
            border-radius: 50%;
            background-color: #10b981;
            border: 2px solid #fff;
          }
        }

        .user-detail {
          .username {
            font-size: 20px;
            font-weight: 600;
            color: #333;
            margin: 0 0 4px 0;
            display: flex;
            align-items: center;
          }
          .upload-status-tag {
            display: inline-block;
            margin-left: 8px;
            padding: 2px 8px;
            border-radius: 8px;
            font-size: 12px;
            font-weight: 400;
            background: #f0f0f0;
            &.green {
              color: #10b981;
              background: #e6f9f0;
              border: 1px solid #10b981;
            }
            &.red {
              color: #ef4444;
              background: #fdeaea;
              border: 1px solid #ef4444;
            }
            &.yellow {
              color: #f59e0b;
              background: #fffbeb;
              border: 1px solid #f59e0b;
            }
          }

          .user-role {
            font-size: 14px;
            color: #666;
            margin: 0;
          }
        }
      }
    }

    // 工作统计卡片
    .stats-card {
      background-color: #fff;
      border-radius: 8px;
      padding: 16px;
      margin-bottom: 16px;

      .stats-grid {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        gap: 16px;
        text-align: center;

        .stat-item {
          .stat-value {
            font-size: 24px;
            font-weight: 600;
            color: #3b82f6;
            margin-bottom: 4px;
          }

          .stat-label {
            font-size: 14px;
            color: #666;
          }
        }
      }
    }

    // 功能列表卡片
    .menu-card {
      background-color: #fff;
      border-radius: 8px;
      overflow: hidden;

      .menu-section {
        padding: 16px;

        .menu-title {
          font-size: 14px;
          font-weight: 500;
          color: #666;
          margin-bottom: 12px;
        }

        .menu-list {
          .menu-item {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 12px;
            background-color: #f7f8fa;
            border-radius: 8px;
            margin-bottom: 8px;
            cursor: pointer;

            &:last-child {
              margin-bottom: 0;
            }

            .menu-item-content {
              display: flex;
              align-items: center;
              gap: 12px;

              .menu-icon {
                font-size: 24px;
                color: #3b82f6;

                &.logout-icon {
                  color: #ef4444;
                }
              }

              .menu-text {
                font-size: 16px;
                color: #333;
              }
            }

            .menu-arrow {
              color: #999;
              font-size: 16px;
            }
          }
        }
      }
    }
  }
  .action_section {
    display: flex;
    align-items: center;
  }
}
</style>
