<template>
  <div class="announcement-tab">
    <div v-if="isCreator">
      <el-popover v-model:visible="noticePopover"
                  :width="160"
                  placement="bottom">
        <el-row class="sel-notice-type">
          <div :style="{color:themeColor.green}" class="notice-type-icon">
            公告
          </div>
          <div class="notice-type-txt">
            <el-link href="javascript:void(0);" type="success" @click="selAndInitAnnouncement('announcement')">
              发布公告
            </el-link>
          </div>
        </el-row>
        <el-row class="sel-notice-type">
          <div :style="{color:themeColor.orange}" class="notice-type-icon">
            作业
          </div>
          <div class="notice-type-txt">
            <el-link href="javascript:void(0);" type="warning" @click="selAndInitAnnouncement('homework')">发布作业
            </el-link>
          </div>
        </el-row>
        <el-row class="sel-notice-type">
          <div :style="{color:themeColor.red}" class="notice-type-icon">
            考试
          </div>
          <div class="notice-type-txt">
            <el-link href="javascript:void(0);" type="danger" @click="selAndInitAnnouncement('exam')">发布考试
            </el-link>
          </div>
        </el-row>
        <template #reference>
          <el-button plain type="primary" @click="noticePopover = true">添加发布
          </el-button>
        </template>
      </el-popover>
    </div>
    <!--通知列表-->
    <el-collapse v-if="announcementList.length!==0">
      <el-collapse-item v-for="(item,index) in announcementList"
                        :key="item.id"
                        :name="index"
                        @click="readAnnouncement(item)">
        <template #title>
          <notice-item :ref="'noticeItem'+item.id"
                       :notice-v-o="item" @update="beforeUpdateAnnouncement(item)"
                       @delete="deleteAnnouncement(item, index)"/>
        </template>
        <div class="announcement-content">{{ announcementContent(item) }}</div>
      </el-collapse-item>
    </el-collapse>
  </div>
  <el-dialog v-model="announcementFormDialog" :before-close="beforeFormClose" :title="announcementForm.dialogTitle">
    <el-form ref="announceFormRef" :model="announcementForm" :rules="announcementFormRule" label-position="right"
             label-width="60px">
      <el-form-item label="类别" prop="type">
        <el-select v-model="announcementForm.type">
          <el-option label="公告" value="announcement"></el-option>
          <el-option label="作业" value="homework"></el-option>
          <el-option label="考试" value="exam"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="主题" prop="title">
        <el-input v-model="announcementForm.title"></el-input>
      </el-form-item>
      <el-form-item label="内容" prop="content">
        <el-input v-model="announcementForm.content" :rows="3" type="textarea"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" @click="handlePublishAnnouncement">确认发布</el-button>
    </template>
  </el-dialog>
</template>

<script>
import portal from "@/utils/portal/portal";
import {ElMessage, ElMessageBox} from "element-plus";
import NoticeItem from "@/views/CourseDetailPage/components/NoticeItem.vue";

export default {
  name: "AnnouncementTab",
  components: {NoticeItem},
  props: {
    courseId: {
      required: true,
    },
    teacherId: {
      required: true,
    },
  },
  data() {
    return {
      themeColor: portal.variables.themeColor,
      noticePopover: false,
      announcementFormDialog: false,
      announcementForm: {
        dialogTitle: "添加发布",
        id: null,
        type: null,
        title: "",
        content: "",
      },
      announcementFormRule: {
        type: {
          required: true, message: "请选择发布类别", trigger: "change",
        },
        title: {
          required: true, message: "请输入发布主题", trigger: "blur",
        }
      },
      announcementList: [],
    };
  },
  computed: {
    isCreator() {
      return Number(this.teacherId) === Number(this.$store.state.user.id);
    },
  },
  async mounted() {
    this.init();
  },
  methods: {
    async init() {
      this.announcementList = (await this.$apis.getAnnouncementsByCourseId(this.courseId)).data.data || [];
    },

    selAndInitAnnouncement(type) {
      this.announcementForm.type = type;
      this.announcementFormDialog = true;
    },

    beforeFormClose() {
      ElMessage.info("取消创建");
      this.announcementFormDialog = false;
      this.$refs.announceFormRef.resetFields();
    },

    handlePublishAnnouncement() {
      const _this = this;
      if (this.announcementForm.content === "") {
        ElMessageBox.confirm("是否确认发布内容为空？", "提示", {
          confirmButtonText: "确认为空",
          cancelButtonText: "我再想想",
          type: "warning",
          center: true,
        })
          .then(() => {
            if (this.announcementForm.id === null) {
              createAnnouncement();
            } else {
              updateAnnouncement();
            }
          });
      } else {
        if (this.announcementForm.id === null) {
          createAnnouncement();
        } else {
          updateAnnouncement();
        }
      }

      function createAnnouncement() {
        let announcementVO = {
          sender: {id: _this.$store.state.user.id,},
          courseId: _this.courseId,
          title: _this.announcementForm.title,
          content: _this.announcementForm.content,
          type: _this.announcementForm.type.toUpperCase(),
          createdAt: new Date(),
        };
        _this.$apis.createAnnouncement(announcementVO)
          .then(res => {
            _this.announcementList.push(res.data.data);
            _this.announcementFormDialog = false;
            _this.$refs.announceFormRef.resetFields();
            ElMessage.success("新建公告完成");
          });
      }

      function updateAnnouncement() {
        let announcementVO = {
          id: _this.announcementForm.id,
          title: _this.announcementForm.title,
          content: _this.announcementForm.content,
          type: _this.announcementForm.type.toUpperCase(),
        };
        _this.$apis.updateAnnouncement(announcementVO)
          .then(res => {
            for (let i = 0; i < _this.announcementList.length; i++) {
              if (_this.announcementList[i].id === _this.announcementForm.id) {
                _this.announcementList[i] = res.data.data;
              }
            }
            _this.$refs["noticeItem" + _this.announcementForm.id][0].setNoticeInfo(res.data.data);
            _this.announcementFormDialog = false;
            _this.$refs.announceFormRef.resetFields();
            ElMessage.success("修改公告完成");
          });
      }
    },

    beforeUpdateAnnouncement(item) {
      this.announcementForm.dialogTitle = "修改公告";
      this.announcementForm.id = item.id;
      this.announcementForm.type = item.type;
      this.announcementForm.title = item.title;
      this.announcementForm.content = item.content;
      this.announcementFormDialog = true;
    },

    deleteAnnouncement(item, index) {
      ElMessageBox.confirm("是否确认删除公告  \"" + item.title + "\"  ？", "提示", {
        confirmButtonText: "确认删除",
        cancelButtonText: "我再想想",
        type: "warning",
        center: true,
      })
        .then(() => {
          this.$apis.deleteAnnouncement(item.id)
            .then(() => {
              this.announcementList.splice(index, 1);
            });
        });
    },

    announcementContent(item) {
      if (item.content === "") {
        return "当前公告暂无具体内容。";
      } else {
        return item.content;
      }
    },

    readAnnouncement(item) {
      if (!item.read) {
        this.$apis.readAnnouncement(item.id)
          .then(() => {
            item.read = true;
            this.$refs["noticeItem" + item.id][0].setNoticeInfo(item);
          });
      }
    },
  },
};
</script>

<style scoped>
@import "tabs.css";

.el-collapse {
  margin-top: 10px;
}
</style>