<template>
  <div>
    <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="100px" class="demo-ruleForm">
      <el-form-item label="banner名字" prop="banner_name">
        <el-input v-model="ruleForm.banner_name" />
      </el-form-item>
      <el-form-item label="上传图片" prop="banner_img">
        <file-upload-progress v-model:part="ruleForm.banner_img" :limit="1" accept=".png,.jpg,.jpeg" :size-limit="200">
          <template #default>
            <div class="flex_center w-65px h-65px border border-dashed border-hex-E4E6E8 bg-hex-F9F9F9 text-hex-9D9AB9">
              <i-akar-icons:plus class="text-xl" />
            </div>
          </template>
          <template #tip>
            <div class="mt-2">支持格式：jpg,png,jpeg（200kb以内） 建议尺寸12:5</div>
          </template>
        </file-upload-progress>
      </el-form-item>
      <el-form-item label="顺序" prop="banner_sort">
        <el-input v-model="ruleForm.banner_sort" :min="0" type="number" />
      </el-form-item>
      <div class="btnDiv" style="text-align: center;">
        <el-button @click="emit('update', 2)">取消</el-button>
        <el-button type="primary" @click="submitForm(ruleFormRef)">确定</el-button>
      </div>
    </el-form>
  </div>
</template>

<script setup>
import { reactive, ref, watch } from "vue";

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

const ruleFormRef = ref();
const ruleForm = reactive({
  banner_name: "",
  banner_img: "",
  banner_sort: ""
})

const rules = reactive({
  banner_name: [{ required: true, message: "请输入banner名字", trigger: "blur" }],
  banner_img: [{ required: true, message: "请上传图片", trigger: "submit" }],
  banner_sort: [{ required: true, message: "请输入顺序", trigger: "blur" }],
});

function init() {
  for (let key in props.editForm) {
    ruleForm[key] = props.editForm[key];
  }
}

const emit = defineEmits(["update", "data"]);
const submitForm = (formEl) => {
  if (!formEl) return;
  formEl.validate((valid, fields) => {
    if (valid) {
      emit("data", ruleForm);
    } else {
      console.log("error submit!", fields);
    }
  });
};

const resetForm = (formEl) => {
  if (!formEl) return;
  formEl.resetFields();
};

watch(
  () => props.editForm,
  (newVal, oldVal) => {
    if (!newVal) {
      resetForm(ruleFormRef);
    } else {
      init();
    }
  },
  { immediate: true }
);
</script>

<style>
</style>