<template>
  <div class="mobile-home">
    <!-- 页面头部 -->
    <header class="home-header">
      <h2>服务申报</h2>
      <div class="user-info">
        <span>{{ userInfo.actualName }}</span>
        <button @click="handleLogout" class="logout-btn">退出</button>
      </div>
    </header>
    
    <!-- 主要内容 -->
    <div class="home-content">
      <!-- 新建申报按钮：非协会角色且非CEO角色显示（与PC端相同逻辑） -->
      <button v-if="!isAssociationRole && !isCeo" @click="handleCreate" class="create-btn">
        + 新建申报
      </button>
      
      <!-- 服务申报列表 -->
      <div class="service-section">
        <h3>服务申报列表</h3>
        
        <div v-if="loading" class="loading">
          加载中...
        </div>
        
        <div v-else class="service-list">
          <div v-for="item in serviceList" :key="item.applicationId" class="service-item" @click="viewDetail(item)">
            <div class="item-main">
              <div class="item-title">{{ item.activityName || '服务申报' }}</div>
              <div class="item-meta">
                <div class="item-duration">{{ item.serviceDuration }}小时</div>
                <div class="item-status" :class="getStatusClass(item.firmAuditStatus)">
                  {{ getStatusText(item.firmAuditStatus) }}
                </div>
              </div>
            </div>
            <div class="item-time">
              {{ formatTime(item.serviceStart) }}
            </div>
          </div>
          
          <div v-if="serviceList.length === 0" class="empty-state">
            <div class="empty-icon">📋</div>
            <div class="empty-text">暂无申报记录</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { loginApi } from '/@/api/system/login-api'
import { serviceApplicationsApi } from '/@/api/business/service-applications/service-applications-api'
import { message } from 'ant-design-vue'

const router = useRouter()
const userInfo = ref({})
const serviceList = ref([])
const loading = ref(false)

// 角色判断（与PC端相同逻辑）
const isCeo = ref(false)
const isAssociationRole = ref(false)

// 获取用户信息
async function getUserInfo() {
  try {
    const res = await loginApi.getLoginInfo()
    userInfo.value = res.data
    checkUserRole() // 获取登录信息后检查用户角色
  } catch (error) {
    console.error('获取用户信息失败:', error)
  }
}

// 检查用户角色（与PC端相同逻辑）
function checkUserRole() {
  if (userInfo.value) {
    // 使用roleCode字段进行角色判断
    const userRole = userInfo.value.roleCode || ''
    const roleLower = userRole.toLowerCase()
    
    // CEO角色判断（CEO不显示新建申报按钮）
    isCeo.value = roleLower === 'ceo'
    
    // 协会角色判断
    isAssociationRole.value = roleLower.includes('协会') || 
                             roleLower.includes('association') || 
                             roleLower.includes('律协') || 
                             roleLower.includes('律师协会') ||
                             roleLower.includes('admin_employee')
    
    console.log('用户角色:', userRole, '是CEO:', isCeo.value, '是协会角色:', isAssociationRole.value)
  }
}

// 获取服务申报列表
async function getServiceList() {
  loading.value = true
  try {
    const res = await serviceApplicationsApi.queryPage({
      pageNum: 1,
      pageSize: 10
    })
    
    if (res.code === 0) {
      // 根据PC端逻辑，返回的数据结构是 res.data.list
      serviceList.value = res.data.list || []
      console.log('获取到的申报列表:', serviceList.value)
    } else {
      message.error('获取申报列表失败')
    }
  } catch (error) {
    console.error('获取申报列表失败:', error)
    message.error('网络错误，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 新建申报
function handleCreate() {
  router.push('/mobile/service/create')
}

// 查看详情
function viewDetail(item) {
  console.log('查看申报详情:', item)
  
  // 判断状态：草稿状态（status=0）可以编辑，其他状态只能查看详情
  if (item.firmAuditStatus === 0) {
    // 草稿状态：跳转到编辑页面
    router.push(`/mobile/service/create?applicationId=${item.applicationId}`)
  } else {
    // 其他状态：跳转到详情页面
    router.push(`/mobile/service/detail?applicationId=${item.applicationId}`)
  }
}

// 退出登录
async function handleLogout() {
  try {
    // 调用后端退出接口
    await loginApi.logout()
  } catch (e) {
    console.error('退出登录接口调用失败:', e)
    // 即使接口调用失败，也要确保前端退出
  } finally {
    // 前端状态清理
    localStorage.removeItem('token')
    localStorage.removeItem('userInfo')
    router.push('/mobile/login')
  }
}

// 状态文本映射（与PC端保持一致）
function getStatusText(status) {
  const statusMap = {
    0: '未提交',
    1: '待审核', 
    2: '审核中',
    3: '已通过',
    4: '驳回'
  }
  return statusMap[status] || '未知状态'
}

// 状态样式类（与PC端保持一致）
function getStatusClass(status) {
  const classMap = {
    0: 'status-pending',
    1: 'status-approved',
    2: 'status-rejected',
    3: 'status-completed',
    4: 'status-draft'
  }
  return classMap[status] || 'status-unknown'
}

// 时间格式化
function formatTime(time) {
  if (!time) return ''
  return time.split(' ')[0] // 只显示日期部分
}

onMounted(() => {
  getUserInfo()
  getServiceList()
})
</script>

<style scoped>
.mobile-home {
  min-height: 100vh;
  background: #f5f5f5;
}

.home-header {
  position: sticky;
  top: 0;
  background: white;
  padding: 15px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: 1px solid #e8e8e8;
  z-index: 100;
}

.home-header h2 {
  font-size: 18px;
  color: #333;
  margin: 0;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 14px;
}

.logout-btn {
  padding: 6px 12px;
  background: #f5f5f5;
  color: #666;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 12px;
  cursor: pointer;
}

.home-content {
  padding: 15px;
}

.create-btn {
  width: 100%;
  padding: 15px;
  background: #1890ff;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  cursor: pointer;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.3);
}

.service-section {
  background: white;
  border-radius: 8px;
  padding: 15px;
  margin-top:10px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
  min-height:200px;
}

.service-section h3 {
  font-size: 16px;
  color: #333;
  margin: 0 0 15px 0;
  padding-bottom: 10px;
  border-bottom: 1px solid #f0f0f0;
}

.loading {
  text-align: center;
  padding: 20px;
  color: #666;
}

.service-item {
  padding: 15px 0;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  cursor: pointer;
}

.service-item:last-child {
  border-bottom: none;
}

.item-main {
  flex: 1;
}

.item-title {
  font-size: 16px;
  color: #333;
  margin-bottom: 5px;
  font-weight: 500;
}

.item-status {
  font-size: 12px;
  padding: 2px 8px;
  border-radius: 12px;
  display: inline-block;
}

.status-pending {
  background: #fff7e6;
  color: #fa8c16;
}

.status-approved {
  background: #f6ffed;
  color: #52c41a;
}

.status-rejected {
  background: #fff2f0;
  color: #ff4d4f;
}

.status-completed {
  background: #f0f5ff;
  color: #1890ff;
}

.status-draft {
  background: #f5f5f5;
  color: #666;
}

.item-meta {
  display: flex;
  align-items: center;
  gap: 10px;
}

.item-time {
  font-size: 12px;
  color: #999;
}

.item-arrow {
  color: #ccc;
  font-size: 14px;
}

.empty-state {
  text-align: center;
  padding: 40px 20px;
}

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

.empty-text {
  color: #666;
  margin-bottom: 20px;
}

.empty-btn {
  padding: 10px 20px;
  background: #1890ff;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
}

/* 移动端优化 */
@media (max-width: 768px) {
  .home-header {
    padding: 12px;
  }
  
  .home-content {
    padding: 12px;
  }
  
  .service-section {
    padding: 12px;
  }
  
  .service-item {
    padding: 12px 0;
  }
}
</style>