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

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

const useFormFilter = () => {
  const {
    subjectList,
    mainQuestionList,
    groupListWithAll,
    dataModel,
    onOptionInit,
    changeModelValue,
    isExpert,
    isLeader,
  } = useOptions(['subject', 'question', 'group'], undefined, true, true, true)

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

  const model = reactive<ExtractApiParams<'getTrainingMonitor'> & { diffShow: string[] }>({
    subjectCode: dataModel.subject || '',
    mainNumber: dataModel.question,
    markingGroupNumbers: dataModel.group,
    markStage: 'SAMPLE_A',
    forceGroupNumber: void 0,
    diffShow: [],
    dispenseRound: void 0,
  })

  const diffShow = computed(() => {
    return !!model.diffShow.length
  })

  const forceGroupListParams = computed(() => {
    return {
      subjectCode: model.subjectCode,
      questionMainNumber: model.mainNumber,
    }
  })

  const { fetch: getForceCheckGroupList, result: forceCheckGroupListResult } = useFetch('getForceCheckGroupList')
  const { fetch: getDispenseRound, result: roundList } = useFetch('getDispenseRound')

  const forceCheckGroup = computed(() =>
    forceCheckGroupListResult?.value?.map((group) => {
      return { ...group, value: group.forceGroupNumber, label: `第${group.forceGroupNumber}组` }
    })
  )

  watch(
    forceGroupListParams,
    () => {
      if (model.subjectCode && model.mainNumber) {
        getForceCheckGroupList({ subjectCode: model.subjectCode, mainNumber: model.mainNumber })
      }
    },
    { immediate: true }
  )

  watch(
    dataModel,
    () => {
      model.subjectCode = dataModel.subject || ''
      model.mainNumber = dataModel.question
      model.markingGroupNumbers = dataModel.group
    },
    { deep: true }
  )

  // watch(
  //   [forceCheckGroup, model],
  //   () => {
  //     if (forceCheckGroup.value?.length && !model.forceGroupNumber) {
  //       model.forceGroupNumber = forceCheckGroup.value[0].value
  //     }
  //   },
  //   { deep: true, immediate: true }
  // )
  watch(
    [forceCheckGroup],
    () => {
      model.dispenseRound = void 0
      if (forceCheckGroup.value?.length) {
        model.forceGroupNumber = forceCheckGroup.value[0].value
      } else {
        model.forceGroupNumber = void 0
      }
    },
    { deep: true, immediate: true }
  )
  watch(
    () => model.forceGroupNumber,
    () => {
      model.dispenseRound = void 0
      if (model.forceGroupNumber) {
        getDispenseRound({
          forceGroupNumber: model.forceGroupNumber,
          subjectCode: model.subjectCode,
          mainNumber: model.mainNumber,
        })
      }
    }
  )

  const rules = computed<EpFormRules>(() => {
    return {
      forceGroupNumber: model.markStage === 'FORCE' ? [{ required: true, message: '请选择强制考核组' }] : [],
      dispenseRound: !!model.forceGroupNumber ? [{ required: true, message: '请选择考核轮次' }] : [],
    }
  })

  const isSmallScreen = window.innerWidth < 1300
  // let isMiddleScreen = window.innerWidth<1400;
  const OneRowSpan2 = defineColumn(_, 'row-1', { span: 2 })
  const OneRowSpan3 = defineColumn(_, 'row-1', { span: 3 })
  const OneRowSpan4 = defineColumn(_, 'row-1', { span: 4 })
  const OneRowSpan5 = defineColumn(_, 'row-1', { span: 5 })
  // const TwoRowSpan5 = defineColumn(_, 'row-2', { span: 5 })

  const customGroupChange = (v: any) => {
    if (groupListWithAll.value.find((item: any) => item.value == undefined)) {
      if (model.markingGroupNumbers.includes(undefined)) {
        model.markingGroupNumbers = [void 0]
        changeModelValue('group')(model.markingGroupNumbers)
      } else {
        changeModelValue('group')(v)
      }
    } else {
      changeModelValue('group')(v)
    }
  }
  const transGroupOptions = computed(() => {
    // return (model.markingGroupNumbers || []).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
    //     })
    return groupListWithAll.value || []
  })

  const items = computed<EpFormItem[]>(() => {
    return [
      OneRowSpan3({
        label: '科目',
        prop: 'subjectCode',
        slotType: 'select',
        labelWidth: '38px',
        slot: {
          options: subjectList.value,
          onChange: changeModelValue('subject'),
          disabled: !isExpert.value,
        },
      }),
      OneRowSpan3({
        prop: 'mainNumber',
        label: '大题',
        slotType: 'select',
        labelWidth: '50px',
        slot: {
          options: mainQuestionList.value,
          onChange: changeModelValue('question'),
          disabled: !isExpert.value && !isLeader.value,
        },
      }),
      OneRowSpan4({
        prop: 'markingGroupNumbers',
        label: '小组',
        slotType: 'select',
        labelWidth: '50px',
        slot: {
          options: transGroupOptions.value,
          onChange: changeModelValue('group'),
          multiple: true,
          collapseTags: model.markingGroupNumbers?.includes(undefined),
        },
      }),

      OneRowSpan4({
        label: '试卷类型',
        slotType: 'select',
        prop: 'markStage',
        labelWidth: '72px',
        slot: {
          placeholder: '试卷类型',
          options: [
            { label: 'SAMPLE_A', value: 'SAMPLE_A' },
            { label: 'SAMPLE_B', value: 'SAMPLE_B' },
            { label: '强制考核卷', value: 'FORCE' },
          ],
        },
      }),
      model.markStage === 'FORCE'
        ? OneRowSpan4({
            label: '强制考核组',
            slotType: 'select',
            prop: 'forceGroupNumber',
            labelWidth: '86px',
            slot: {
              placeholder: '强制考核组',
              options: forceCheckGroup.value,
            },
          })
        : null,
      model.markStage === 'FORCE' && !isNaN(model.forceGroupNumber as number)
        ? OneRowSpan2({
            label: '',
            labelWidth: '5px',
            slotType: 'select',
            prop: 'dispenseRound',
            slot: {
              placeholder: '考核轮次',
              options: roundList.value.map((item: any) => {
                item.value = item.round
                return item
              }),
            },
          })
        : null,
      OneRowSpan2({
        label: '差值展示',
        slotType: 'checkbox',
        labelWidth: 70,

        prop: 'diffShow',
        slot: { options: [{ label: '是' }] },
      }),
      OneRowSpan2({
        labelWidth: 20,
        slotName: 'operation',
      }),
    ].filter(Boolean) as EpFormItem[]
  })

  return {
    formRef,
    elFormRef,
    model,
    diffShow,
    items,
    rules,
    onOptionInit,
  }
}

export default useFormFilter
