<template>
  <div>
    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="分类名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入分类名称" />
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input-number
          style="width: 100%"
          v-model="form.sort"
          :min="1"
          :max="9999"
          label="请输入排序"
        ></el-input-number>
      </el-form-item>
      <el-form-item label="显示状态" prop="status">
        <el-select
          v-model="form.status"
          placeholder="请选择显示状态"
          style="width: 100%"
        >
          <el-option
            v-for="dict in statusOption"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          type="textarea"
          :rows="4"
          v-model="form.remark"
          placeholder="请输入备注"
        />
      </el-form-item>
    </el-form>
    <div style="text-align: right">
      <el-button type="primary" @click="handleConfirm">确 定</el-button>
      <el-button @click="handleCancel">取 消</el-button>
    </div>
  </div>
</template>

<script>
export default {
  props: {
    data: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    return {
      // 状态组
      statusOption: [
        { value: "0", label: "显示" },
        { value: "1", label: "隐藏" },
      ],
      form: {
        name: "",
        sort: "",
        status: "",
        remark: "",
      },
      rules: {
        name: [{ required: true, trigger: "blur", message: "请输入分类名称" }],
        sort: [{ required: true, trigger: "blur", message: "请输入排序" }],
        status: [
          { required: true, trigger: "change", message: "请选择显示状态" },
        ],
      },
    };
  },
  watch: {
    data: {
      handler(newVal) {
        if (newVal) {
          this.form = {
            id: newVal.id || "",
            name: newVal.name || "",
            sort: newVal.sort || "",
            status: newVal.status || "",
            remark: newVal.remark || "",
          };
          this.$nextTick(() => {
            this.$refs.form && this.$refs.form.clearValidate();
          });
        }
      },
    },
  },
  methods: {
    // 确定
    handleConfirm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.$emit("confirm", this.form);
        }
      });
    },
    // 取消
    handleCancel() {
      this.form = {
        name: "",
        sort: "",
        status: "",
        remark: "",
      };
      this.$nextTick(() => {
        this.$refs.form && this.$refs.form.clearValidate();
      });
      this.$emit("cancel");
    },
  },
};
</script>

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