import { reactive, computed, watch } from 'vue'
import useForm from '@/hooks/useForm'
import useOptions from '@/hooks/useOptions'
import useVW from '@/hooks/useVW'

import type { EpFormItem } from 'global-type'
import type { ExtractApiParams } from '@/api/api'

const useFormFilter = () => {
  const { subjectList, mainQuestionList, groupListWithAll, changeModelValue, dataModel, onOptionInit } = useOptions([
    'subject',
    'question',
    'group',
  ])
  const { formRef, elFormRef, defineColumn, _ } = useForm()

  const model = reactive<
    Omit<ExtractApiParams<'getGroupMonitor'>, 'markingGroupNumbers'> & { markingGroupNumbers?: number }
  >({
    subjectCode: dataModel.subject || '',
    markingGroupNumbers: dataModel.group,
    questionMainNumber: dataModel.question,
  })

  const formModel = computed<ExtractApiParams<'getGroupMonitor'>>(() => {
    return {
      subjectCode: model.subjectCode,
      markingGroupNumbers:
        typeof model.markingGroupNumbers === 'number' ? [model.markingGroupNumbers] : model.markingGroupNumbers,
      questionMainNumber: model.questionMainNumber,
    }
  })

  watch(dataModel, () => {
    model.subjectCode = dataModel.subject || ''
    model.questionMainNumber = dataModel.question
    model.markingGroupNumbers = dataModel.group
  })

  const OneRowSpan5 = defineColumn(_, 'row-1', { span: 5 })

  const items = computed<EpFormItem[]>(() => [
    OneRowSpan5({
      label: '科目',
      prop: 'subjectCode',
      slotType: 'select',
      slot: {
        disabled: true,
        options: subjectList.value,
        onChange: changeModelValue('subject'),
      },
    }),
    OneRowSpan5({
      prop: 'questionMainNumber',
      label: '大题',
      slotType: 'select',
      slot: {
        disabled: true,
        options: mainQuestionList.value,
        onChange: changeModelValue('question'),
      },
    }),
    OneRowSpan5({
      prop: 'markingGroupNumbers',
      label: '小组',
      slotType: 'select',
      slot: {
        options: groupListWithAll.value,
        onChange: changeModelValue('group'),
      },
    }),
    OneRowSpan5({
      labelWidth: useVW(20),
      slotName: 'button-group',
    }),
  ])

  return {
    formRef,
    elFormRef,
    model,
    formModel,
    items,
    onOptionInit,
  }
}

export default useFormFilter
