import { ref, reactive, computed, watch } from 'vue'
import { ROLE_OPTION, StatusMap } from '@/constants/dicts'
import useForm from '@/hooks/useForm'
import useOptions, { DataModel } from '@/hooks/useOptions'

import type { EpFormItem, InstanceForm, EpFormRows } from 'global-type'
import type { ExtractMultipleApiParams } from '@/api/api'

const useUserManageFilter = () => {
  const { subjectList, mainQuestionList, changeModelValue, dataModel } = useOptions(['subject', 'question'])

  const { elFormRef, formRef, defineColumn, _ } = useForm()

  const expand = ref(false)

  const model = reactive<ExtractMultipleApiParams<'getUserList'>>({
    subjectCode: dataModel.subject || '',
    mainNumber: dataModel.question,
    enable: true,
    loginName: '',
    name: '',
    role: void 0,
  })

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

  const rows: EpFormRows = reactive({
    'row-1': { hidden: false },
    'row-2': { hidden: true },
  })

  const Span5 = defineColumn(_, _, { span: 5 })
  const Span9 = defineColumn(_, _, { span: 9 })

  const OneRowSpan5 = Span5(_, 'row-1')
  const OneRowSpan9 = Span9(_, 'row-1')
  const TwoRowSpan5 = Span5(_, 'row-2')

  const items = computed<EpFormItem[]>(() => [
    OneRowSpan5({
      slotType: 'select',
      label: '科目',
      prop: 'subjectCode',
      slot: {
        placeholder: '选择科目',
        options: subjectList.value,
        onChange: changeModelValue('subject'),
        clearable: true,
      },
    }),
    OneRowSpan5({
      slotType: 'select',
      label: '大题',
      prop: 'mainNumber',
      slot: {
        placeholder: '选择大题',
        options: mainQuestionList.value,
        onChange: changeModelValue('question'),
        clearable: true,
      },
    }),
    OneRowSpan5({
      slotType: 'select',
      label: '角色',
      prop: 'role',
      slot: {
        placeholder: '用户角色',
        options: ROLE_OPTION,
        clearable: true,
      },
    }),
    TwoRowSpan5({
      slotType: 'input',
      label: '登录名',
      prop: 'loginName',
      slot: {
        placeholder: '登录名',
        clearable: true,
      },
    }),
    TwoRowSpan5({
      slotType: 'input',
      label: '姓名',
      prop: 'name',
      slot: {
        placeholder: '用户姓名',
        clearable: true,
      },
    }),
    TwoRowSpan5({
      slotType: 'select',
      label: '状态',
      prop: 'enable',
      slot: {
        options: StatusMap,
        clearable: true,
      },
    }),
    OneRowSpan9({
      slotName: 'button-group',
    }),
  ])

  const toggleExpand = () => {
    expand.value = !expand.value
  }

  watch(expand, () => {
    rows['row-2'].hidden = !expand.value
  })

  return {
    model,
    elFormRef,
    formRef,
    items,
    rows,
    expand,
    toggleExpand,
  }
}

export default useUserManageFilter
