<template>
  <el-dialog
    v-model="visible"
    title="一键未选做"
    width="500px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    top="10vh"
    append-to-body
    @close="handleClose"
    @open="modalBeforeOpen"
  >
    <div class="unselective-content">
      <div class="checkbox-section">
        <el-checkbox v-model="formModel.enableOneKeyUnselective">
          启用一键未选做
        </el-checkbox>
      </div>

      <div class="warning-text">
        <p>
          *启用一键未选做后，当前科目所有选做题给分板下均支持一键未选做的操作。
        </p>
      </div>
    </div>

    <template #footer>
      <el-button @click="close">取消</el-button>
      <el-button type="primary" :loading="loading" @click="confirm">
        确认
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
  import { reactive } from 'vue';
  import { ElMessage } from 'element-plus';
  import useModal from '@/hooks/modal';
  import useLoading from '@/hooks/loading';
  import { setSubjectUnselectiveConfig } from '@/api/subject';

  defineOptions({
    name: 'SetUnselectiveDialog',
  });

  /* modal */
  const { visible, open, close } = useModal();
  defineExpose({ open, close });

  interface Props {
    subjectCode?: string; // 科目代码
    value: boolean;
  }

  const props = withDefaults(defineProps<Props>(), {
    subjectCode: '',
    value: false,
  });

  const emit = defineEmits(['modified']);

  interface FormModel {
    subjectCode: string;
    enableOneKeyUnselective: boolean;
  }

  const initialFormState: FormModel = {
    subjectCode: '',
    enableOneKeyUnselective: false,
  };

  const formModel = reactive<FormModel>({ ...initialFormState });

  const handleClose = () => {
    Object.assign(formModel, initialFormState);
  };

  /* confirm */
  const { loading, setLoading } = useLoading();
  async function confirm() {
    setLoading(true);

    try {
      await setSubjectUnselectiveConfig({
        subjectCode: formModel.subjectCode,
        enableOneKeyUnselective: formModel.enableOneKeyUnselective,
      });

      ElMessage.success(
        formModel.enableOneKeyUnselective
          ? '启用一键未选做成功！'
          : '关闭一键未选做成功！'
      );
      emit('modified');
      close();
    } catch (error) {
      ElMessage.error('操作失败，请重试');
    } finally {
      setLoading(false);
    }
  }

  /* init modal */
  function modalBeforeOpen() {
    formModel.subjectCode = props.subjectCode;
    formModel.enableOneKeyUnselective = props.value;
  }
</script>

<style scoped>
  .unselective-content {
    padding: 20px 0;
  }

  .checkbox-section {
    margin-bottom: 20px;
  }

  .warning-text {
    font-size: 14px;
    line-height: 1.5;
    color: var(--color-danger);
  }
</style>
