<template>
  <div>
    <vxe-modal
      :value="isShow"
      show-footer
      :z-index="zIndex"
      title="发布通知或提醒"
      show-confirm-button
      :width="740"
      :height="620"
      esc-closable
      :fullscreen="$store.getters.device === 'mobile'"
      @input="(e) => $emit('update:isShow', e)"
    >
      <el-form
        ref="elForm"
        :model="form"
        :rules="rules"
        label-position="top"
        label-width="100"
      >
        <el-form-item label="公告标题" prop="title">
          <el-input v-model="form.title" />
        </el-form-item>
        <el-form-item label="公告内容" prop="content">
          <el-input
            v-model="form.content"
            type="textarea"
            :autosize="{ minRows: 2 }"
          />
        </el-form-item>
        <el-form-item label="回复格式" prop="reply_fields">
          <el-input
            placeholder="参会人员
联系电话"
            v-model="form.reply_fields"
            type="textarea"
            :autosize="{ minRows: 2 }"
          />
          <span style="font-size: 12px; color: #6c757d; line-height: 1">
            回复方式为文字回复时有效，每行一个栏位。举例：如需要回复参会人员和联系电话，只要在以上框中输入“参会人员”、“联系电话”即可
          </span>
        </el-form-item>
        <el-form-item label="附件上传">
          <el-upload
            :action="action"
            :headers="{
              Authorization: `Bearer ${getToken()}`,
            }"
            :before-upload="beforeUpload"
            :on-success="uploadSuccess"
            :on-remove="uploadRemove"
            multiple
            :file-list="fileList"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">上传文件不超过10Mb</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="回复方式" prop="deal_type">
          <el-select style="width: 100%" v-model="form.deal_type">
            <el-option value="read" label="阅读即可，无需回复"></el-option>
            <el-option value="text" label="文字"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="回复时是否开放附件上传" prop="reply_need_files">
          <el-switch
            v-model="form.reply_need_files"
            :active-value="1"
            :inactive-value="0"
            active-text="开放"
            inactive-text="不开放"
          ></el-switch>
        </el-form-item>
        <el-form-item label="回复时限" prop="deadline">
          <el-date-picker
            style="width: 100%"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            v-model="form.deadline"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="用户选择" prop="user_ids">
          <el-transfer
            filterable
            :titles="['未选用户', '已选用户']"
            filter-placeholder="请输入关键字"
            :value="form.user_ids.map((i) => i.user_id)"
            :props="{
              key: 'id',
              label: 'name',
            }"
            :data="users"
            @input="(e) => (form.user_ids = e.map((i) => ({ user_id: i })))"
          >
          </el-transfer>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button type="primary" :loading="loading" @click="submit"
          >确认</el-button
        >
      </template>
    </vxe-modal>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import { save } from "@/api/notice";
import { PopupManager } from "element-ui/lib/utils/popup";
import { userListNoAuth as index } from "@/api/common";
export default {
  props: {
    isShow: {
      type: Boolean,
      default: false,
      required: true,
    }
  },
  data() {
    return {
      users: [],
      zIndex: PopupManager.nextZIndex(),
      loading: false,
      form: {
        title: '',
        content: '',
        file_ids: '',
        deal_type: '',
        reply_fields: '',
        reply_need_files: '',
        deadline: '',
        user_ids: []
      },
      action: process.env.VUE_APP_UPLOAD_API,
      fileList: [],
      rules: {},
    };
  },
  computed: {},
  watch: {
    isShow(newVal) {
      if(newVal) {
        this.zIndex = PopupManager.nextZIndex()
      }
    }
  },
  created() {
    this.getUsers()
  },
  methods: {
    uploadRemove(file, fileList) {
      this.fileList = fileList
    },
    beforeUpload(file) {
      const isLt10M = file.size / 1024 / 1024 < 10
      if (!isLt10M) {
        this.$message.error('上传文件大小不能超过 10MB!')
      }
      return isLt10M
    },
    uploadSuccess(response, file, fileList) {
      if (response.code) {
        fileList.splice(fileList.indexOf(file), 1)
        this.$message.warning(response.msg)
      }
      this.fileList = fileList
    },

    getToken,
    submit() {
      this.$refs["elForm"].validate(async (valid) => {
        if (valid) {
          this.loading = true;
          try {
            this.form.file_ids = this.fileList.map(i => i.response?.data?.id).filter(i => !!i)
            await save(this.form);
            this.$message.success("新增成功");
            this.$emit("refresh");
            this.$emit("update:isShow", false);
            this.loading = false;
            this.$refs["elForm"].resetFields();
          } catch (err) {
            this.loading = false;
          }
        }
      });
    },
    async getUsers () {
      try {
        const res = await index({
          page: 1,
          rows: 9999
        })
        this.users = res.data
      } catch (err) {
      }
    }
  },
};
</script>

<style scoped lang="scss"></style>
