<script setup lang="ts">
import { ref, unref, watch } from "vue";
import { REMARK_MAX_LENGTH } from "/@/utils/global";
import { defaultRules } from "./_rules";
import { ElForm } from "element-plus";

const emit = defineEmits(["approval"]);
const props = defineProps<{ approveValue: string; rejectValue: string; }>();

const formRef = ref<InstanceType<typeof ElForm> | null>(null);
const formData = ref({ status: "", remark: "" });
const rules = ref({ ...defaultRules });

async function handleApproval() {
  try{
    await formRef.value?.validate()
    emit("approval", unref(formData))
  }catch(err){
    console.log(err)
  }
}

watch(
  () => formData.value,
  ({ status }) => { rules.value.remark[0].required = (status === props.rejectValue); },
  { deep: true }
);
</script>

<template>
  <ElForm ref="formRef" :model="formData" :rules="rules" label-width="100px">
    <div flex flex-col style="width: 50%">
      <ElFormItem label="审核状态" prop="status">
        <ElSelect placeholder="请选择审核状态" v-model="formData.status">
          <ElOption :value="approveValue" label="通过" />
          <ElOption :value="rejectValue" label="驳回" />
        </ElSelect>
      </ElFormItem>

      <ElFormItem label="备注" prop="remark">
        <ElInput
          :rows="5"
          type="textarea"
          placeholder="请输入备注"
          v-model="formData.remark"
          v-bind="REMARK_MAX_LENGTH"
        />
      </ElFormItem>
    </div>

    <ElFormItem>
      <div class="w-full flex justify-end">
        <ElButton type="primary" @click="handleApproval">
          提交审核结果
        </ElButton>
      </div>
    </ElFormItem>
  </ElForm>
</template>
