<template>
  <BasicDialog ref="basicDialogRef" title="提交审批" @refresh="refreshFromData">
    <template #form>
      <el-form ref="formRef" :model="formData" label-width="auto">
        <el-form-item
          label="审批："
          prop="approvalStatus"
          :rules="{ required: true, message: '请选择', trigger: 'change' }"
        >
          <el-radio-group v-model="formData.approvalStatus">
            <el-radio :value="2">通过</el-radio>
            <el-radio :value="3">退回</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          v-if="formData.approvalStatus === 3"
          label="退回原因："
          prop="returnReason"
          :rules="{ required: true, message: '请选择', trigger: 'change' }"
        >
          <el-input v-model="formData.returnReason" placeholder="请输入退回原因" />
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <el-button type="primary" @click="handleSumbit">提交</el-button>
      <el-button @click="closeDialog">取消</el-button>
    </template>
  </BasicDialog>
</template>

<script setup lang="ts">
  import { approveDrillRecord } from '@/api/emergency-drill/emergency-drill';
  import BasicDialog from '@/components/BasicDialog.vue';
  import { ElMessage } from 'element-plus';
  import { reactive, ref } from 'vue';

  const props = defineProps<{
    id: number;
    status: number;
  }>();
  const emits = defineEmits<{
    (e: 'success'): void;
  }>();

  const formRef = ref();

  const formData = reactive<{ approvalStatus: number | null; returnReason: string }>({
    approvalStatus: null,
    returnReason: '',
  });

  const basicDialogRef = ref<InstanceType<typeof BasicDialog>>();
  const openDialog = () => {
    basicDialogRef.value?.openDialog();
  };

  const closeDialog = () => {
    clearForm();
    basicDialogRef.value?.closeDialog();
  };

  function clearForm() {
    formData.approvalStatus = null;
    formData.returnReason = '';
  }

  const refreshFromData = () => {
    formRef.value?.clearValidate();
  };
  const handleSumbit = async () => {
    const validate = await new Promise((resolve) => {
      formRef.value?.validate((valid: boolean) => {
        resolve(valid);
      });
    });
    if (!validate) return;
    try {
      if (!formData.approvalStatus) throw new Error('请选择审批状态');
      await approveDrillRecord({
        drillPlanId: props.id,
        approvalStatus: formData.approvalStatus,
        returnReason: formData.returnReason,
      });
      ElMessage.success('审批成功');
      emits('success');
    } catch (e) {
      ElMessage.error('审批失败');
    }
  };

  defineExpose({
    openDialog,
    closeDialog,
  });
</script>

<style scoped lang="scss">
  .el-form {
    display: flex;
    flex-direction: column;
    width: 600px;
    min-height: 100px;
    height: 100%;
    gap: 32px;

    .el-form-item {
      margin-bottom: 0;
    }

    :deep(.el-form-item__label) {
      padding: 0;
      min-width: 80px;
    }
  }
</style>
