<template>
  <div class="p-base full">
    <div class="flex direction-column fill-blank full radius-base p-base">
      <base-form
        ref="formRef"
        size="small"
        :model="taskSettingModel"
        :items="items"
        :rules="rules"
        :label-width="'120px'"
      >
        <template #form-item-un-mark>
          <span class="un-mark-count">{{ unMarkTasks?.unmarkCount ?? 0 }}</span>
        </template>
        <template #form-item-chooseMarkers>
          <choose-markers
            v-if="!isGroupSetting"
            :subject-code="taskSettingModel.subjectCode"
            :main-number="taskSettingModel.mainNumber"
            @user-list="onUserListChange"
          ></choose-markers>
        </template>
        <template #form-item-confirm>
          <el-button :loading="loading" type="primary" @click="onSubmit">{{
            isGroupSetting ? '确认追加' : '确定'
          }}</el-button>
        </template>
      </base-form>
      <div class="flex-1 overflow-hidden m-t-base">
        <!-- <component
          :is="TableComponent"
          v-bind="taskSettingModel"
          :key="refresh"
          @user-list="onUserListChange"
        ></component> -->
        <group-setting v-if="isGroupSetting" v-bind="taskSettingModel" :key="refresh"></group-setting>
        <marker-setting
          v-else
          v-bind="taskSettingModel"
          :filter-users="userIds"
          @user-list="onUserListChange"
        ></marker-setting>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts" name="DataTaskSetting">
/** 任务设置 */
import { ref, reactive, computed, watch, nextTick } from 'vue'
import { ElButton, ElMessage } from 'element-plus'
import useFetch from '@/hooks/useFetch'
import useOptions from '@/hooks/useOptions'
import useForm from '@/hooks/useForm'
import useVW from '@/hooks/useVW'
import BaseForm from '@/components/element/BaseForm.vue'
import GroupSetting from './components/GroupSetting.vue'
import MarkerSetting from './components/MarkerSetting.vue'
import ChooseMarkers from '@/components/common/ChooseMarkers.vue'
import bus from '@/utils/bus'
import { omit } from 'lodash-es'
import type { ExtractApiParams, ExtractMultipleApiResponse } from '@/api/api'
import type { EpFormRules, EpFormItem } from 'global-type'

type FormParams = ExtractApiParams<'markerSetCount'> &
  ExtractApiParams<'markGroupUpdateCount'> & { settingType: 'group' | 'marker' }

const refresh = ref<number>(0)

const { subjectList, mainQuestionList, groupList, groupListWithAll, changeModelValue, dataModel } = useOptions(
  ['subject', 'question', 'group'],
  undefined,
  true,
  true,
  true,
  false,
  false
)

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

const taskSettingModel = reactive<FormParams>({
  subjectCode: dataModel.subject,
  mainNumber: dataModel.question,
  markingGroupNumbers: dataModel.group,
  markCount: void 0,
  markDayCount: void 0,
  markTotalCount: void 0,
  userId: [],
  settingType: 'group',
})

const isGroupSetting = computed(() => taskSettingModel.settingType === 'group')

const TableComponent = computed(() => {
  return isGroupSetting.value ? GroupSetting : MarkerSetting
})

const { fetch: getUnMarkTasks, result: unMarkTasks } = useFetch('getUnMarkTasks')

watch(
  () => taskSettingModel.settingType,
  (val: string) => {
    if (val === 'group') {
      userList.value = []
    }
    setTimeout(() => {
      elFormRef?.value?.clearValidate()
    })
  }
)

watch(
  () => taskSettingModel.markingGroupNumbers,
  () => {
    if (taskSettingModel.markingGroupNumbers) {
      getUnMarkTasks({
        subjectCode: taskSettingModel.subjectCode,
        mainNumber: taskSettingModel.mainNumber,
        markingGroupNumbers: taskSettingModel.markingGroupNumbers,
      })
    }
  }
)

watch(dataModel, () => {
  taskSettingModel.subjectCode = dataModel.subject
  taskSettingModel.mainNumber = dataModel.question
  taskSettingModel.markingGroupNumbers = dataModel.group
})

const Span7 = defineColumn(_, '', { span: 7 })
const customGroupChange = (v: any) => {
  if (groupListWithAll.value.find((item: any) => item.value == undefined)) {
    if (taskSettingModel.markingGroupNumbers?.includes(undefined)) {
      taskSettingModel.markingGroupNumbers = [void 0]
      changeModelValue('group')(taskSettingModel.markingGroupNumbers)
    } else {
      changeModelValue('group')(v)
    }
  } else {
    changeModelValue('group')(v)
  }
}
const transGroupOptions = computed(() => {
  // return (taskSettingModel.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[]>(() => [
  Span7({
    rowKey: 'row-1',
    label: '科目',
    prop: 'subjectCode',
    slotType: 'select',
    slot: { options: subjectList.value, onChange: changeModelValue('subject') },
  }),
  Span7({
    rowKey: 'row-1',
    label: '大题',
    prop: 'mainNumber',
    slotType: 'select',
    slot: { options: mainQuestionList.value, onChange: changeModelValue('question') },
  }),
  Span7({
    rowKey: 'row-2',
    label: '任务设置对像',
    prop: 'settingType',
    slotType: 'select',
    slot: {
      options: [
        { label: '按小组追加', value: 'group' },
        { label: '按评卷员设置', value: 'marker' },
      ],
    },
  }),
  Span7({
    rowKey: 'row-2',
    label: '小组',
    prop: 'markingGroupNumbers',
    slotType: 'select',
    hidden: !isGroupSetting.value,
    slot: {
      // options: groupList.value,
      onChange: changeModelValue('group'),
      // multiple: true,
      options: transGroupOptions.value,
      // onChange: customGroupChange,
      multiple: true,
    },
  }),
  Span7({
    rowKey: 'row-2',
    label: '任务余量',
    slotName: 'un-mark',
    hidden: !isGroupSetting.value,
  }),
  Span7({
    rowKey: 'row-2',
    label: '评卷员',
    slotName: 'chooseMarkers',
    hidden: isGroupSetting.value,
    prop: 'userId',
  }),
  Span7({
    rowKey: 'row-3',
    label: '任务数设置',
    prop: 'markTotalCount',
    slotType: 'inputNumber',
    slot: {
      step: 1,
      stepStrictly: true,
    },
    hidden: isGroupSetting.value,
  }),
  Span7({
    rowKey: 'row-3',
    label: '每日任务量',
    prop: 'markDayCount',
    slotType: 'inputNumber',
    slot: {
      step: 1,
      stepStrictly: true,
    },
    hidden: isGroupSetting.value,
  }),
  Span7({
    rowKey: 'row-3',
    label: '统一追加量',
    prop: 'markCount',
    slotType: 'inputNumber',
    slot: {
      step: 1,
      stepStrictly: true,
    },
    hidden: !isGroupSetting.value,
  }),
  Span7({ rowKey: 'row-3', slotName: 'confirm' }),
])

const rules = computed<EpFormRules>(() => {
  const obj: EpFormRules = {
    subjectCode: [{ required: true, message: '请选择科目' }],
    mainNumber: [{ required: true, message: '请选择大题' }],
  }
  if (isGroupSetting.value) {
    obj['markingGroupNumbers'] = [
      { required: true, message: '请选择小组', trigger: 'blur' },
      {
        validator: (rule: any, value: any, callback: any) => {
          if (!taskSettingModel.markingGroupNumbers?.length) {
            callback(new Error('请选择小组'))
          } else {
            callback()
          }
        },
        trigger: 'blur',
      },
    ]
    obj['markCount'] = [{ required: true, message: '请设置统一追加量' }]
  } else {
    obj['markTotalCount'] = [
      { required: true, message: '请设置任务数' },
      { type: 'number', min: 0, max: 999999, message: '任务数限制0-999999之间' },
    ]
    obj['markDayCount'] = [
      { required: true, message: '请设置每日任务量' },
      { type: 'number', min: 0, max: 999999, message: '每日任务量限制0-999999之间' },
    ]
    obj['userId'] = [
      { required: true, message: '请选择评卷员', trigger: 'blur' },
      {
        validator: (rule: any, value: any, callback: any) => {
          console.log('taskSettingModel.userId', taskSettingModel.userId)
          if (!taskSettingModel.userId?.length) {
            callback(new Error('请选择评卷员'))
          } else {
            callback()
          }
        },
        trigger: 'blur',
      },
    ]
  }
  return obj
})

const userList = ref<ExtractMultipleApiResponse<'getUserList'>[]>([])

const userIds = computed(() => {
  return userList.value?.map((u) => u.id) || []
})
watch(userIds, () => {
  taskSettingModel.userId = [...(userIds.value || [])]
})
const onUserListChange = (list: ExtractMultipleApiResponse<'getUserList'>[]) => {
  userList.value = list || []
  nextTick(() => {
    elFormRef?.value?.validateField('userId')
  })
}
const loading = ref<boolean>(false)
/** 按评卷员设置 */
const onMarkerSetCount = async () => {
  loading.value = true
  try {
    taskSettingModel.userId = userIds.value
    await useFetch('markerSetCount')
      .fetch(omit(taskSettingModel, 'markingGroupNumbers'))
      .then(() => {
        bus.emit('updateMarkerSetting')
      })
  } catch (error) {
    console.error(error)
  } finally {
    loading.value = false
  }
}

/** 按小组追加 */

const onMarkGroupUpdateCount = async () => {
  loading.value = true
  try {
    await useFetch('markGroupUpdateCount').fetch(taskSettingModel)
  } catch (error) {
    console.error(error)
  } finally {
    loading.value = false
  }
}

const onSubmit = async () => {
  try {
    const valid = await elFormRef?.value?.validate()
    if (valid) {
      await (isGroupSetting.value ? onMarkGroupUpdateCount() : onMarkerSetCount())
    }
    ElMessage.success('设置成功')
    Object.assign(taskSettingModel, { markCount: void 0, markDayCount: void 0, markTotalCount: void 0, userId: [] })
    setTimeout(() => {
      elFormRef?.value?.clearValidate()
      refresh.value++
    })
  } catch (error) {
    console.error(error)
  }
}
</script>

<style scoped lang="scss">
.un-mark-count {
  color: $DangerColor;
  font-size: $MediumFont;
}
</style>
