<template>
  <el-dialog
    v-dialogdrag
    title="发送通知"
    :visible.sync="visible"
    append-to-body
    width="45%"
    :close-on-click-modal="false"
    :destroy-on-close="true"
    :close-on-press-escape="false"
    :before-close="closeDialog"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="接受者" prop="toUserId">
        <el-select
          v-model="form.toUserId"
          clearable
          filterable
          size="small"
        >
          <el-option
            v-for="(item, index) in userOption"
            :key="index"
            :label="item.realName"
            :value="item.id"
            @change="getUserName"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="发送内容" prop="messageBody">
        <el-input type="textarea" v-model="form.messageBody" size="small" placeholder="请输入发送内容"></el-input>
      </el-form-item>
    </el-form>

    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="sendHandle">发送</el-button>
      <el-button @click="closeDialog">取消</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { getList } from "@/api/system/user";
import { sendMessage,sendManyMessage } from "@/api/basicData/message"

export default {
  name: "main",
  props: {},
  data() {
    return {
      visible: false,
      form: {},
      userOption: [],
      rules: {
        toUserId: [{required: true, message: " ", trigger: "change"}],
        messageBody: [{required: true, message: " ", trigger: "blur"}],
      },
    }
  },
  created() {
    getList().then(res => {
      this.userOption = res.data.data.records;
    })
  },
  methods: {
    // 打开
    init() {
      this.visible = true;
    },
    closeDialog() {
      this.visible = false;
      this.form = {}
      this.$refs.form.clearValidate();
      this.$emit("closeDialog")
    },
    // 发送消息
    sendHandle() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          const data = {
            ...this.form,
            messageType: 1
          }
          sendManyMessage(data).then(res => {
            this.$message.success('发送成功')
            this.closeDialog()
          })
        }
      })
    },
    getUserName() {
      if (this.form.toUserId) {
        this.userOption.forEach(item => {
          if (item.form.toUserId == this.form.toUserId) {
            this.$set(this.form, 'toUserName', item.realName)
          }
        })
      }
    },
  },
}
</script>

<style scoped>

</style>
