<template>
  <div class="wrap">
    <div class="content">
      <!-- 头部统计 -->
      <div class="list-header">
        <view class="header-info">
          <text class="header-title">待办事项(<text class="header-count">{{ itemList.length }}</text>)</text>
        </view>
        <view class="refresh-btn" @tap="onRefresh" :class="{ 'is-loading': isRefreshing }">
          <u-icon name="reload" color="#333" size="20"></u-icon>
        </view>
      </div>

      <!-- 加载中 -->
      <div class="loading-box" v-if="status === -1 && isGet">
        <u-loading mode="circle" size="32"></u-loading>
        <p class="loading-text">正在加载...</p>
      </div>

      <!-- 空状态 -->
      <div class="empty-box" v-if="status === 0">
        <view class="empty-illustration">
          <view class="empty-circle"></view>
          <view class="empty-icon">📋</view>
        </view>
        <p class="empty-title">暂无待办事项</p>
        <p class="empty-desc">所有任务已处理完毕</p>
      </div>

      <!-- 列表 -->
      <div class="list" v-if="status === 1">
        <div
          class="list-item"
          :class="'type-' + getTypeIndex(item.MenuName)"
          v-for="(item, index) in itemList"
          :key="index"
          @click="gotoConfirm"
          :data-menuid="item.MenuId"
          :data-id="item.DataId"
          :data-name="item.MenuName"
          :data-model="item"
          :data-url="item.UrlStr"
          :style="{ animationDelay: (index * 0.05) + 's' }"
        >
          <!-- 左侧彩色指示条 -->
          <view class="item-indicator"></view>

          <!-- 卡片内容 -->
          <view class="item-content">
            <!-- 类型图标 + 标题 + 状态 -->
            <view class="item-header">
              <view class="item-header-center">
                <text class="card-title">{{ item.MenuName }}</text>
                <text class="item-time-compact">{{ formatTimeCompact(item.DataTimeStr) }}</text>
              </view>
            </view>

            <!-- 内容摘要 -->
            <view class="item-content-text">{{ item.Content || '--' }}</view>

            <!-- 底部操作 -->
            <view class="item-footer">
              <view class="item-meta">
                <text class="meta-icon">🕐</text>
                <text class="meta-value">{{ item.DataTimeStr || '--' }}</text>
              </view>
              <view class="item-action">
                <text class="action-text">处理</text>
                <text class="action-arrow">→</text>
              </view>
            </view>
          </view>
        </div>

        <!-- 加载中提示 -->
        <div class="load-more" v-if="isGet">
          <u-loading mode="circle" size="24"></u-loading>
          <span class="load-more-text">加载中...</span>
        </div>

        <!-- 无更多 -->
        <div class="no-more" v-if="isFininsh && !isGet">— 没有更多了 —</div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { onShow, onReachBottom } from '@dcloudio/uni-app'
import { storeToRefs } from 'pinia'
import { useUserStore } from '@/store'

const userStore = useUserStore()
const { userInfo, currentProject } = storeToRefs(userStore)

const status = ref(-1)
const isFininsh = ref(false)
const pageIndex = ref(1)
const pageSize = 10
const isGet = ref(false)
const isRefreshing = ref(false)
const itemList = ref([])

// 类型序号（用于指示条颜色）
const typeIndexMap = {
  '安全确认': 1, '安全检查': 1,
  '动火作业': 2,
  '考试计划': 3,
  '技术交底': 4,
  '质量验收': 5,
  '进度确认': 6,
  '材料进场': 7,
  '应急预案': 8,
  '会议通知': 9,
}
function getTypeIndex(name) {
  return typeIndexMap[name] || 0
}

// 格式化时间：今天显示 "今天 HH:mm"，其他显示 MM-DD
function formatTimeCompact(str) {
  if (!str) return ''
  const today = new Date()
  const todayStr = today.getFullYear() + '-' + String(today.getMonth()+1).padStart(2,'0') + '-' + String(today.getDate()).padStart(2,'0')
  const datePart = str.split(' ')[0] || ''
  if (datePart === todayStr) return '今天 ' + (str.split(' ')[1] || '')
  return datePart.slice(5)
}

// 刷新
async function onRefresh() {
  if (isRefreshing.value) return
  isRefreshing.value = true
  pageIndex.value = 1
  isFininsh.value = false
  itemList.value = []
  await getList()
  isRefreshing.value = false
}

// ===== 模拟数据（开发调试用，上线前改为 false） =====
const USE_MOCK = true

const mockData = [
  {
    MenuId: 'M001',
    DataId: 'D001',
    MenuName: '安全确认',
    Content: '今日需要对3号楼脚手架搭设进行安全验收检查，确保符合规范要求',
    DataTimeStr: '2026-06-13 09:30',
    UrlStr: '/pages/grow/safe_confirm/main'
  },
  {
    MenuId: 'M002',
    DataId: 'D002',
    MenuName: '动火作业',
    Content: '1号楼地下室管道焊接动火申请，需确认消防设施配备齐全',
    DataTimeStr: '2026-06-13 10:15',
    UrlStr: '/pages/job_info/dh_approval/main'
  },
  {
    MenuId: 'M003',
    DataId: 'D003',
    MenuName: '考试计划',
    Content: '本月特种作业人员安全资格考试安排，请相关人员准时参加',
    DataTimeStr: '2026-06-12 14:00',
    UrlStr: '/pages/train_task/test_list/main'
  },
  {
    MenuId: 'M004',
    DataId: 'D004',
    MenuName: '安全检查',
    Content: '现场临时用电安全检查，重点排查配电箱接地保护和漏保动作电流',
    DataTimeStr: '2026-06-12 11:20',
    UrlStr: '/pages/grow/safe_confirm/main'
  },
  {
    MenuId: 'M005',
    DataId: 'D005',
    MenuName: '技术交底',
    Content: '基础底板大体积混凝土浇筑技术交底，注意温控措施和养护方案',
    DataTimeStr: '2026-06-11 16:45',
    UrlStr: '/pages/grow/safe_confirm/main'
  },
  {
    MenuId: 'M006',
    DataId: 'D006',
    MenuName: '质量验收',
    Content: '2号楼三层梁板钢筋隐蔽验收，检查钢筋规格、间距和锚固长度',
    DataTimeStr: '2026-06-11 15:30',
    UrlStr: '/pages/grow/safe_confirm/main'
  },
  {
    MenuId: 'M007',
    DataId: 'D007',
    MenuName: '进度确认',
    Content: '本月施工进度计划确认，包括主体结构、装饰装修和机电安装',
    DataTimeStr: '2026-06-11 09:00',
    UrlStr: '/pages/grow/safe_confirm/main'
  },
  {
    MenuId: 'M008',
    DataId: 'D008',
    MenuName: '材料进场',
    Content: 'HRB400E螺纹钢20mm进场验收，需核对材质证明和复试报告',
    DataTimeStr: '2026-06-10 13:20',
    UrlStr: '/pages/grow/safe_confirm/main'
  },
  {
    MenuId: 'M009',
    DataId: 'D009',
    MenuName: '应急预案',
    Content: '汛期防汛应急演练方案审批，请相关负责人审阅确认',
    DataTimeStr: '2026-06-10 10:50',
    UrlStr: '/pages/grow/safe_confirm/main'
  },
  {
    MenuId: 'M010',
    DataId: 'D010',
    MenuName: '会议通知',
    Content: '本周三下午3点召开项目周例会，请各部门负责人准时参会',
    DataTimeStr: '2026-06-10 08:30',
    UrlStr: '/pages/grow/safe_confirm/main'
  }
]
// ================================================

// 获取列表
async function getList() {
  if (isGet.value) return
  isGet.value = true
  try {
    let list = []

    if (USE_MOCK) {
      // 模拟网络延迟
      await new Promise(r => setTimeout(r, 600))
      const start = (pageIndex.value - 1) * pageSize
      const end = start + pageSize
      list = mockData.slice(start, end)
    } else {
      const UserId = userInfo.value?.PersonId || uni.getStorageSync('UserId') || ''
      const res = await reqToDoItemByProjectIdUserId(currentProject.value?.ProjectId, UserId)
      list = res?.data?.getDataList || []
    }

    if (pageIndex.value === 1 && list.length === 0) {
      status.value = 0
      isGet.value = false
      return
    }

    itemList.value = itemList.value.concat(list)
    status.value = 1
    pageIndex.value++
    isFininsh.value = list.length < pageSize
  } catch (e) {
    console.error('获取待办列表失败', e)
    status.value = 0
  }
  isGet.value = false
}

// 点击列表项 → 直接跳转
function gotoConfirm(e) {
  const dataset = e.mp?.currentTarget?.dataset || {}
  const { id, url, menuid } = dataset
  if (!url) return
  uni.navigateTo({ url: `${url}?id=${id}&menuId=${menuid}` })
}

// 页面生命周期
onShow(() => {
  status.value = -1
  isFininsh.value = false
  itemList.value = []
  pageIndex.value = 1
  isGet.value = false
  getList()
})

onReachBottom(() => {
  if (isFininsh.value) return
  getList()
})

onMounted(() => {
  console.log('safeid', currentProject.value)
  // onShow 可能未触发时兜底加载
  getList()
})
</script>

<style lang="scss">
page {
  background-color: #f5f6f8;
}
</style>

<style scoped lang="scss">
.wrap {
  min-height: 100vh;
  padding-bottom: 180rpx;
  background: #f5f6f8;
}

/* ========== 头部统计 ========== */
.list-header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 99;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 32rpx;
  height: 96rpx;
  background: #fff;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);

  .header-info {
    .header-title {
      font-size: 30rpx;
      font-weight: 600;
      color: #333;

      .header-count {
        color: #3577ff;
        font-weight: 700;
        font-size: 28rpx;
      }
    }
  }

  .refresh-btn {
    width: 64rpx;
    height: 64rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #f5f6f8;
    border-radius: 50%;

    &.is-loading {
      animation: rotate 0.8s linear infinite;
    }
  }
}

/* ========== 列表容器 ========== */
.list {
  padding: 24rpx 24rpx 40rpx;
  padding-top: 130rpx; // 固定头部高度
}

/* ========== 列表项卡片 ========== */
.list-item {
  position: relative;
  background: #fff;
  border-radius: 20rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
  overflow: hidden;
  transition: all 0.2s ease;
  animation: card-in 0.4s ease both;

  &:active {
    transform: scale(0.97);
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  }

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

/* 左侧彩色指示条 */
.item-indicator {
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 8rpx;
  background: linear-gradient(180deg, #3577ff 0%, #6366f1 100%);
}

.type-1 .item-indicator { background: linear-gradient(180deg, #ff4d4f 0%, #ff7a45 100%); }
.type-2 .item-indicator { background: linear-gradient(180deg, #ff4d4f 0%, #ff7a45 100%); }
.type-3 .item-indicator { background: linear-gradient(180deg, #3577ff 0%, #6366f1 100%); }
.type-4 .item-indicator { background: linear-gradient(180deg, #13c2c2 0%, #36cfc9 100%); }
.type-5 .item-indicator { background: linear-gradient(180deg, #52c41a 0%, #73d13d 100%); }
.type-6 .item-indicator { background: linear-gradient(180deg, #fa8c16 0%, #ffc53d 100%); }
.type-7 .item-indicator { background: linear-gradient(180deg, #722ed1 0%, #9254de 100%); }
.type-8 .item-indicator { background: linear-gradient(180deg, #eb2f96 0%, #f759ab 100%); }
.type-9 .item-indicator { background: linear-gradient(180deg, #1890ff 0%, #40a9ff 100%); }
.type-0 .item-indicator { background: linear-gradient(180deg, #999 0%, #bbb 100%); }

/* 卡片内容区 */
.item-content {
  padding: 28rpx 28rpx 28rpx 36rpx;
}

/* 头部：图标 + 标题 + 状态 */
.item-header {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;

  .item-header-center {
    flex: 1;
    min-width: 0;
    display: flex;
    flex-direction: column;

    .card-title {
      font-size: 30rpx;
      font-weight: 600;
      color: #333;
      margin-bottom: 4rpx;
    }

    .item-time-compact {
      font-size: 22rpx;
      color: #999;
    }
  }

  .card-status {
    font-size: 22rpx;
    padding: 6rpx 16rpx;
    border-radius: 20rpx;
    font-weight: 500;
    flex-shrink: 0;

    &.pending {
      background: rgba(255, 167, 38, 0.1);
      color: #ffa726;
    }
  }
}

/* 内容摘要 */
.item-content-text {
  font-size: 26rpx;
  color: #666;
  line-height: 1.7;
  margin-bottom: 20rpx;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 底部操作区 */
.item-footer {
  display: flex;
  align-items: center;
  justify-content: space-between;

  .item-meta {
    display: flex;
    align-items: center;

    .meta-icon {
      font-size: 24rpx;
      margin-right: 8rpx;
    }

    .meta-value {
      font-size: 24rpx;
      color: #999;
    }
  }

  .item-action {
    display: flex;
    align-items: center;
    padding: 10rpx 24rpx;
    background: linear-gradient(135deg, #3577ff 0%, #6366f1 100%);
    border-radius: 24rpx;

    .action-text {
      font-size: 24rpx;
      color: #fff;
      font-weight: 500;
      margin-right: 6rpx;
    }

    .action-arrow {
      font-size: 26rpx;
      color: #fff;
    }
  }
}

/* ========== 加载中 ========== */
.loading-box {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 200rpx 0;

  .loading-text {
    margin-top: 24rpx;
    font-size: 26rpx;
    color: #999;
  }
}

.load-more {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 32rpx 0;

  .load-more-text {
    margin-left: 16rpx;
    font-size: 24rpx;
    color: #999;
  }
}

/* ========== 空状态 ========== */
.empty-box {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 200rpx 0;

  .empty-illustration {
    position: relative;
    width: 200rpx;
    height: 200rpx;
    margin-bottom: 48rpx;

    .empty-circle {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      border-radius: 50%;
      background: linear-gradient(135deg, rgba(53, 119, 255, 0.08), rgba(99, 102, 241, 0.08));
    }

    .empty-icon {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      font-size: 80rpx;
    }
  }

  .empty-title {
    font-size: 30rpx;
    font-weight: 500;
    color: #333;
    margin-bottom: 12rpx;
  }

  .empty-desc {
    font-size: 24rpx;
    color: #999;
  }
}

/* ========== 无更多 ========== */
.no-more {
  text-align: center;
  padding: 40rpx 0;
  font-size: 24rpx;
  color: #ccc;
}

/* ========== 卡片入场动画 ========== */
@keyframes card-in {
  from {
    opacity: 0;
    transform: translateY(20rpx);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* ========== 旋转动画 ========== */
@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}
</style>
