<template>
  <el-form :model="formData" :rules="formRules" ref="form" style="max-width: 1048px" class="form">
    <el-form-item label="banner名称" prop="banner_name">
      <el-input v-model.trim="formData.banner_name" show-word-limit maxlength="30" />
    </el-form-item>
    <el-form-item label="链接地址（选填）" prop="link_address">
      <el-input v-model.trim="formData.link_address" />
    </el-form-item>
    <el-form-item label="上传banner图片" prop="banner_image">
      <bg-upload-image
        v-model="formData.banner_image"
        :fileSize="1"
        :showTips="true"
        customTips="请选择图片上传：大小1920 * 464像素支持jpg、jpeg、png格式，图片需小于1MB"
        :limit="1"
        listType="picture-card"
        @change="changeLogo"
        :accept="['.jpg', '.jpeg', '.png']"></bg-upload-image>
    </el-form-item>
    <el-form-item label="是否启用" prop="state" class="state_form_item">
      <bg-switch :labels="['否', '是']" :values="[0, 1]" v-model="formData.state"></bg-switch>
    </el-form-item>
  </el-form>
</template>

<script setup>
import { reactive, toRefs, ref, onBeforeMount, nextTick } from "vue";
import axios from "../../../../../request/http.js";
import { ElMessage } from "element-plus";
import { useRoute, useRouter } from "vue-router";
const router = useRouter();
const route = useRoute();
const form = ref(null);
const state = reactive({
  formData: {
    banner_name: "",
    link_address: "",
    banner_image: [],
    state: 1,
  },
  formRules: {
    banner_name: [{ required: true, message: "请输入banner名称", trigger: "blur" }],
    link_address: [{ max: 8182, message: "最长可输入8182个字符", trigger: "blur" }],
    banner_image: [{ required: true, message: "请上传banner图", trigger: "change" }],
    state: [{ required: true, message: "请选择启用状态", trigger: "change" }],
  },
});

const changeLogo = (value) => {
  if (value && value.length > 0) {
    form.value.clearValidate("banner_image");
  }
};

const emit = defineEmits(["action"]);

const submitForm = async () => {
  if (!form) return;
  await form.value.validate((valid, fields) => {
    if (valid) {
      emit("action", state.formData);
    } else {
      emit("action", null);
    }
  });
};

const clearForm = () => {
  if (!form) return;
  form.value.resetFields();
};

const setForm = (data) => {
  Object.assign(state.formData, data);
};

onBeforeMount(() => {});

const { formData, formRules } = toRefs(state);

defineExpose({ submitForm, clearForm, setForm });
</script>

<style lang="scss" scoped>
.form {
  .el-form-item {
    display: block;
  }
  .state_form_item {
    display: flex;
  }
  :deep().bg-upload {
    .el-upload--picture-card {
      width: 800px;
      height: 194px;
      background-color: #fff;
      border: 1px solid #dadee7;
    }
    .el-upload-list--picture-card .el-upload-list__item {
      width: 800px;
      height: 194px;
    }
  }
}
</style>
