<route lang="json5" type="page">
{
  layout: 'default',
  type: 'home',
  style: {
    navigationBarTitleText: '首页',
    navigationStyle: 'custom',
    disableScroll: true,
    'app-plus': {
      bounce: 'none',
    },
  },
}
</route>

<template>
  <view class="home-container">
    <scroll-view class="scroll-view" scroll-y>
      <!-- 状态栏占位 -->
      <view class="status-bar-placeholder" :style="{ height: statusBarHeight + 'px' }"></view>

      <!-- 头部 -->
      <view class="header">
        <text class="header-title">广州特检院</text>
      </view>

      <!-- Tab 栏 -->
      <view class="tab-bar">
        <view class="tab-item tab-item-active">
          <text class="tab-item-text-active">检验检测</text>
        </view>
      </view>

      <!-- 待办事项标题 -->
      <view class="todo-title-box">
        <text class="todo-title">我的待办事项</text>
        <wd-picker
          style="z-index: 999;"
          class="equip-picker"
          :model-value="equipType"
          :columns="equipmentOptions"
          label-key="label"
          value-key="value"
          placeholder="请选择"
          @confirm="onEquipTypeChange"
        />
      </view>

      <!-- 待办卡片列表 -->
      <view class="todo-cards">
        <CardItem
          v-for="card in cardList"
          :key="card.id"
          :ref="(el: any) => (cardItemRef[card.id] = el)"
          :card="card"
          :user-id="userId"
          :width="windowWidth"
          @navigate="pushCard"
        />
      </view>

      <!-- 功能栏 -->
      <view class="home-section">
        <view class="section-header">
          <text class="todo-title">功能栏</text>
        </view>
        <view class="cap-section-content">
          <view
            v-for="cap in capabilityList"
            :key="cap.title"
            class="section-item"
            :style="{ backgroundColor: cap.backgroundColor }"
            @click="pushCard(cap)"
          >
            <view class="cap-info">
              <text class="cap-title">{{ cap.title }}</text>
              <text class="cap-desc">{{ cap.desc }}</text>
            </view>
            <image class="cap-section-image" :src="cap.iconUrl" mode="aspectFit" />
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 网络状态提示 -->
    <view v-if="!networkStatus" class="network-toast">
      <text class="network-toast-text">当前网络不可用</text>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue'
import { onShow, onLoad } from '@dcloudio/uni-app'
import { useUserStore } from '@/store/user'
import { useConfigStore } from '@/store/config'
import { EquipmentType } from '@/utils/dictMap'
import { getTaskOrder } from '@/api/task'
import iconMap from '@/utils/imagesMap'
import CardItem, { type CardObj } from './components/CardItem.vue'
import { requestFunc, IndexFuncName } from '@/api/ApiRouter/index'

defineOptions({
  name: 'home',
})

// 常量
const NUM = 2 // 一行多少个卡片
const SPACE = 15 // 卡片之间的间距
const PADDING = 20 // 左右边距

// 状态
const refresh = ref(false)
const userId = ref('')
const cardItemRef = reactive<Record<string, any>>({})
const windowWidth = ref(0)
const statusBarHeight = ref(20)
const networkStatus = ref(true)

const userStore = useUserStore()
const userInfo = computed(() => userStore.userInfo)

const configStore = useConfigStore()
const equipType = computed(() => configStore.getEquipType())

const equipmentOptions = [
  { label: '锅炉', value: EquipmentType.BOILER },
  { label: '管道', value: EquipmentType.PIPE },
  // { label: '压力容器', value: EquipmentType.CONTAINER },
]

onShow(() => {
  refreshAllCards()
})

const onEquipTypeChange = ({ value }: { value: string }) => {
  if (value && value !== equipType.value) {
    configStore.switchEquipType(value as any)
    uni.reLaunch({ url: '/pages/home/index' })
  }
}

// 获取屏幕宽度
const getWindowWidth = () => {
  const systemInfo = uni.getSystemInfoSync()
  windowWidth.value = systemInfo.windowWidth || 375
  statusBarHeight.value = systemInfo.statusBarHeight || 20
}

// 监听网络状态
const onNetworkStatusChange = (res: any) => {
  networkStatus.value = res.isConnected
}

// 检查网络状态
const checkNetworkStatus = () => {
  uni.getNetworkType({
    success: (res) => {
      networkStatus.value = res.networkType !== 'none'
    },
    fail: () => {
      networkStatus.value = false
    },
  })
}

// 防抖刷新函数
const refreshAllCards = () => {
  const currentUserInfo = userStore.userInfo
  if (currentUserInfo?.id) {
    console.log('🔄 Home 页面自动刷新任务状态')
    cardList.forEach((card) => {
      cardItemRef[card.id]?.getCount(currentUserInfo.id)
    })
  }
}
onMounted(() => {
  getWindowWidth()
  getUserId()
  checkNetworkStatus()

  // 监听网络状态变化
  uni.onNetworkStatusChange(onNetworkStatusChange)
})

onUnmounted(() => {
  uni.offNetworkStatusChange(onNetworkStatusChange)
})

// 获取用户 id
const getUserId = async () => {
  try {
    const res = await uni.getStorage({ key: 'USER_INFO' })
    if (res.data?.id) {
      userId.value = res.data.id
    } else if (userInfo.value?.id) {
      userId.value = userInfo.value.id
    }
  } catch (e) {
    console.error('获取用户信息失败', e)
  }
}

// 查询待认领数量
const getUnClaimNum = async () => {
  const params = {
    pageNo: 1,
    pageSize: 10,
    taskStatus: 100,
  }
  const result = await requestFunc(IndexFuncName.PreClaimNumberApi, equipType.value, params)
  const num = result?.data?.total
  return num || 0
}

// 查询本地待下载的任务
const queryLocalTask = async (userId: string) => {
  const getServer = async () => {
    const result = await getTaskOrder({ pageNo: 1, pageSize: 5 })
    return result?.data?.total || 0
  }

  // TODO: 需要实现本地数据库查询
  const getLocal = async () => {
    return 0
  }

  const result = await Promise.all([getServer(), getLocal()])
  const num = result[0] - result[1]
  return num || 0
}

// 获取待录入数量
const getUnEnterNum = async (userId: string) => {
  // TODO: 需要实现本地数据库查询
  return 0
}

// 获取分配项目数量
const getCheckerOwnTaskNum = async () => {
  const result = await requestFunc(IndexFuncName.TaskEquipNumberApi, equipType.value, {
    pageNo: 1,
    pageSize: 10,
    taskStatusList: [400, 500, 510],
    isClaim: false,
    planCheckUserIds: userInfo.value?.id ? [userInfo.value.id] : [],
  })

  if (result?.code == 0 && result?.data?.total) {
    return result.data.total
  }
  return 0
}

// 获取待校核数量
const getVerificationListNum = async () => {
  if (!userInfo.value || !userInfo.value.id) return 0

  const result = await requestFunc(IndexFuncName.PendingVerificationNumberApi, equipType.value, {
    pageNo: 1,
    pageSize: 10,
    recheckStrIds: userInfo.value.id,
    recheckStatus: '100',
  })

  if (result?.code == 0 && result?.data?.total) {
    return result.data.total
  }
  return 0
}

// 获取待编制数量
const getPendingPreparationListNum = async () => {
  if (!userInfo.value || !userInfo.value.id) return 0

  const result = await requestFunc(IndexFuncName.PendingPreparationNumberApi, equipType.value, {
    pageNo: 1,
    pageSize: 10,
    mainCheckerStrIds: userInfo.value.id,
  })

  if (result?.code == 0 && result?.data?.total) {
    return result.data.total
  }
  return 0
}

// 获取待审核数量
const getApprovalListNum = async () => {
  if (!userInfo.value || !userInfo.value.id) return 0

  const result = await requestFunc(IndexFuncName.ApprovalNumberApi, equipType.value, {
    pageNo: 1,
    pageSize: 10,
    approveStrIds: userInfo.value.id,
  })

  if (result?.code == 0 && result?.data?.total) {
    return result.data.total
  }
  return 0
}

// 获取待审批数量
const getRatifyListNum = async () => {
  if (!userInfo.value || !userInfo.value.id) return 0

  const result = await requestFunc(IndexFuncName.RatifyNumberApi, equipType.value, {
    pageNo: 1,
    pageSize: 10,
    ratifyStrIds: userInfo.value.id,
  })

  if (result?.code == 0 && result?.data?.total) {
    return result.data.total
  }
  return 0
}

// 获取检验方案审核数量
const getInspectionPlanAuditListNum = async (params: Record<string, any>) => {
  if (!userInfo.value || !userInfo.value.id) return 0

  const result = await requestFunc(IndexFuncName.MajorIssuesAuditNumberApi, equipType.value, {
    pageNo: 1,
    pageSize: 10,
    ...params,
  })

  if (result?.code == 0 && result?.data?.total) {
    return result.data.total || 0
  }
  return 0
}

// 卡片列表
const cardList: CardObj[] = [
  {
    title: '待认领',
    id: 'unClaim',
    description: '条任务待认领',
    path: '/pages/unClaim/unClaimList',
    iconUrl: 'deviceExam',
    getCountFun: getUnClaimNum,
    netWork: true,
  },
  {
    title: '在线录入',
    id: 'taskOnlinePage',
    description: '条待完成',
    path: '/pages/taskOnlinePage/taskOnline',
    iconUrl: 'unitQuery',
    getCountFun: getCheckerOwnTaskNum,
    netWork: true,
  },
  {
    title: '待校核',
    id: 'pendingVerification',
    description: '条待校核',
    path: '/pages/pendingVerification/list/PendingVerificationList',
    iconUrl: 'unitQuery',
    getCountFun: getVerificationListNum,
    netWork: true,
  },
  // {
  //   title: '待编制',
  //   id: 'endingPreparation',
  //   description: '条待编制',
  //   path: '/pages/pendingPreparation/list/PendingPreparationList',
  //   iconUrl: 'unitQuery',
  //   getCountFun: getPendingPreparationListNum,
  //   netWork: true,
  // },
  // {
  //   title: '待审核',
  //   id: 'pendingApproval',
  //   description: '条待审核',
  //   path: '/pages/pendingApproval/list/PendingApprovalList',
  //   iconUrl: 'unitQuery',
  //   getCountFun: getApprovalListNum,
  //   netWork: true,
  // },
  // {
  //   title: '待审批',
  //   id: 'pendingRatify',
  //   description: '条待审批',
  //   path: '/pages/pendingRatify/list/PendingRatifyList',
  //   iconUrl: 'unitQuery',
  //   getCountFun: getRatifyListNum,
  //   netWork: true,
  // },
  {
    title: '检验方案审批',
    id: 'inspectionPlanAudit',
    description: '条待审批',
    path: '/pages/inspectionPlanAudit/list/InspectionPlanAuditList',
    iconUrl: 'unitQuery',
    getCountFun: () =>
      getInspectionPlanAuditListNum({
        reportType: 600,
        status: 100,
        bpmUserId: userInfo.value?.id,
      }),
    netWork: true,
  },
  // {
  //   title: '检验方案批准',
  //   id: 'inspectionApproval',
  //   description: '条待审批',
  //   path: '/pages/inspectionApproval/list/inspectionApprovalList',
  //   iconUrl: 'unitQuery',
  //   getCountFun: () =>
  //     getInspectionPlanAuditListNum({
  //       reportType: 600,
  //       secondStatus: 100,
  //       flag: 1,
  //       bpmUserId: userInfo.value?.id,
  //       isInspectionSchemeRatify: true,
  //     }),
  //   netWork: true,
  // },
  {
    title: '操作指导书批准',
    id: 'workInstructionAudit',
    description: '条待审批',
    path: '/pages/workInstructionAudit/list/WorkInstructionAuditList',
    iconUrl: 'unitQuery',
    getCountFun: () =>
      getInspectionPlanAuditListNum({
        reportType: 700,
        status: 100,
        bpmUserId: userInfo.value?.id,
      }),
    netWork: true,
  },
]

// 功能栏列表
const capabilityList = [
  {
    title: '设备查询',
    desc: '查看全部设备',
    iconUrl: iconMap.deviceExam,
    path: '/pages/deviceExam/deviceExam',
    backgroundColor: '#F6FAFE',
  },
  {
    title: '单位信息',
    desc: '查看单位信息',
    iconUrl: iconMap.unitQuery,
    path: '/pages/unitQuery/unitQuery',
    backgroundColor: '#FEF7F6',
  },
  // {
  //   title: '体系文件',
  //   desc: '查看体系文件',
  //   iconUrl: iconMap.systemFile,
  //   path: '/pages/systemFile/systemFile',
  //   backgroundColor: '#F6FBF6',
  // },
]

// 跳转
const pushCard = (card: CardObj) => {
  // 检查网络状态
  if (card?.netWork && !networkStatus.value) {
    return uni.showToast({ title: '当前网络不可用', icon: 'error' })
  }

  uni.navigateTo({ url: card.path })
}

// 下拉刷新
const onRefresh = () => {
  refresh.value = true

  const currentUserInfo = userStore.userInfo
  cardList.forEach((card) => {
    cardItemRef[card.id]?.getCount(currentUserInfo.id + '')
  })

  setTimeout(() => {
    refresh.value = false
  }, 500)
}
</script>

<style lang="scss" scoped>
.home-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #f2f2f2;
}

.scroll-view {
  flex: 1;
  background-color: #f2f2f2;
}

.status-bar-placeholder {
  width: 100%;
  background-color: #071f50;
}

.header {
  padding: 0 20px 20px;
  padding-top: 50px;
  background-color: #071f50;
}

.header-title {
  font-size: 32px;
  color: #fff;
}

.tab-bar {
  display: flex;
  flex-direction: row;
  align-items: flex-start;
  background-color: #071f50;
}

.tab-item {
  display: flex;
  flex: 1;
  flex-direction: row;
  align-items: center;
  justify-content: center;
  max-width: calc(100vw / 3);
  padding: 12px;
}

.tab-item-active {
  background-color: #fff;
  border-top-left-radius: 15px;
  border-top-right-radius: 15px;
}

.tab-item-text-active {
  font-size: 15px;
  font-weight: bold;
  color: rgb(59, 59, 59);
}

.todo-title-box {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  padding: 20px;
  background-color: #fff;
}

.equip-picker {
  flex-shrink: 0;
}

.todo-title {
  font-size: 18px;
  color: rgb(51, 51, 51);
}

.todo-cards {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: space-between;
  padding: 0 10px;
  margin: 0 10px;
  background-color: #fff;
  border-radius: 0 0 12px 12px;
}

.home-section {
  padding: 0 12px 20px 12px;
  margin: 10px;
  background-color: #ffffff;
  border-radius: 6px;
}

.section-header {
  padding: 16px 8px 16px 8px;
  border-bottom: 1px solid #eee;
}

.cap-section-content {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  gap: 12px;
  padding: 0 8px 15px;
  margin-top: 15px;
}

.section-item {
  position: relative;
  flex: 1;
  padding: 20px 15px;
}

.cap-info {
  width: 100%;
}

.cap-title {
  display: block;
  margin-bottom: 4px;
  font-size: 15px;
  font-weight: 500;
  color: #333333;
}

.cap-desc {
  display: block;
  font-size: 12px;
  color: #666;
}

.cap-section-image {
  display: block;
  width: 100%;
  height: 50px;
}

.network-toast {
  position: fixed;
  top: 50%;
  left: 50%;
  z-index: 9999;
  padding: 15px 25px;
  background-color: rgba(0, 0, 0, 0.7);
  border-radius: 8px;
  transform: translate(-50%, -50%);
}

.network-toast-text {
  font-size: 14px;
  color: #fff;
}
</style>
