import React, { useState, useEffect } from 'react'
import { View, Text, ScrollView, Input, Picker } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { useQuery } from '@tanstack/react-query'
import { Navbar } from '@d8d/mini-shared-ui-components/components/navbar'
import { enterpriseOrderClient } from '../../api'
import type { OrderDetailResponse, CompanyVideosResponse, CheckinStatisticsResponse, VideoStatisticsResponse } from '../../api'


interface OrderDetailData {
  id: any
  orderNumber: any
  name: any
  createdAt: string
  updatedAt: string
  status: any
  statusLabel: string
  statusClass: string
  company: any
  platform: any
  channel: any
  expectedPeople: any
  actualPeople: any
  expectedStartDate: string
  actualStartDate: string
  expectedEndDate: string
  actualEndDate: string | null
  orderPersons?: Array<{
    id: number
    workStatus: string
    joinDate: string
    person?: {
      name: string
      gender: string
      disabilityType: string
      phone: string
    }
  }>
}

const OrderDetail: React.FC = () => {
  const router = Taro.useRouter()
  const orderIdParam = router.params.id ? parseInt(router.params.id) : null
  const orderId = orderIdParam && !Number.isNaN(orderIdParam) ? orderIdParam : null
  const [showCheckinCalendar, setShowCheckinCalendar] = useState(false)
  const [filterStartDate, setFilterStartDate] = useState('')
  const [filterEndDate, setFilterEndDate] = useState('')


  // 获取订单详情查询函数
  const fetchOrderDetailQuery = async (id: number) => {
    const response = await enterpriseOrderClient.detail[':id'].$get({
      param: { id: id }
    })

    if (response.status !== 200) {
      throw new Error(`获取订单详情失败: ${response.status}`)
    }

    const data = await response.json()
    if (!data) {
      throw new Error('API返回数据为空')
    }
    // 转换API数据到UI格式
    const orderPersons = data?.orderPersons || []
    return {
      id: data?.id ?? 0,
      orderNumber: data?.orderName ? `ORDER-${data.id}` : `ORDER-${data?.id ?? 0}`,
      name: data?.orderName || '未命名订单',
      createdAt: data?.createTime ? new Date(data.createTime).toISOString().split('T')[0] : '未知日期',
      updatedAt: data?.updateTime ? new Date(data.updateTime).toISOString().split('T')[0] : '未知日期',
      status: data?.orderStatus || 'draft',
      statusLabel: getStatusLabel(data?.orderStatus),
      statusClass: getStatusClass(data?.orderStatus),
      company: data?.companyId ? `公司${data.companyId}` : '未知公司',
      platform: data?.platformId ? `平台${data.platformId}` : '未知平台',
      channel: '未知渠道', // data?.channelName 不存在
      expectedPeople: 0, // data?.expectedPersonCount 不存在
      actualPeople: orderPersons.length,
      expectedStartDate: data?.expectedStartDate ? new Date(data.expectedStartDate).toISOString().split('T')[0] : '未设置',
      actualStartDate: data?.actualStartDate ? new Date(data.actualStartDate).toISOString().split('T')[0] : '未设置',
      expectedEndDate: '未设置', // data?.expectedEndDate 不存在
      actualEndDate: data?.actualEndDate ? new Date(data.actualEndDate).toISOString().split('T')[0] : null,
      orderPersons: orderPersons.map((op: any) => ({
        id: op.id,
        workStatus: op.workStatus || 'unknown',
        joinDate: op.joinDate ? new Date(op.joinDate).toISOString().split('T')[0] : '未知日期',
        person: op.person ? {
          name: op.person.name || '未知姓名',
          gender: op.person.gender || '未知',
          disabilityType: op.person.disabilityType || '未知类型',
          phone: op.person.phone || '未知电话'
        } : undefined
      }))
    }
  }

  // 获取企业用户信息
  const getEnterpriseUserInfo = () => {
    try {
      const userInfoStr = Taro.getStorageSync('enterpriseUserInfo')
      if (!userInfoStr) return null

      // 尝试解析JSON字符串
      let userInfo = userInfoStr
      if (typeof userInfoStr === 'string') {
        userInfo = JSON.parse(userInfoStr)
      }

      // 处理双重编码情况：{"data": "{\"id\":2,...}"}
      if (userInfo && typeof userInfo === 'object' && userInfo.data) {
        if (typeof userInfo.data === 'string') {
          userInfo = JSON.parse(userInfo.data)
        } else {
          userInfo = userInfo.data
        }
      }

      return userInfo || null
    } catch (error) {
      console.error('获取企业用户信息失败:', error)
      return null
    }
  }

  // 获取订单视频查询函数
  const fetchOrderVideosQuery = async (orderId: number) => {
    try {
      const userInfo = getEnterpriseUserInfo()
      const companyId = userInfo?.companyId || 0

      if (!companyId) {
        console.warn('未找到企业ID，返回空视频列表')
        return [] as VideoItem[]
      }

      // 获取企业视频列表
      const response = await enterpriseOrderClient['company-videos'].$get({
        query: {
          companyId,
          page: 1,
          pageSize: 50 // 获取前50个视频
        }
      })

      if (response.ok) {
        const data = await response.json()
        const videos = data?.data || []

        // 转换API数据到UI格式
        const transformedVideos = videos.map((video: CompanyVideosResponse['data'][0]) => {
          // 根据assetType确定视频类型
          let videoType: 'checkin_video' | 'salary_video' | 'tax_video' = 'checkin_video'
          if (video.assetType === 'salary_video') videoType = 'salary_video'
          if (video.assetType === 'tax_video') videoType = 'tax_video'

          return {
            id: video.id || video.fileId || 0,
            name: video.file?.name || `视频-${video.id}`,
            type: videoType,
            size: video.file?.size ? `${Math.round(video.file.size / 1024 / 1024)}MB` : '未知大小',
            uploadTime: video.file?.uploadTime ? new Date(video.file.uploadTime).toISOString().split('T')[0] : '未知日期'
          }
        })

        return transformedVideos
      } else {
        throw new Error('获取视频列表失败')
      }
    } catch (error) {
      console.error('获取订单视频失败:', error)
      // 返回空列表
      return [] as VideoItem[]
    }
  }


  // 获取订单统计数据查询函数
  const fetchOrderStatisticsQuery = async (orderId: number) => {
    try {
      const userInfo = getEnterpriseUserInfo()
      const companyId = userInfo?.companyId || 0

      if (!companyId) {
        console.warn('未找到企业ID，返回空统计数据')
        return {
          checkinStats: { current: 0, total: 0, percentage: 0 },
          salaryVideoStats: { current: 0, total: 0, percentage: 0 },
          taxVideoStats: { current: 0, total: 0, percentage: 0 },
        }
      }

      // 获取打卡统计数据
      const checkinResponse = await enterpriseOrderClient['checkin-statistics'].$get({
        query: {}
      })

      // 获取视频统计数据
      const videoResponse = await enterpriseOrderClient['video-statistics'].$get({
        query: {}
      })

      if (checkinResponse.ok && videoResponse.ok) {
        const checkinData = await checkinResponse.json()
        const videoData = await videoResponse.json()

        // 解析统计数据 - 使用RPC推断的实际API响应结构
        // CheckinStatisticsResponse: { companyId, checkinVideoCount, totalVideos }
        // VideoStatisticsResponse: { companyId, stats: [{ assetType, count, percentage }], total }
        const checkinCount = checkinData?.checkinVideoCount || 0
        const totalVideos = checkinData?.totalVideos || 0

        // 从视频统计中提取各类视频数量
        const stats = videoData?.stats || []
        const salaryVideoStat = stats.find((stat: any) => stat.assetType === 'salary_video')
        const taxVideoStat = stats.find((stat: any) => stat.assetType === 'tax_video')
        const checkinVideoStat = stats.find((stat: any) => stat.assetType === 'checkin_video')

        const salaryVideoCount = salaryVideoStat?.count || 0
        const taxVideoCount = taxVideoStat?.count || 0
        const checkinVideoCount = checkinVideoStat?.count || 0

        // 总人数需要从订单详情获取，暂时使用总视频数作为占位
        const totalPersonCount = totalVideos

        return {
          checkinStats: {
            current: checkinCount,
            total: totalPersonCount,
            percentage: totalPersonCount > 0 ? Math.round((checkinCount / totalPersonCount) * 100) : 0
          },
          salaryVideoStats: {
            current: salaryVideoCount,
            total: totalPersonCount,
            percentage: totalPersonCount > 0 ? Math.round((salaryVideoCount / totalPersonCount) * 100) : 0
          },
          taxVideoStats: {
            current: taxVideoCount,
            total: totalPersonCount,
            percentage: totalPersonCount > 0 ? Math.round((taxVideoCount / totalPersonCount) * 100) : 0
          },
        }
      } else {
        throw new Error('获取统计数据失败')
      }
    } catch (error) {
      console.error('获取订单统计数据失败:', error)
      // 返回默认数据
      return {
        checkinStats: { current: 0, total: 0, percentage: 0 },
        salaryVideoStats: { current: 0, total: 0, percentage: 0 },
        taxVideoStats: { current: 0, total: 0, percentage: 0 },
      }
    }
  }

  // 使用React Query获取订单详情
  const {
    data: order,
    isLoading,
    error: queryError,
  } = useQuery<OrderDetailData, Error>({
    queryKey: ['order-detail', orderId],
    queryFn: () => orderId ? fetchOrderDetailQuery(orderId) : Promise.reject(new Error('未找到订单ID')),
    enabled: !!orderId,
  })

  // 视频查询接口
  interface VideoItem {
    id: number
    name: string
    type: 'checkin_video' | 'salary_video' | 'tax_video'
    size: string
    uploadTime: string
  }

  // 统计数据接口
  interface StatisticsData {
    checkinStats: { current: number, total: number, percentage: number }
    salaryVideoStats: { current: number, total: number, percentage: number }
    taxVideoStats: { current: number, total: number, percentage: number }
  }

  // 使用React Query获取订单视频
  const {
    data: videos = [],
    isLoading: videosLoading,
    error: videosError,
  } = useQuery<VideoItem[], Error>({
    queryKey: ['order-videos', orderId],
    queryFn: () => orderId ? fetchOrderVideosQuery(orderId) : Promise.reject(new Error('未找到订单ID')),
    enabled: !!orderId,
  })

  // 使用React Query获取订单统计数据
  const {
    data: statistics,
    isLoading: statisticsLoading,
    error: statisticsError,
  } = useQuery<StatisticsData, Error>({
    queryKey: ['order-statistics', orderId],
    queryFn: () => orderId ? fetchOrderStatisticsQuery(orderId) : Promise.reject(new Error('未找到订单ID')),
    enabled: !!orderId,
  })

  // 处理查询错误
  useEffect(() => {
    if (queryError) {
      console.error('获取订单详情错误:', queryError)
      Taro.showToast({
        title: queryError.message.includes('未找到订单ID') ? '未找到订单ID' : '获取订单详情失败',
        icon: 'none'
      })
    }
    if (videosError) {
      console.error('获取订单视频错误:', videosError)
      Taro.showToast({
        title: '获取视频数据失败',
        icon: 'none'
      })
    }
    if (statisticsError) {
      console.error('获取订单统计错误:', statisticsError)
      Taro.showToast({
        title: '获取统计数据失败',
        icon: 'none'
      })
    }
  }, [queryError, videosError, statisticsError])

  // 组合加载状态和错误状态
  const isLoadingAll = isLoading || videosLoading || statisticsLoading
  const hasError = queryError || videosError || statisticsError
  const errorMessage = queryError?.message || videosError?.message || statisticsError?.message || '加载数据失败'

  // 状态标签和样式辅助函数
  const getStatusLabel = (status: string | undefined) => {
    const statusValue = status || 'draft'
    switch (statusValue) {
      case 'draft': return '草稿'
      case 'confirmed': return '已确认'
      case 'in_progress': return '进行中'
      case 'completed': return '已完成'
      case 'cancelled': return '已取消'
      default: return statusValue
    }
  }

  const getStatusClass = (status: string | undefined) => {
    const statusValue = status || 'draft'
    switch (statusValue) {
      case 'draft': return 'bg-gray-100 text-gray-800'
      case 'confirmed': return 'bg-blue-100 text-blue-800'
      case 'in_progress': return 'bg-green-100 text-green-800'
      case 'completed': return 'bg-purple-100 text-purple-800'
      case 'cancelled': return 'bg-red-100 text-red-800'
      default: return 'bg-gray-100 text-gray-800'
    }
  }





  const handleViewCheckinDetails = () => {
    setShowCheckinCalendar(true)
  }

  // 获取打卡日历数据
  const getCheckinCalendarData = () => {
    if (!videos || videos.length === 0) {
      return {
        checkinDays: [],
        totalDays: 31,
        checkinCount: 0,
        missedCount: 0,
        attendanceRate: 0
      }
    }

    // 筛选打卡视频
    const checkinVideos = videos.filter(video => video.type === 'checkin_video')

    // 提取日期（假设uploadTime格式为YYYY-MM-DD）
    const checkinDates = checkinVideos.map(video => {
      const dateStr = video.uploadTime
      return dateStr.split(' ')[0] // 取日期部分
    })

    // 去重
    const uniqueDates = [...new Set(checkinDates)]

    // 计算本月数据（模拟）
    const currentMonth = '2025-12'
    const daysInMonth = 31

    // 筛选本月日期
    const monthDates = uniqueDates.filter(date => date.startsWith(currentMonth))

    // 计算打卡日期
    const checkinDays = monthDates.map(date => parseInt(date.split('-')[2]))

    return {
      checkinDays,
      totalDays: daysInMonth,
      checkinCount: checkinDays.length,
      missedCount: daysInMonth - checkinDays.length,
      attendanceRate: Math.round((checkinDays.length / daysInMonth) * 100)
    }
  }

  const handleDownloadReport = () => {
    console.log('下载报告')
    // TODO: 下载订单报告
  }

  // 导出打卡数据
  const handleExportCheckinData = async () => {
    try {
      // 获取打卡数据
      const checkinData = getCheckinCalendarData()
      const checkinVideos = videos.filter(video => video.type === 'checkin_video')

      // 创建CSV内容
      const headers = ['日期', '视频名称', '视频类型', '大小', '上传时间']
      const rows = checkinVideos.map(video => [
        video.uploadTime.split(' ')[0],
        video.name,
        video.type === 'checkin_video' ? '打卡视频' : '其他',
        video.size,
        video.uploadTime
      ])

      // 添加统计信息
      rows.push([])
      rows.push(['统计信息', '', '', '', ''])
      rows.push(['总打卡天数', checkinData.checkinCount.toString(), '', '', ''])
      rows.push(['未打卡天数', checkinData.missedCount.toString(), '', '', ''])
      rows.push(['出勤率', `${checkinData.attendanceRate}%`, '', '', ''])

      const csvContent = [headers, ...rows].map(row => row.join(',')).join('\n')

      // 在小程序中，可以使用Taro.saveFile或Taro.downloadFile
      // 这里先显示提示，实际项目中需要实现文件保存逻辑
      Taro.showToast({
        title: `已生成${checkinVideos.length}条打卡记录`,
        icon: 'success'
      })

      console.log('打卡数据CSV:', csvContent)
      // TODO: 实际文件保存逻辑
      // Taro.downloadFile({
      //   url: 'data:text/csv;charset=utf-8,' + encodeURIComponent(csvContent),
      //   success: function (res) {
      //     Taro.saveFile({
      //       tempFilePath: res.tempFilePath,
      //       success: function (saveRes) {
      //         Taro.showToast({ title: '导出成功', icon: 'success' })
      //       }
      //     })
      //   }
      // })

    } catch (error) {
      console.error('导出打卡数据失败:', error)
      Taro.showToast({
        title: '导出失败',
        icon: 'none'
      })
    }
  }

  // 播放视频
  const handlePlayVideo = (videoId: number, videoName: string) => {
    console.log('播放视频:', videoId, videoName)
    // TODO: 实现视频播放逻辑
    // 在小程序中，可能需要使用Taro.openVideo或Taro.previewMedia
    // 首先需要获取视频URL
    Taro.showToast({
      title: `播放视频: ${videoName}`,
      icon: 'none'
    })
  }

  // 下载视频
  const handleDownloadVideo = async (videoId: number, videoName: string) => {
    try {
      console.log('下载视频:', videoId, videoName)
      Taro.showToast({
        title: `开始下载: ${videoName}`,
        icon: 'none'
      })

      // TODO: 实现视频下载逻辑
      // 1. 获取视频URL
      // 2. 使用Taro.downloadFile下载
      // 3. 使用Taro.saveFile保存到本地

      // 模拟下载延迟
      setTimeout(() => {
        Taro.showToast({
          title: `已下载: ${videoName}`,
          icon: 'success'
        })
      }, 1000)

    } catch (error) {
      console.error('下载视频失败:', error)
      Taro.showToast({
        title: '下载失败',
        icon: 'none'
      })
    }
  }

  // 分享视频
  const handleShareVideo = (videoId: number, videoName: string) => {
    console.log('分享视频:', videoId, videoName)
    // 小程序分享功能
    Taro.showShareMenu({
      withShareTicket: true
    })
    Taro.showToast({
      title: `分享视频: ${videoName}`,
      icon: 'none'
    })
  }

  // 批量下载视频
  const handleBatchDownload = async () => {
    try {
      if (!videos || videos.length === 0) {
        Taro.showToast({
          title: '没有可下载的视频',
          icon: 'none'
        })
        return
      }

      Taro.showToast({
        title: `开始批量下载${videos.length}个视频`,
        icon: 'none'
      })

      // 在实际项目中，这里需要调用批量下载API
      // const response = await enterpriseOrderClient['batch-download'].$post({
      //   body: {
      //     downloadScope: 'company',
      //     companyId: getEnterpriseUserInfo()?.companyId || 0,
      //     assetTypes: ['checkin_video', 'salary_video', 'tax_video']
      //   }
      // })

      // 模拟批量下载过程
      let downloadedCount = 0
      for (const video of videos) {
        console.log(`下载视频: ${video.name}`)
        downloadedCount++
        // 模拟每个视频下载延迟
        await new Promise(resolve => setTimeout(resolve, 500))
      }

      Taro.showToast({
        title: `批量下载完成: ${downloadedCount}/${videos.length}`,
        icon: 'success'
      })

    } catch (error) {
      console.error('批量下载视频失败:', error)
      Taro.showToast({
        title: '批量下载失败',
        icon: 'none'
      })
    }
  }

  return (
    <>
      {/* 导航栏 */}
      <Navbar
        title="订单详情"
        leftIcon="i-heroicons-chevron-left-20-solid"
        leftText="返回"
        backgroundColor="bg-white"
        border={true}
        fixed={true}
        placeholder={true}
        onClickLeft={() => console.log('返回')}
      />
      <ScrollView
        className="h-screen overflow-y-auto px-4 pb-4 pt-0"
        scrollY
      >
        {isLoadingAll ? (
          <View className="flex items-center justify-center h-64">
            <Text className="text-gray-500">加载中...</Text>
          </View>
        ) : hasError ? (
          <View className="flex items-center justify-center h-64">
            <Text className="text-red-500">{errorMessage}</Text>
          </View>
        ) : !order ? (
          <View className="flex items-center justify-center h-64">
            <Text className="text-gray-500">未找到订单数据</Text>
          </View>
        ) : (
          <>
        {/* 顶部信息卡片 */}
        <View className="card bg-white p-4 mb-4 mt-4">
          <View className="flex justify-between items-start mb-3">
            <View className="flex flex-col">
              <Text className="text-xl font-bold text-gray-800">{order.name}</Text>
              <Text className="text-sm text-gray-500 mt-1">订单编号: {order.orderNumber}</Text>
            </View>
            <Text className={`text-xs px-2 py-1 rounded-full ${order.statusClass}`}>
              {order.statusLabel}
            </Text>
          </View>

          <View className="grid grid-cols-2 gap-3 text-sm">
            <View className="flex flex-col">
              <Text className="text-gray-500">创建时间</Text>
              <Text className="text-gray-800">{order.createdAt}</Text>
            </View>
            <View className="flex flex-col">
              <Text className="text-gray-500">更新时间</Text>
              <Text className="text-gray-800">{order.updatedAt}</Text>
            </View>
            <View className="flex flex-col">
              <Text className="text-gray-500">企业名称</Text>
              <Text className="text-gray-800">{order.company}</Text>
            </View>
            <View className="flex flex-col">
              <Text className="text-gray-500">平台</Text>
              <Text className="text-gray-800">{order.platform}</Text>
            </View>
          </View>
        </View>

        {/* 基本信息卡片 */}
        <View className="card bg-white p-4 mb-4">
          <Text className="font-semibold text-gray-700 mb-3">基本信息</Text>
          <View className="grid grid-cols-2 gap-3 text-sm">
            <View className="flex flex-col">
              <Text className="text-gray-500">预计人数</Text>
              <Text className="text-gray-800">{order.expectedPeople}人</Text>
            </View>
            <View className="flex flex-col">
              <Text className="text-gray-500">实际人数</Text>
              <Text className="text-gray-800">{order.actualPeople}人</Text>
            </View>
            <View className="flex flex-col">
              <Text className="text-gray-500">预计开始</Text>
              <Text className="text-gray-800">{order.expectedStartDate}</Text>
            </View>
            <View className="flex flex-col">
              <Text className="text-gray-500">实际开始</Text>
              <Text className="text-gray-800">{order.actualStartDate}</Text>
            </View>
            <View className="flex flex-col">
              <Text className="text-gray-500">预计结束</Text>
              <Text className="text-gray-800">{order.expectedEndDate}</Text>
            </View>
            <View className="flex flex-col">
              <Text className="text-gray-500">实际结束</Text>
              <Text className="text-gray-800">{order.actualEndDate || '未结束'}</Text>
            </View>
            <View className="flex flex-col">
              <Text className="text-gray-500">渠道</Text>
              <Text className="text-gray-800">{order.channel}</Text>
            </View>
          </View>
        </View>

        {/* 打卡统计卡片 */}
        <View className="card bg-white p-4 mb-4">
          <Text className="font-semibold text-gray-700 mb-3">打卡数据统计</Text>
          <View className="grid grid-cols-3 gap-2 mb-3">
            <View className="bg-blue-50 rounded-lg p-2 text-center flex flex-col">
              <Text className="text-xs text-gray-600">本月打卡</Text>
              <Text className="text-sm font-bold text-gray-800">
                {statistics?.checkinStats.current || 0}/{statistics?.checkinStats.total || 0}
              </Text>
              <Text className="text-xs text-gray-500">{statistics?.checkinStats.percentage || 0}%</Text>
            </View>
            <View className="bg-green-50 rounded-lg p-2 text-center flex flex-col">
              <Text className="text-xs text-gray-600">工资视频</Text>
              <Text className="text-sm font-bold text-gray-800">
                {statistics?.salaryVideoStats.current || 0}/{statistics?.salaryVideoStats.total || 0}
              </Text>
              <Text className="text-xs text-gray-500">{statistics?.salaryVideoStats.percentage || 0}%</Text>
            </View>
            <View className="bg-purple-50 rounded-lg p-2 text-center flex flex-col">
              <Text className="text-xs text-gray-600">个税视频</Text>
              <Text className="text-sm font-bold text-gray-800">
                {statistics?.taxVideoStats.current || 0}/{statistics?.taxVideoStats.total || 0}
              </Text>
              <Text className="text-xs text-gray-500">{statistics?.taxVideoStats.percentage || 0}%</Text>
            </View>
          </View>
          <View className="flex items-center text-blue-500 text-sm" onClick={handleViewCheckinDetails}>
            <Text>查看详细打卡记录</Text>
          </View>
        </View>

        {/* 关联人才卡片 */}
        <View className="card bg-white p-4 mb-4">
          <View className="flex items-center mb-3">
            <Text className="font-semibold text-gray-700">关联人才</Text>
          </View>
          <View className="space-y-3">
            {order?.orderPersons?.map((orderPerson) => (
              <View key={orderPerson.id} className="flex justify-between items-center border-b border-gray-100 pb-2">
                <View className="flex flex-col">
                  <Text className="font-medium text-gray-800">{orderPerson.person?.name || '未知姓名'}</Text>
                  <Text className="text-xs text-gray-500">
                    {orderPerson.person?.gender || '未知'} · {orderPerson.person?.disabilityType || '未知类型'} · 入职: {orderPerson.joinDate}
                  </Text>
                </View>
                <Text className={`text-xs px-2 py-1 rounded-full ${
                  orderPerson.workStatus === 'working' ? 'bg-green-100 text-green-800' :
                  orderPerson.workStatus === 'pre_working' ? 'bg-yellow-100 text-yellow-800' :
                  'bg-gray-100 text-gray-800'
                }`}>
                  {orderPerson.workStatus === 'working' ? '已就业' :
                   orderPerson.workStatus === 'pre_working' ? '待就业' : '未就业'}
                </Text>
              </View>
            ))}
          </View>
        </View>

        {/* 视频资料卡片 */}
        <View className="card bg-white p-4 mb-4">
          <View className="flex justify-between items-center mb-3">
            <Text className="font-semibold text-gray-700">视频资料</Text>
            <View className="flex items-center text-blue-500 text-xs" onClick={handleBatchDownload}>
              <Text>批量下载</Text>
            </View>
          </View>
          <View className="space-y-3">
            {(videos || []).map((video: VideoItem) => (
              <View key={video.id} className="flex justify-between items-center border-b border-gray-100 pb-2">
                <View className="flex flex-col">
                  <Text className="font-medium text-gray-800">{video.name}</Text>
                  <Text className="text-xs text-gray-500">
                    {video.type === 'checkin_video' ? '打卡视频' :
                     video.type === 'salary_video' ? '工资视频' : '个税视频'} · {video.size} · {video.uploadTime}
                  </Text>
                </View>
                <View className="flex space-x-2">
                  <View className="flex items-center text-blue-500 text-xs" onClick={() => handlePlayVideo(video.id, video.name)}>
                    <Text>播放</Text>
                  </View>
                  <View className="flex items-center text-gray-500 text-xs" onClick={() => handleDownloadVideo(video.id, video.name)}>
                    <Text>下载</Text>
                  </View>
                  <View className="flex items-center text-green-500 text-xs" onClick={() => handleShareVideo(video.id, video.name)}>
                    <Text>分享</Text>
                  </View>
                </View>
              </View>
            ))}
          </View>
        </View>



        {/* 操作按钮区域 */}
        <View className="card bg-white p-4 mb-4">
          <View className="flex flex-col space-y-2">
            <View
              className="flex items-center justify-center bg-green-500 text-white text-sm px-4 py-2 rounded-lg"
              onClick={handleDownloadReport}
            >
              <Text>下载订单报告</Text>
            </View>
            <View
              className="flex items-center justify-center border border-gray-300 text-gray-700 text-sm px-4 py-2 rounded-lg"
              onClick={() => console.log('分享订单')}
            >
              <Text>分享订单</Text>
            </View>
          </View>
        </View>
        </>)}
      </ScrollView>
      {/* 打卡日历模态框 */}
      {showCheckinCalendar && (
        <View className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <View className="bg-white rounded-lg w-11/12 max-w-md">
            {/* 模态框头部 */}
            <View className="flex justify-between items-center p-4 border-b border-gray-200">
              <Text className="font-semibold text-gray-700">打卡日历</Text>
              <View
                className="text-gray-500 text-lg"
                onClick={() => setShowCheckinCalendar(false)}
              >
                <Text>×</Text>
              </View>
            </View>
            {/* 模态框内容 */}
            <View className="p-4">
              {/* 时间范围筛选 */}
              <View className="flex space-x-2 mb-4">
                <View className="flex-1">
                  <Text className="text-xs text-gray-500 mb-1">开始日期</Text>
                  <Picker
                    mode="date"
                    value={filterStartDate}
                    onChange={(e) => setFilterStartDate(e.detail.value)}
                  >
                    <View className="border border-gray-300 rounded px-2 py-1 text-sm bg-white min-h-[2rem] flex items-center">
                      <Text className={filterStartDate ? 'text-gray-800' : 'text-gray-400'}>
                        {filterStartDate || '选择开始日期'}
                      </Text>
                    </View>
                  </Picker>
                </View>
                <View className="flex-1">
                  <Text className="text-xs text-gray-500 mb-1">结束日期</Text>
                  <Picker
                    mode="date"
                    value={filterEndDate}
                    onChange={(e) => setFilterEndDate(e.detail.value)}
                  >
                    <View className="border border-gray-300 rounded px-2 py-1 text-sm bg-white min-h-[2rem] flex items-center">
                      <Text className={filterEndDate ? 'text-gray-800' : 'text-gray-400'}>
                        {filterEndDate || '选择结束日期'}
                      </Text>
                    </View>
                  </Picker>
                </View>
              </View>

              {/* 简单的日历视图 */}
              <View className="mb-4">
                <Text className="font-medium text-gray-700 mb-2">2025年12月</Text>
                <View className="grid grid-cols-7 gap-1 text-center">
                  {/* 星期标题 */}
                  {['日', '一', '二', '三', '四', '五', '六'].map((day) => (
                    <Text key={day} className="text-xs text-gray-500 py-1">{day}</Text>
                  ))}
                  {/* 日期单元格 */}
                  {Array.from({ length: 31 }, (_, i) => i + 1).map((day) => {
                    const checkinData = getCheckinCalendarData()
                    const isCheckedIn = checkinData.checkinDays.includes(day)
                    return (
                      <View
                        key={day}
                        className={`p-2 rounded ${isCheckedIn ? 'bg-green-100' : 'bg-gray-100'}`}
                      >
                        <Text className={`text-sm ${isCheckedIn ? 'text-green-800' : 'text-gray-500'}`}>
                          {day}
                        </Text>
                        {isCheckedIn && (
                          <Text className="text-xs text-green-600">已打卡</Text>
                        )}
                      </View>
                    )
                  })}
                </View>
              </View>

              {/* 打卡统计 */}
              <View className="bg-blue-50 rounded-lg p-3 mb-4">
                <Text className="font-medium text-blue-700 mb-1">本月打卡统计</Text>
                <View className="flex justify-between">
                  <View className="flex flex-col">
                    <Text className="text-xs text-blue-600">已打卡</Text>
                    <Text className="text-lg font-bold text-blue-800">{getCheckinCalendarData().checkinCount}天</Text>
                  </View>
                  <View className="flex flex-col">
                    <Text className="text-xs text-blue-600">未打卡</Text>
                    <Text className="text-lg font-bold text-blue-800">{getCheckinCalendarData().missedCount}天</Text>
                  </View>
                  <View className="flex flex-col">
                    <Text className="text-xs text-blue-600">出勤率</Text>
                    <Text className="text-lg font-bold text-blue-800">{getCheckinCalendarData().attendanceRate}%</Text>
                  </View>
                </View>
              </View>

              {/* 操作按钮 */}
              <View className="flex space-x-2">
                <View
                  className="flex-1 flex items-center justify-center bg-blue-500 text-white text-sm px-4 py-2 rounded-lg"
                  onClick={handleExportCheckinData}
                >
                  <Text>导出打卡数据</Text>
                </View>
                <View
                  className="flex-1 flex items-center justify-center border border-gray-300 text-gray-700 text-sm px-4 py-2 rounded-lg"
                  onClick={() => setShowCheckinCalendar(false)}
                >
                  <Text>关闭</Text>
                </View>
              </View>
            </View>
          </View>
        </View>
      )}
    </>
  )
} 

export default OrderDetail