<template>
  <div class="flex direction-column full personnel-statistics-view">
    <div class="p-l-base p-r-base p-t-medium-base fill-blank filter-form">
      <base-form size="small" :label-width="useVW(88)" :disabled="loading" :model="model" :items="items">
        <template #form-item-button-group>
          <el-button :loading="loading" type="primary" @click="onSearch">查询</el-button>
          <el-button :loading="exporting" type="primary" custom-1 @click="onExport">导出</el-button>
        </template>
      </base-form>
    </div>
    <div class="flex-1 p-small">
      <component
        :is="fetchModel.expand ? StatisticsPersonnel : StatisticsGroup"
        :data="data"
        :params="fetchModel"
      ></component>
    </div>
  </div>
</template>

<script setup lang="ts" name="PersonnelStatistics">
/** 人员数据统计 */
import { computed } from 'vue'
import { omit } from 'lodash-es'
import { ElButton } from 'element-plus'
import BaseForm from '@/components/element/BaseForm.vue'
import useFetch from '@/hooks/useFetch'
import useVW from '@/hooks/useVW'
import useStatisticsFilter from './hooks/useStatisticsFilter'

import StatisticsGroup from './components/StatisticsGroup.vue'
import StatisticsPersonnel from './components/StatisticsPersonnel.vue'

import type { ExtractApiResponse } from '@/api/api'

const { model, fetchModel, items, onOptionInit } = useStatisticsFilter()

const { fetch, result, loading } = useFetch('getStatisticsByGroup')

const data = computed<ExtractApiResponse<'getStatisticsByGroup'>>(() => {
  const groupList = result?.value?.slice(0) || []
  return fetchModel.value.expand
    ? groupList
        .reduce((total, cur) => {
          total.push(...(cur.markerDetails || []))
          return total
        }, [] as ExtractApiResponse<'getStatisticsByGroup'>)
        .sort((a, b) => a.markerId - b.markerId)
    : groupList.sort((a, b) => a.markingGroupNumber - b.markingGroupNumber)
})

/** 刷新按钮 */
function onSearch() {
  fetch(omit(fetchModel.value, 'expand'))
}

onOptionInit(onSearch)

const { fetch: exportStatisticsByGroup, loading: exporting } = useFetch('exportStatisticsByGroup', 'get')
/**导出 */
function onExport() {
  exportStatisticsByGroup(omit(fetchModel.value, 'expand'))
}
</script>

<style scoped lang="scss">
.personnel-statistics-view {
  .filter-form {
    border-bottom: $OnePixelLine;
  }
}
</style>
