<template>
  <ai-detail class="addMeeting">
    <ai-title slot="title" title="发起会议" isShowBack isShowBottomBorder @onBackClick="$parent.goBack"/>
    <template #content>
      <ai-card title="会议信息">
        <template #content>
          <el-form :model="saveData" status-icon ref="ruleForm" :rules="rules" label-width="100px"
                   label-position="right">
            <el-form-item label="会议标题：" prop="title">
              <el-input v-model="saveData.title" size="small" placeholder="请输入..."
                        :maxlength="30" show-word-limit></el-input>
            </el-form-item>
            <el-row type="flex" justify="space-between">
              <el-form-item label="开始时间：" prop="startTime">
                <el-date-picker
                    :editable="false"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    v-model="saveData.startTime"
                    :picker-options="pickerOptions"
                    type="datetime"
                    size="small"
                    placeholder="选择开始时间">
                </el-date-picker>
              </el-form-item>
              <el-form-item label="结束时间：" prop="endTime">
                <el-date-picker
                    :editable="false"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    v-model="saveData.endTime"
                    :picker-options="pickerOptions"
                    type="datetime"
                    :disabled="!Boolean(saveData.startTime)"
                    size="small"
                    placeholder="选择结束时间">
                </el-date-picker>
              </el-form-item>
            </el-row>
            <el-form-item label="会议地点：" prop="address">
              <el-input v-model="saveData.address" size="small" placeholder="请输入..."
                        :maxlength="30" show-word-limit></el-input>
            </el-form-item>
            <el-form-item label="会议内容：" prop="content">
              <el-input v-model="saveData.content" size="small" placeholder="请输入..."
                        type="textarea" :rows="8" :maxlength="500" show-word-limit></el-input>
            </el-form-item>
            <el-row type="flex" justify="space-between">
              <el-form-item label="参会提醒：" prop="noticeBefore">
                <ai-select v-model="saveData.noticeBefore"
                           placeholder="请选择"
                           :selectList="dict.getDict('meetingNoticeBefore')"
                ></ai-select>
              </el-form-item>
              <el-form-item label="确认提醒：" prop="noticeAfter">
                <ai-select v-model="saveData.noticeAfter"
                           placeholder="请选择"
                           :selectList="dict.getDict('meetingNoticeAfter')"
                ></ai-select>
              </el-form-item>
            </el-row>
            <el-form-item label="会议资料：" prop="files">
              <ai-uploader :instance="instance" @change="handleChange" isShowTip fileType="file"
                           v-model="saveData.fileList"
                           acceptType=".zip,.rar,.doc,.docx,.xls,.ppt,.pptx,.pdf,.txt,.jpg,.png,.xlsx"
                           :limit="9"></ai-uploader>
            </el-form-item>
          </el-form>
        </template>
      </ai-card>
      <ai-card title="参会人员信息">
        <template #right>
          <ai-user-get slot="append" :instance="instance" v-model="saveData.attendees" sass>
            <el-button type="text" icon="iconfont iconAdd">选择参会人员</el-button>
          </ai-user-get>
        </template>
        <template #content>
          <ai-table
              border
              :tableData="saveData.attendees"
              :colConfigs="colConfigs"
              :isShowPagination="false">
            <el-table-column label="操作" slot="option" align="center">
              <template v-slot="{row}">
                <el-button type="text" title="删除" @click="deletePer(row)">删除</el-button>
              </template>
            </el-table-column>
          </ai-table>
        </template>
      </ai-card>
    </template>
    <template #footer>
      <el-button @click="$parent.goBack">取消</el-button>
      <el-button type="primary" @click="saveFrom(0)">保存草稿</el-button>
      <el-button type="primary" @click="saveFrom(1)">保存并发布</el-button>
    </template>
  </ai-detail>
</template>
<script>
import {mapState} from "vuex";
import moment from 'dayjs'

export default {
  name: "addMeeting",
  inject: ['top'],
  props: {
    instance: Function,
    dict: Object,
    permissions: Function,
    detail: Object
  },
  data() {
    let endTimePass = (rule, value, callback) => {
      if (value) {
        if (moment(value).unix() - moment(this.saveData.startTime).unix() > 0) {
          callback()
        } else {
          callback(new Error('结束时间要大于开始时间'));
        }
      } else {
        callback(new Error('请选择结束时间'));
      }
    }
    return {
      saveData: {
        noticeBefore: '4',
        noticeAfter: '0',
        attendees: [],
        fileList: []
      },
      rules: {
        title: [{required: true, message: '请填写会议标题', trigger: 'blur'}],
        startTime: [{required: true, message: '请选择开始时间', trigger: 'blur'}],
        endTime: [{required: true, validator: endTimePass, trigger: 'change'}],
        address: [{required: true, message: '请填写会议地点', trigger: 'blur'}],
        // content: [{required: true, message: '请填写会议内容', trigger: 'blur'}],
        noticeBefore: [{required: true, message: '请选择参会提醒', trigger: 'blur'}],
        noticeAfter: [{required: true, message: '请选择确认提醒', trigger: 'blur'}],
      },
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7;
        }
      },
      showEdit: false,
      total: 0,
    }
  },
  methods: {
    handleChange(e) {
      this.saveData.fileList = e
    },
    deletePer(scope) {
      this.$confirm('确认删除此参会人？')
      .then(_ => {
        if (this.detail.id) { //编辑

        } else { //新增
          this.saveData.attendees.map((item, index) => {
            if (item.id == scope.id) {
              this.saveData.attendees.splice(index, 1)
            }
          })
        }
      })
    },
    saveFrom(status) {
      this.$refs["ruleForm"].validate((valid) => {
        if (this.saveData.attendees.length == 0) {
          return this.$message.error("参会人不能为空！")
        }
        if (moment(this.saveData.startTime).unix() - moment(Date.now()).unix() < 0) {
          return this.$message.error("会议开始时间已过期，请重新选择！");
        }
        if (valid) {

          this.saveData.files = []
          this.saveData.fileList.map((item) => {
            this.saveData.files.push(item.id)
          })
          this.instance.post(`/app/appmeetinginfo/add-update`, {
            ...this.saveData,
            status: status,
          }).then(res => {
            if (res.code == 0) {
              if (status != 1) {
                this.$message.success("保存草稿成功")
              } else {
                this.$message.success("发布成功")
              }
              this.$parent.goBack();
            }
          });
        }
      });
    },
    getDetail() {
      this.instance.post(`/app/appmeetinginfo/info-id?id=${this.detail.id}`).then(res => {
        if (res?.data) {
          this.saveData = {
            ...res.data,
          };
          this.saveData.fileList = res.data.files || []
        }
      });
    }
  },
  created() {
    this.dict.load("meetingNoticeAfter", "meetingNoticeBefore").then(
        this.$nextTick(() => {
          if (JSON.stringify(this.detail) == '{}') {
            this.showEdit = false;
          } else {
            this.showEdit = true;
            // this.saveData = {...this.detail};
            // this.compereList = this.saveData.hosts;
            // this.saveData.attendees = this.saveData.attendees || [];
            this.getDetail()
          }
        })
    )
  },
  computed: {
    ...mapState(['user']),
    headerTitle() {
      return this.showEdit ? '修改会议' : '发起会议'
    },
    colConfigs() {
      return [
        {prop: 'name', align: 'center', label: '姓名', openType: "userName"},
        {prop: 'departName', align: 'center', label: '所属单位', openType: "departmentName"},
        {slot: 'option'}
      ]
    },
  }
}
</script>
<style lang="scss" scoped>
.addMeeting {
  ::v-deep .el-button--text {
    .iconfont {
      color: inherit;
    }
  }
}
</style>
