import { reactive, computed, watch } from 'vue'
import { omit } from 'lodash-es'
import useForm from '@/hooks/useForm'
import useOptions from '@/hooks/useOptions'
import useVW from '@/hooks/useVW'
import { getCurDayRange } from '@/utils/common'
import useFetch from '@/hooks/useFetch'
import useDayList from '@/hooks/useDayList'
import { getTodayByDay } from '@/utils/common'
import type { EpFormItem, EpFormRows } from 'global-type'
import type { ExtractApiParams } from '@/api/api'

type FormMode = Omit<
  ExtractApiParams<'getStatisticsByGroup'>,
  'curDay' | 'hasGroupLeaderScore' | 'markingGroupNumber'
> & {
  curDay: string
  hasGroupLeaderScore: string[]
  expand: string[]
  markingGroupNumber?: number | string
}

const useStatisticsFilter = () => {
  // console.log('dayList:', dayList)
  const {
    subjectList,
    mainQuestionList,
    groupListWithAll,
    changeModelValue,
    dataModel,
    onOptionInit,
    isExpert,
    isLeader,
  } = useOptions(['subject', 'question', 'group'], undefined, true, true, true)

  const curDayRange = getCurDayRange()
  const model = reactive<any>({
    subjectCode: dataModel.subject || '',
    questionMainNumber: dataModel.question,
    markingGroupNumber: dataModel.group,
    // time: [curDayRange[0], curDayRange[1]],
    curDay: getTodayByDay(),
    // hasGroupLeaderScore: ['true'],
    hasGroupLeaderScore: [],
    expand: [],
    markerId: '',
    online: '',
  })
  const { dayOptions } = useDayList(dataModel, true)
  watch(dayOptions, () => {
    model.curDay = getTodayByDay()
  })

  // const { fetch: getMarkerList, result: markerList } = useFetch('getMarkerList')
  const { fetch: getMarkerList, result: allMarkerList } = useFetch('getMarkerList')
  const markerList = computed(() => {
    let mgn = model.markingGroupNumber
    if (typeof mgn == 'number') {
      mgn = [mgn]
    }
    if ((mgn || []).includes(undefined) || typeof mgn === 'undefined') {
      return allMarkerList?.value || []
    } else {
      return (allMarkerList?.value || []).filter((item) => {
        return (mgn || []).includes(item.markingGroupNumber)
      })
    }
  })
  // watch(
  //   () => model.markingGroupNumber,
  //   () => {
  //     console.log('model.markingGroupNumber:', model.markingGroupNumber)
  //     if (Array.isArray(model.markingGroupNumber) && model.markingGroupNumber.includes(undefined)) {
  //       model.markingGroupNumber = [void 0]
  //     }
  //   }
  // )
  watch(
    () => [model.subjectCode, model.questionMainNumber, model.markingGroupNumber],
    () => {
      if (model.subjectCode && model.questionMainNumber) {
        getMarkerList({
          subjectCode: model.subjectCode,
          mainNumber: model.questionMainNumber,
          // markingGroupNumber: model.markingGroupNumber,
        })
        model.markerId = ''
      }
    },
    {
      immediate: true,
    }
  )
  // const fetchModel = computed<ExtractApiParams<'getStatisticsByGroup'> & { expand: boolean }>(() => {
  const fetchModel = computed<any>(() => {
    return Object.assign(omit(model, 'curDay'), {
      // startTime: model.time?.[0],
      // endTime: model.time?.[1],
      curDay: model.curDay,
      hasGroupLeaderScore: model.hasGroupLeaderScore.length > 0,
      expand: model.expand.length > 0,
      // markingGroupNumber:
      //   typeof model.markingGroupNumber === 'number' ? [model.markingGroupNumber] : model.markingGroupNumber,
      markingGroupNumber: model.markingGroupNumber,
    })
  })

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

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

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

  const OneRowSpan5 = defineColumn(_, 'row-1', { span: 5 })
  const OneRowSpan4 = defineColumn(_, 'row-1', { span: 4 })
  const OneRowSpan3 = defineColumn(_, 'row-1', { span: 3 })
  const OneRowSpan1 = defineColumn(_, 'row-1', { span: 1 })
  const TwoRowSpan5 = defineColumn(_, 'row-2', { span: 5 })
  const TwoRowSpan8 = defineColumn(_, 'row-2', { span: 8 })
  const TwoRowSpan3 = defineColumn(_, 'row-2', { span: 3 })
  const TwoRowSpan4 = defineColumn(_, 'row-2', { span: 4 })
  const TwoRowSpan2 = defineColumn(_, 'row-2', { span: 1.3 })

  const customGroupChange = (v: any) => {
    if (groupListWithAll.value.find((item: any) => item.value == undefined)) {
      if (model.markingGroupNumber.includes(undefined)) {
        model.markingGroupNumber = [void 0]
        changeModelValue('group')(model.markingGroupNumber)
      } else {
        changeModelValue('group')(v)
      }
    } else {
      changeModelValue('group')(v)
    }
  }
  const transGroupOptions = computed(() => {
    return (model.markingGroupNumber || []).includes(undefined)
      ? (groupListWithAll.value || []).map((item: any) => {
          item.value != undefined && (item.disabled = true)
          return item
        })
      : groupListWithAll.value.map((item: any) => {
          item.disabled = false
          return item
        })
  })

  const items = computed<EpFormItem[]>(() => [
    OneRowSpan4({
      labelWidth: '52px',
      label: '科目',
      prop: 'subjectCode',
      slotType: 'select',
      slot: {
        options: subjectList.value,
        onChange: changeModelValue('subject'),
        disabled: !isExpert.value,
      },
    }),
    OneRowSpan4({
      labelWidth: '52px',
      prop: 'questionMainNumber',
      label: '大题',
      slotType: 'select',
      slot: {
        options: mainQuestionList.value,
        onChange: changeModelValue('question'),
        disabled: !isExpert.value && !isLeader.value,
      },
    }),
    OneRowSpan4({
      labelWidth: '52px',
      prop: 'markingGroupNumber',
      label: '小组',
      slotType: 'select',
      slot: {
        options: transGroupOptions.value,
        onChange: customGroupChange,
        multiple: true,
      },
    }),
    OneRowSpan4({
      labelWidth: '65px',
      label: '评卷员',
      slotType: 'select',
      prop: 'markerId',
      slot: {
        options: [
          { label: '全部', value: '' },
          ...(markerList?.value || []).map((marker) => ({
            value: marker.id,
            label: marker.loginName ? `${marker.loginName}-${marker.name}` : marker.name,
          })),
        ],
        filterable: true,
        clearable: true,
      },
    }),
    OneRowSpan4({
      labelWidth: '20px',
      slotName: 'button-group',
    }),

    OneRowSpan4({
      labelWidth: '0px',
      slotName: 'columns-setting',
    }),
    // TwoRowSpan8({
    //   labelWidth: '52px',
    //   label: '时间',
    //   slotType: 'dateTime',
    //   prop: 'time',
    //   slot: {
    //     type: 'datetimerange',
    //     valueFormat: 'YYYYMMDDHHmmss',
    //     startPlaceholder: '开始时间',
    //     endPlaceholder: '结束时间',
    //   },
    // }),
    TwoRowSpan4({
      labelWidth: '52px',
      label: '时间',
      slotType: 'select',
      prop: 'curDay',
      slot: {
        options: dayOptions.value,
      },
    }),
    TwoRowSpan4({
      labelWidth: '52px',
      prop: 'online',
      label: '人员',
      slotType: 'select',
      slot: {
        options: [
          { label: '全部', value: '' },
          { label: '在线', value: true },
          { label: '离线', value: false },
        ],
      },
    }),
    TwoRowSpan2({
      prop: 'expand',
      label: '',
      slotType: 'checkbox',
      labelWidth: '15px',
      slot: {
        options: [{ label: '按人员展开' }],
      },
    }),
    TwoRowSpan3({
      prop: 'hasGroupLeaderScore',
      label: '',
      slotType: 'checkbox',
      labelWidth: '40px',
      slot: {
        options: [{ label: 'true', slotLabel: '包含组长给分' }],
      },
    }),
  ])

  return {
    formRef,
    elFormRef,
    model,
    fetchModel,
    items,
    rows,
    onOptionInit,
    groupListWithAll,
    changeModelValue,
  }
}

export default useStatisticsFilter
