<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <div class="mb-15px">
      <span class="mr-10px">统计区间：</span>
      <el-date-picker
        v-model="dateRange"
        type="datetimerange"
        align="right"
        unlink-panels
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        :shortcuts="dateShortcuts"
        class="!w-240px mr-10px"
        @change="handleDateChange"
      />
      <el-button
        type="warning"
        plain
        @click="handleExport"
      >
        <Icon icon="ep:download" class="mr-5px" /> 导出数据表
      </el-button>
    </div>

    <!-- 统计图表 -->
    <div class="grid grid-cols-2 gap-10px">
      <div class="border border-solid border-gray-300 h-400px">
        <LockerDaily :start-time="queryParams.startTime" :end-time="queryParams.endTime" />
      </div>
      <div class="border border-solid border-gray-300 h-400px">
        <LockerLending :start-time="queryParams.startTime" :end-time="queryParams.endTime" />
      </div>
      <div class="border border-solid border-gray-300 h-400px">
        <LockerCollection :start-time="queryParams.startTime" :end-time="queryParams.endTime" />
      </div>
      <div class="border border-solid border-gray-300 h-400px">
        <LockerReturn :start-time="queryParams.startTime" :end-time="queryParams.endTime" />
      </div>
    </div>
  </ContentWrap>
</template>

<script lang="ts" setup>
import LockerDaily from './LockerDaily.vue'
import LockerLending from './LockerLending.vue'
import LockerCollection from './LockerCollection.vue'
import LockerReturn from './LockerReturn.vue'
import download from '@/utils/download'
import * as StatisticsApi from "@/api/material/statistics";
import {exportClaimAndReturn} from "@/api/material/statistics";
defineOptions({ name: 'LockerTwo' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

// 日期范围
const dateRange = ref<[Date, Date]>(getDefaultDateRange())
const queryParams = reactive({
  startTime: undefined as string | undefined,
  endTime: undefined as string | undefined
})

// 日期快捷选项
const dateShortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    }
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    }
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    }
  }
]

/** 获取默认日期范围 */
function getDefaultDateRange(): [Date, Date] {
  const today = new Date()
  const oneMonthAgo = new Date(today.getFullYear(), today.getMonth() - 1, today.getDate())
  return [oneMonthAgo, today]
}

/** 处理日期变化 */
const handleDateChange = (val: [Date, Date] | null) => {
  if (val && val.length === 2) {
    // 格式化开始时间（设置为当天开始）
    const startDate = new Date(val[0])
    startDate.setHours(0, 0, 0, 0)
    queryParams.startTime = formatDateTime(startDate)

    // 格式化结束时间（设置为当天结束）
    const endDate = new Date(val[1])
    endDate.setHours(23, 59, 59, 999)
    queryParams.endTime = formatDateTime(endDate)

    console.log('开始时间:', queryParams.startTime)
    console.log('结束时间:', queryParams.endTime)
  } else {
    queryParams.startTime = undefined
    queryParams.endTime = undefined
  }
}

/** 格式化日期时间为字符串 */
const formatDateTime = (date: Date): string => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}


/** 导出数据 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    const data = await StatisticsApi.exportClaimAndReturn(queryParams)
    download.excel(data, '领取归还统计.xls')
  } catch {
  }
}

/** 初始化 */
onMounted(() => {

  handleDateChange(dateRange.value)
})
</script>

<style lang="scss" scoped>
.grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
}
</style>
