<template>
  <div>
    <vxe-modal
      :value="isShow"
      show-footer
      :z-index="zIndex"
      title="会议使用审核"
      show-confirm-button
      :width="defaultModalSize.width"
      :height="defaultModalSize.height"
      esc-closable
      transfer
      show-zoom
      resize
      :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="start_time">
          <el-date-picker
            style="width: 100%;"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            v-model="form.start_time"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="end_time">
          <el-date-picker
            style="width: 100%;"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            v-model="form.end_time"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="会议室" prop="room_id">
          <el-select
            style="width: 100%;"
            v-model="form.room_id"
            @change="
              (e) =>
                (form.address = rooms.find((i) => i.id === e)
                  ? rooms.find((i) => i.id === e).name
                  : '')
            "
          >
            <el-option
              v-for="item in rooms"
              :key="item.id"
              :value="item.id"
              :label="item.name"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="会议/活动地址" prop="address">
          <el-input v-model="form.address" />
        </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="附件上传">
          <el-upload
            :action="action"
            :headers="{
                Authorization: `Bearer ${getToken()}`,
              }"
            :before-upload="beforeUpload"
            :on-success="uploadSuccess"
            :on-remove="uploadRemove"
            :on-error="uploadError"
            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="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-item v-if="type === 'examine'" label="会议状态" prop="meeting_status">
          <el-select v-model="form.meeting_status">
            <el-option label="待审核" :value="0"></el-option>
            <el-option label="通过" :value="1"></el-option>
            <el-option label="不通过" :value="2"></el-option>
          </el-select>
        </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/meeting";
import { PopupManager } from "element-ui/lib/utils/popup";
import { userListNoAuth as index } from '@/api/common';
import {defaultModalSize, uploadSize} from "@/settings";
import { formatFileSize } from "@/utils"
export default {
  props: {
    type: {
      type: String,
      default: 'add',
      required: true
    },
    isShow: {
      type: Boolean,
      default: false,
      required: true,
    },
    rooms: {
      type: Array,
      default: () => [],
    }
  },
  data() {
    return {
      uploadSize,
      users: [],
      defaultModalSize,
      zIndex: PopupManager.nextZIndex(),
      loading: false,
      form: {
        id: "",
        title: "",
        start_time: "",
        end_time: "",
        address: "",
        room_id: "",
        content: "",
        meeting_status: 0,
        files: [],
        user_ids: [],
      },
      action: process.env.VUE_APP_UPLOAD_API,
      fileList: [],
      rules: {
        title: [
          { required: true, message: '请填写标题' }
        ],
        start_time: [
          { required: true, message: '请填写开始时间' }
        ],
        end_time: [
          { required: true, message: '请结束标题' }
        ],
        room_id: [
          { required: true, message: '请选择会议室' }
        ],
      },
    };
  },
  computed: {},
  watch: {
    isShow(newVal) {
      if(newVal) {
        this.zIndex = PopupManager.nextZIndex()
      } else {
        this.fileList = []
        this.$emit('update:type', 'add')
      }
    }
  },
  created() {
    this.getUsers()
  },
  methods: {
    formatFileSize,
    getDetail (data) {
      for (let key in this.form) {
        this.form[key] = data[key]
      }
      this.form.user_ids = data['users']?.map(i => ({ user_id: i.id }))
      this.fileList = data['files_details']?.map(i => ({
        name: i.original_name,
        url: i.url,
        response: {
          data: i
        }
      })) ?? []
    },
    uploadRemove(file, fileList) {
      this.fileList = fileList
    },
    beforeUpload(file) {
      const isLt = file.size < uploadSize
      if (!isLt) {
        this.$message.error(`上传文件大小不能超过${formatFileSize(uploadSize)}!`)
      } else {
        window.$_uploading = true
      }
      return isLt
    },
    uploadSuccess(response, file, fileList) {
      window.$_uploading = false
      if (response.code) {
        fileList.splice(fileList.indexOf(file), 1)
        this.$message.warning(response.msg)
      }
      this.fileList = fileList
    },
    uploadError() {
      window.$_uploading = false
    },

    getToken,
    submit() {
      if (window.$_uploading) {
        this.$message.warning("文件正在上传中")
        return
      }
      this.$refs["elForm"].validate(async (valid) => {
        if (valid) {
          this.loading = true;
          try {
            this.form.files = 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>
