<template>
  <el-dialog
    :title="id==null ? '新增' : '编辑'"
    width="520px"
    :visible="visible"
    :keyboard="false"
    @close="handleCancel"
    :show-close="false"
    @open="init"
  >
    <el-form :model="dataForm" label-width="120px" ref="form">
      <el-form-item label="标题" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }" prop="title">
        <el-input v-model="dataForm.title" />
      </el-form-item>
      <el-form-item label="内容" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }" prop="content">
        <el-input v-model="dataForm.content" />
      </el-form-item>
    </el-form>
    <template slot="footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">保存</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { reportDe, reportSave, reportPut } from "@/api/report";
export default {
  name: "reportDe",
  props: {
    visible: {
      default: false,
      type: Boolean
    },
    id: {
      default: null,
      type: Number
    }
  },
  data() {
    return {
      dataForm: {
        title: "",
        content: ""
      }
    };
  },
  methods: {
    //关闭模态框
    handleCancel() {
      console.log("关闭弹窗");
      this.visible = false;
      // 退出弹窗需要清空对象，否则新增时会有上次编辑的数据
      this.dataForm = {
        title: "",
        content: ""
      };
      this.$emit("deClose", {});
    },
    // form提交按钮触发，根据是否有id决定是新增api还是保存api
    dataFormSubmitHandle() {
      console.log("试图保存");
      console.log(this.id);
      if (this.id == null) {
        reportSave(this.dataForm).then(res => {
          console.log("新增成功:");
          console.log(res);
          this.$message({
            message: "新增成功",
            type: "success"
          });
          this.handleCancel();
          this.$emit("getReport", {});
        });
      } else {
        reportPut(this.id, this.dataForm).then(res => {
          console.log("更新成功");
          this.$message({
            message: "更新成功",
            type: "success"
          });
          this.handleCancel();
          this.$emit("getReport", {});
        });
      }
    },
    // 弹窗组件自动触发，决定是否需要请求某个具体的日报内容
    init() {
      console.log("init:" + this.id);
      if (this.id == null) {
        return;
      }
      reportDe(this.id).then(res => {
        this.dataForm.title = res.data.title;
        this.dataForm.content = res.data.content;
      });
    }
  }
};
</script>