<template>
  <base-dialog v-model="visible" title="打回说明" :footer="false" destroy-on-close>
    <base-form ref="formRef" :model="model" :items="items" :rules="rules" :label-width="useVW(72)">
      <el-form-item>
        <confirm-button @confirm="onSendBack" @cancel="onCancel"></confirm-button>
      </el-form-item>
    </base-form>
  </base-dialog>
</template>

<script setup lang="ts" name="SendBackMark">
/** 打回弹窗 */
import { reactive, withDefaults, watch } from 'vue'
import { ElFormItem } from 'element-plus'
import BaseDialog from '@/components/element/BaseDialog.vue'
import BaseForm from '../element/BaseForm.vue'
import ConfirmButton from '../common/ConfirmButton.vue'
import useVModel from '@/hooks/useVModel'
import useForm from '@/hooks/useForm'
import useFetch from '@/hooks/useFetch'
import useVW from '@/hooks/useVW'

import type { EpFormItem } from 'global-type'

const emits = defineEmits<{
  (e: 'rejected'): void
}>()

const props = withDefaults(
  defineProps<{
    modelValue: boolean
    id: number | undefined
    // 问题卷 | 系统抽查 | 自查卷
    type?: 'problem' | 'system-check' | 'self-check'
  }>(),
  { type: 'problem' }
)

const visible = useVModel(props)

const { formRef, elFormRef } = useForm()

const model = reactive({
  reason: '',
  description: '',
})

watch(visible, () => {
  if (!visible.value) {
    elFormRef?.value?.resetFields()
  }
})

const rules = {
  reason: [{ required: true, message: '请选择打回原因' }],
}

const reason = ['给分太高', '给分太低', '注意,评分偏紧', '注意,评分偏松', '评分不稳定,请认真评卷'].map((v) => ({
  label: v,
  value: v,
}))

const items: EpFormItem[] = [
  { label: '打回原因', prop: 'reason', slotType: 'select', slot: { options: reason } },
  { label: '说明', prop: 'description', slotType: 'input', slot: { type: 'textarea' } },
]

const { fetch: rejectMarkHistory } = useFetch('rejectMarkHistory')

const { fetch: rejectSystemSpotPaper } = useFetch('rejectSystemSpotPaper')

const { fetch: rejectSelfCheckData } = useFetch('rejectSelfCheckData')

const ApiMap = {
  problem: rejectMarkHistory,
  'system-check': rejectSystemSpotPaper,
  'self-check': rejectSelfCheckData,
}

const onSendBack = async () => {
  try {
    if (!props.id) {
      return
    }
    const valid = await elFormRef?.value?.validate()
    if (valid) {
      await ApiMap[props.type]({ description: model.description, reason: model.reason, id: props.id })
    }
    visible.value = false
    emits('rejected')
  } catch (error) {
    console.error(error)
  }
}

const onCancel = () => {
  visible.value = false
}
</script>

<style scoped lang="scss"></style>
