<template>
  <el-dialog :title="title" width="500px" :visible.sync="dialogVisible" @close="diaClose"
    :close-on-click-modal="true">
    <div >
      <el-form ref="form" :rules="rules" :model="form" label-width="100px">
        <el-form-item label="标题"  prop="title">
          <el-input v-model="form.title"></el-input>
        </el-form-item>
        <el-form-item label="内容"  prop="content">
          <el-input v-model="form.content" type="textarea"></el-input>
        </el-form-item>
        <el-form-item label="状态" required>
          <el-switch v-model="form.state" :active-value="1" :inactive-value="0"></el-switch>
        </el-form-item>
      </el-form>
    </div>

    <div class="dialog-footer">
      <el-button @click="diaClose">取 消</el-button>
      <el-button type="primary" @click="confirm">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import {$announcement as  $api} from "@/api/announcement.js";

export default {
  data() {
    return {
      dialogVisible: false,
      title: "",
      rules: {
        title: [{ required: true, message: "请输入公告标题", trigger: "blur" }],
        content: [{ required: true, message: "请输入公告内容", trigger: "blur" }],
      },
      form: {
        title:'',
        content:'',
        state:1,
      },
    };
  },
  methods: {
    open(item) {
      console.log(item);
      this.dialogVisible = true;
      Object.assign(this.form, item);
      this.title = item ? "修改公告" : "添加公告";
    },
    diaClose() {
      this.dialogVisible = false;
      this.form = {
        title:'',
        content:'',
        state:1,
      };
      this.$refs.form.resetFields();
    },
    async confirm() {
      if (!this.form.title) {
        return this.$message.error("请输入公告标题");
      }
      if (!this.form.content) {
        return this.$message.error("请输入公告内容");
      }
      this.submit();
    },
    async submit() {
      let res = { data: { code: 1 } };
      const submitForm = {
        ...this.form,
      };
      if (this.form.id) {
        res = await $api.update(submitForm);
      } else {
        res = await $api.add(submitForm);
      }
      console.log(res);
      const { data } = res;
      if (data.code == 0) {
        this.$message.success(this.form.id ? "修改成功" : "添加成功");
        this.$emit("refresh");
        this.diaClose();
      } else {
        this.$message.error(data.msg);
      }
    },
  },
};
</script>
<style scoped lang="scss">
.el-form-item__label {
  text-align: left;
}

::v-deep .el-form-item__label {
  text-align: left;
}

.dialog-footer {
  padding-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.upload-file-box {
  border-radius: 6px;
  width: 148px;
  height: 148px;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
  border: 1px solid #c0c4cc;

  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
}
</style>