<script setup lang="ts">
import { useTabbarStore, useUserStore } from '@vben/stores'

import {
  questionService,
  status_approving,
  status_draft,
  status_rejected,
  status_reviewed,
  status_reviewing,
} from '#/api/service/question-bank/question'
import { router } from '#/router'
import hud from '#/utils/hud'

defineOptions({ name: 'OptionButtons' })

const tabStore = useTabbarStore()
const { userInfo } = storeToRefs(useUserStore())
const route = useRoute()

// 表单数据
const {
  formRef,
  editQuestion,
  formDisabled,
  baseDataRef,
  stemDataRef,
  answerDataRef,
} = inject('sharedData') as any

// 保存题目
function handleSave(status: any) {
  if (editQuestion.value?.id) {
    // 编辑
    const userId = userInfo.value.id
    const info = questionService.canSubmit(
      {
        ...editQuestion.value,
        status,
      },
      userId,
    )
    if (typeof info === 'string') {
      hud.error(info)
      return
    }
  }
  formRef.value?.validate((valid: any) => {
    if (valid) {
      saveQuestion(status)
    }
  })
}

function saveQuestion(status: any) {
  const basicData = baseDataRef.value.submit()
  if (!basicData) return

  const stemData = stemDataRef.value.submit()
  if (!stemData) return

  const answerData = answerDataRef.value.submit()
  if (!answerData) return

  const data = {
    ...basicData,
    ...stemData,
    ...answerData,
    status,
    id: editQuestion.value.id,
  }

  // 保存
  hud.load({
    task: async () => {
      await questionService.saveOrUpdate(data)
      tabStore.closeTabByKey(route.fullPath, router)
      router.push('/question-bank/question-mgr')
    },
    option: '保存',
    hideSuccess: false,
  })
}
</script>

<template>
  <div v-if="!formDisabled" class="form-actions">
    <!-- <el-button size="large" @click="resetForm">重置</el-button> -->
    <template
      v-if="
        !editQuestion?.id ||
        editQuestion.status === status_draft ||
        editQuestion.status === status_rejected
      "
    >
      <el-button type="primary" size="large" @click="handleSave(status_draft)">
        保存草稿
      </el-button>
      <el-button
        type="success"
        size="large"
        @click="handleSave(status_approving)"
      >
        提交审核
      </el-button>
    </template>
    <template v-if="editQuestion?.status === status_approving">
      <el-button
        size="large"
        type="success"
        @click="handleSave(status_reviewing)"
      >
        审核通过
      </el-button>
    </template>
    <template v-if="editQuestion?.status === status_reviewing">
      <el-button
        size="large"
        type="success"
        @click="handleSave(status_reviewed)"
      >
        复核通过
      </el-button>
    </template>
  </div>
</template>

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