<template>
  <div>
    <el-form ref="ruleFormRef" :model="state.ruleForm" :rules="state.rules" label-position="top" label-width="120px">
      <el-form-item label="任务名称" prop="name">
        <el-input v-model="state.ruleForm.name" maxlength="20" placeholder="请输入任务名称" show-word-limit />
      </el-form-item>
      <el-form-item label="任务描述" prop="desc">
        <el-input
          v-model="state.ruleForm.desc"
          type="textarea"
          maxlength="200"
          placeholder="请输入任务描述"
          :autosize="{
            minRows: 4,
          }"
          show-word-limit />
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { reactive, ref, onBeforeMount, toRefs } from "vue";
import { useRouter, useRoute } from "vue-router";
import { ElMessage } from "element-plus";
const router = useRouter();
const route = useRoute();

const props = defineProps({
  data: {
    type: Object,
    default: () => {},
  },
});

const ruleFormRef = ref(null);

const state = reactive({
  ruleForm: {
    name: props.data?.name || "",
    desc: props.data?.desc || "",
  },
  rules: {
    name: [
      { required: true, message: "请输入任务名称", trigger: "blur" },
      { max: 20, message: "最大长度20", trigger: "blur" },
    ],
    desc: [{ max: 200, message: "最大长度200", trigger: "blur" }],
  },
});

const save = () => {
  return new Promise((resolve, reject) => {
    ruleFormRef.value.validate((valid, fields) => {
      if (valid) {
        props.data.name = state.ruleForm.name;
        props.data.desc = state.ruleForm.desc;
        resolve();
      } else {
        reject();
        console.log("error submit!", fields);
      }
    });
  });
};

const clear = () => {
  ruleFormRef.value.resetFields();
};

defineExpose({
  save,
  clear,
});
</script>

<style scoped></style>
