<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="useVW(120)"
      >
        <template #form-item-un-mark>
          <span class="un-mark-count">{{ unMarkTasks?.unmarkCount }}</span>
        </template>
        <template #form-item-confirm>
          <el-button 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>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts" name="DataTaskSetting">
/** 任务设置 */
import { ref, reactive, computed, watch } 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 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, changeModelValue, dataModel } = useOptions([
  'subject',
  'question',
  'group',
])

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

const taskSettingModel = reactive<FormParams>({
  subjectCode: dataModel.subject,
  mainNumber: dataModel.question,
  markingGroupNumber: 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,
  () => {
    setTimeout(() => {
      elFormRef?.value?.clearValidate()
    })
  }
)

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

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

const Span7 = defineColumn(_, '', { span: 7 })

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: 'markingGroupNumber',
    slotType: 'select',
    hidden: !isGroupSetting.value,
    slot: {
      options: groupList.value,
      onChange: changeModelValue('group'),
    },
  }),
  Span7({
    rowKey: 'row-2',
    label: '任务余量',
    slotName: 'un-mark',
    hidden: !isGroupSetting.value || !unMarkTasks?.value?.unmarkCount,
  }),
  Span7({
    rowKey: 'row-3',
    label: '任务数设置',
    prop: 'markTotalCount',
    slotType: 'input',
    hidden: isGroupSetting.value,
  }),
  Span7({
    rowKey: 'row-3',
    label: '每日任务量',
    prop: 'markDayCount',
    slotType: 'input',
    hidden: isGroupSetting.value,
  }),
  Span7({ rowKey: 'row-3', label: '统一追加量', prop: 'markCount', slotType: 'input', 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['markingGroupNumber'] = [{ required: true, message: '请选择小组' }]
    obj['markCount'] = [{ required: true, message: '请设置统一追加量' }]
  } else {
    obj['markTotalCount'] = [{ required: true, message: '请设置任务数' }]
    obj['markDayCount'] = [{ required: true, message: '请设置每日任务量' }]
  }
  return obj
})

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

const userIds = computed(() => {
  return userList.value?.map((u) => u.id) || []
})

const onUserListChange = (list: ExtractMultipleApiResponse<'getUserList'>[]) => {
  userList.value = list || []
}

/** 按评卷员设置 */
const onMarkerSetCount = async () => {
  try {
    taskSettingModel.userId = userIds.value
    await useFetch('markerSetCount').fetch(taskSettingModel)
  } catch (error) {
    console.error(error)
  }
}

/** 按小组追加 */

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

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>
