<template>
  <el-dialog :title="modalConfig.title" :visible.sync="modalConfig.show" width="700px" @close="handleClose">
    <el-form ref="form" :model="modalData" :rules="rules" label-width="150px">
      <el-form-item label="排序" prop="sort">
        <el-input-number v-model="modalData.sort" controls-position="right" :min="0"></el-input-number>
        <div class="form-tip">序号越小越靠前显示，建议设置为10、20、30等便于后续插入</div>
      </el-form-item>
      <el-form-item label="公告内容" prop="title">
        <el-input type="textarea" v-model="modalData.title" :rows="5" maxlength="120"></el-input>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-switch v-model="modalData.status" active-text="启用" inactive-text="禁用"></el-switch>
      </el-form-item>
      <el-form-item label="应用" prop="app">
        <el-select v-model="modalData.app" placeholder="请选择应用">
          <el-option label="用户" :value="1"></el-option>
          <el-option label="商家" :value="2"></el-option>
          <el-option label="专员" :value="3"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="toggle">取 消</el-button>
      <el-button type="primary" @click="handleSubmit">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { cloneDeep } from "lodash";

export default {
  data() {
    return {
      isAdd: true,
      modalConfig: {
        title: "",
        show: false,
      },
      modalData: {
        sort: 10,
        title: "",
        status: true,
        app: 1,
        targetId: "",
        position: "",
      },
      rules: {
        title: [{ required: true, message: "请输入公告内容", trigger: "blur" }],
        app: [{ required: true, message: "请选择应用", trigger: "change" }],
      },
    };
  },
  methods: {
    toggle() {
      this.modalConfig.show = !this.modalConfig.show;
    },
    handleClose() {
      this.$refs.form.resetFields();
    },
    init(row) {
      this.modalData = { ...this.modalData, ...row };
    },
    add(row) {
      this.isAdd = true;
      this.modalConfig.title = "添加公告";
      this.modalData = {
        sort: 10,
        title: "",
        status: true,
        app: 1,
        targetId: row.targetId,
        position: row.position,
      };
    },
    update(row) {
      this.isAdd = false;
      this.modalConfig.title = "编辑公告";
      this.init(cloneDeep(row));
    },
    handleSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          const apiCall = this.isAdd
            ? this.$api.mer_admin.noticeAdd(this.modalData)
            : this.$api.mer_admin.noticeUpdate(this.modalData);

          apiCall.then(() => {
            this.$message.success(this.isAdd ? "添加成功" : "编辑成功");
            this.toggle();
            this.$emit("queryList");
          });
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.form-tip {
  color: #999;
  font-size: 12px;
  line-height: 1.5;
}
</style>

