<script setup lang="ts">
/* eslint-disable no-void */
import { computed, onMounted, ref } from 'vue';
import { fetchGetWorkReportStatusDict } from '@/service/api';
import type { SearchField } from '@/components/custom/table-search-fields.vue';
import TableSearchFields from '@/components/custom/table-search-fields.vue';
import { BOOLEAN_TRUE_FALSE_OPTIONS, type WorkReportSearchParams, type WorkReportType } from '../types';

defineOptions({ name: 'WorkReportSearch' });

interface Props {
  reportType: WorkReportType;
  projectOptions?: Api.WorkReport.Project.ProjectReportOwnerProjectOption[];
}

const props = withDefaults(defineProps<Props>(), {
  projectOptions: () => []
});

const model = defineModel<WorkReportSearchParams>('model', { required: true });

const emit = defineEmits<{
  (e: 'reset'): void;
  (e: 'search'): void;
}>();

const statusDict = ref<Api.WorkReport.Common.WorkReportStatusDict[]>([]);

const statusOptions = computed(() =>
  [...statusDict.value]
    .sort((a, b) => Number(a.sort || 0) - Number(b.sort || 0))
    .map(item => ({
      label: item.statusName || item.statusCode,
      value: item.statusCode
    }))
);

const fields = computed<SearchField[]>(() => {
  const baseFields: SearchField[] = [
    { key: 'statusCode', label: '状态', type: 'select', options: statusOptions.value, placeholder: '请选择状态' },
    { key: 'periodStartDate', label: '周期', type: 'dateRange', placeholder: '请选择周期' }
  ];

  const monthPeriodField: SearchField = {
    key: 'periodStartDate',
    label: props.reportType === 'project' ? '月份' : '月份',
    type: 'dateRange',
    dateRangeType: 'monthrange',
    valueFormat: 'YYYY-MM-DD',
    placeholder: '请选择月份'
  };

  if (props.reportType === 'weekly') {
    return [
      ...baseFields,
      {
        key: 'isBusinessTrip',
        label: '是否出差',
        type: 'select',
        options: BOOLEAN_TRUE_FALSE_OPTIONS,
        placeholder: '请选择'
      }
    ];
  }

  if (props.reportType === 'project') {
    return [
      baseFields[0],
      monthPeriodField,
      {
        key: 'projectId',
        label: '项目',
        type: 'select',
        options: props.projectOptions.map(item => ({
          label: item.projectCode ? `${item.projectName}（${item.projectCode}）` : item.projectName,
          value: item.id
        })),
        placeholder: '请选择项目'
      }
    ];
  }

  if (props.reportType === 'monthly') {
    return [baseFields[0], monthPeriodField];
  }

  return baseFields;
});

async function loadStatusDict() {
  const { error, data } = await fetchGetWorkReportStatusDict();
  statusDict.value = error || !data ? [] : data;
}

onMounted(() => {
  loadStatusDict();
});
</script>

<template>
  <TableSearchFields v-model="model" :columns="4" :fields="fields" @reset="emit('reset')" @search="emit('search')" />
</template>
