import { computed, ref, watch } from 'vue'

import { normalizeRequestForUi } from '../../utils/requestViewModel.js'

export default {
  name: 'RequestsView',
  props: {
    filteredRequests: { type: Array, required: true }
  },
  emits: ['ask', 'approve', 'reject', 'create-request'],
  setup(props, { emit }) {
    const activeTab = ref('全部')
    const tabs = ['全部', '待提交', '审批中', '待出行', '已完成']
    const filters = ['报销状态', '出差城市', '费用类型']

    const datePopover = ref(false)
    const rangeStart = ref('')
    const rangeEnd = ref('')
    const appliedStart = ref('')
    const appliedEnd = ref('')

    const dateRangeLabel = computed(() => {
      if (appliedStart.value && appliedEnd.value) {
        return `${appliedStart.value} ~ ${appliedEnd.value}`
      }

      return '选择时间段'
    })

    function applyDateRange() {
      if (!rangeStart.value || !rangeEnd.value) {
        return
      }

      appliedStart.value = rangeStart.value
      appliedEnd.value = rangeEnd.value
      datePopover.value = false
    }

    const rows = computed(() =>
      props.filteredRequests
        .map((item) => normalizeRequestForUi(item))
        .filter(Boolean)
    )

    const currentPage = ref(1)
    const pageSize = ref(10)
    const pageSizes = [10, 20, 50]
    const pageSizeOpen = ref(false)

    function changePageSize(size) {
      pageSize.value = size
      pageSizeOpen.value = false
      currentPage.value = 1
    }

    const filteredRows = computed(() => {
      if (activeTab.value === '全部') {
        return rows.value
      }

      if (activeTab.value === '待提交') {
        return rows.value.filter((row) => row.approval === '待提交')
      }

      if (activeTab.value === '审批中') {
        return rows.value.filter((row) => row.approval === '审批中')
      }

      if (activeTab.value === '待出行') {
        return rows.value.filter((row) => row.travel.includes('待'))
      }

      if (activeTab.value === '已完成') {
        return rows.value.filter((row) => row.approval === '已完成')
      }

      return rows.value
    })

    const totalCount = computed(() => filteredRows.value.length)
    const totalPages = computed(() => Math.max(1, Math.ceil(totalCount.value / pageSize.value)))

    const visibleRows = computed(() => {
      const start = (currentPage.value - 1) * pageSize.value
      return filteredRows.value.slice(start, start + pageSize.value)
    })

    watch([activeTab, rows], () => {
      currentPage.value = 1
    })

    return {
      emit,
      activeTab,
      tabs,
      filters,
      datePopover,
      rangeStart,
      rangeEnd,
      appliedStart,
      appliedEnd,
      dateRangeLabel,
      applyDateRange,
      rows,
      currentPage,
      pageSize,
      pageSizes,
      pageSizeOpen,
      changePageSize,
      filteredRows,
      totalCount,
      totalPages,
      visibleRows
    }
  }
}
