<template>
  <Modal
    class="notice-dialog marker-modal"
    v-model="modalIsShow"
    title="消息"
    :mask-closable="false"
    footer-hide
    fullscreen
    @on-visible-change="visibleChange"
  >
    <div class="notice-container">
      <div v-if="IS_MARK_LEADER" class="notice-users">
        <div class="user-item user-all">
          <div>小组成员</div>
          <div
            :class="['user-selection', { 'is-active': userSelectAll }]"
            @click="selectAll"
          >
            <Icon v-if="userSelectAll" type="ios-checkmark-circle" />
            <Icon v-else type="md-radio-button-off" />
          </div>
        </div>
        <div
          v-for="user in markers"
          :key="user.id"
          class="user-item"
          @click="selectUser(user)"
        >
          <div class="user-avatar"><Icon type="md-contact" /></div>
          <div class="user-name" :title="user.name">{{ user.name }}</div>
          <div :class="['user-selection', { 'is-active': user.selected }]">
            <Icon v-if="user.selected" type="ios-checkmark-circle" />
            <Icon v-else type="md-radio-button-off" />
          </div>
        </div>
      </div>
      <div class="notice-body">
        <div ref="NoticeContent" class="notice-content">
          <div v-if="hasMore" class="notice-item notice-more" @click="nextPage">
            获取更多
          </div>
          <div v-for="notice in notices" :key="notice.id" class="notice-item">
            <div class="notice-item-head">
              <span class="notice-head-users">
                {{ notice.relateUsers }}
              </span>
              <span class="notice-head-time">
                {{ notice.createTime }}
              </span>
            </div>
            <div class="notice-item-content" v-html="notice.content"></div>
          </div>
        </div>
        <div v-if="IS_MARK_LEADER" class="notice-send">
          <textarea
            placeholder="请输入"
            v-model="content"
            maxlength="300"
          ></textarea>
          <div class="notice-send-footer">
            <Button type="primary" :loading="loading" @click="toSend"
              >发送</Button
            >
          </div>
        </div>
      </div>
    </div>
  </Modal>
</template>

<script>
import { mapState, mapMutations } from "vuex";
import {
  userSendNoticeList,
  userReceiveNoticeList,
  fetchReleaseUnreadNotice,
  readNotice,
  sendNotice,
  leaderMarkUserList
} from "@/api";
import timeMixin from "@/plugins/timeMixin";

export default {
  name: "ribbon-set-dialog",
  mixins: [timeMixin],
  data() {
    return {
      workId: "",
      subject: "",
      modalIsShow: false,
      curUserRoleType: this.$ls.get("user", { role: "" }).role,
      userSelectAll: false,
      markers: [],
      notices: [],
      current: 0,
      size: 10,
      content: "",
      hasMore: false,
      fetching: false,
      loading: false
    };
  },
  computed: {
    ...mapState("marker", ["curSubject"]),
    IS_MARKER() {
      return this.curUserRoleType === "MARKER";
    },
    IS_MARK_LEADER() {
      return this.curUserRoleType === "MARK_LEADER";
    }
  },
  mounted() {
    const [workId, subject] = this.$route.params.subjectId.split("-");
    this.workId = workId;
    this.subject = subject;

    this.initData();
  },
  beforeDestroy() {
    this.clearSetTs();
  },
  methods: {
    ...mapMutations("marker", ["setShortcut", "recoverShortcut"]),
    async initData() {
      if (this.IS_MARK_LEADER) {
        this.getLeaderMarkerList();
        this.getLeaderMarkerNoticeList();
        return;
      }

      if (this.IS_MARKER) {
        await this.getMarkerNoticeList();
        // await this.getNewNotice();
      }
    },
    visibleChange(visible) {
      if (visible) {
        if (this.IS_MARKER) {
          this.setNoticeRead();
        }
        this.goToBottom();
        this.setShortcut([]);
      } else {
        this.recoverShortcut();
      }
    },
    goToBottom() {
      this.$nextTick(() => {
        this.$refs.NoticeContent.scrollTop = this.$refs.NoticeContent.offsetHeight;
      });
    },
    async getLeaderMarkerList() {
      const markerId = this.$ls.get("user", { id: "" }).id;
      const data = await leaderMarkUserList({
        workId: this.workId,
        subject: this.subject,
        stage: this.curSubject.stage,
        markerId
      });
      const markers = data || [];
      this.markers = markers.map(item => {
        item.selected = false;
        return item;
      });
    },
    async nextPage() {
      if (this.fetching) return;
      this.fetching = true;

      this.current++;
      if (this.IS_MARKER) {
        await this.getMarkerNoticeList().catch(() => {});
      } else {
        await this.getLeaderMarkerNoticeList().catch(() => {});
      }
      this.fetching = false;
    },
    async getLeaderMarkerNoticeList() {
      const sendUserId = this.$ls.get("user", { id: "" }).id;
      const lastId = this.notices.length ? this.notices.slice(-1)[0].id : null;
      const data = await userSendNoticeList({
        subject: this.subject,
        stage: this.curSubject.stage,
        sendUserId,
        lastId,
        page: this.current,
        size: this.size
      });
      const notices = data.content.map(item => {
        item.receiveUser = JSON.parse(item.receiveUser);
        item.relateUsers = item.receiveUser.map(user => user.name).join("，");
        return item;
      });
      notices.reverse();
      this.hasMore = this.current + 1 < data.totalPages;
      this.notices = [...notices, ...this.notices];
    },
    parseMarkerNotice(info) {
      return {
        ...info.message,
        id: info.id,
        read: info.read,
        relateUsers: info.message.sendUserName
      };
    },
    async getMarkerNoticeList() {
      const receiveUserId = this.$ls.get("user", { id: "" }).id;
      const lastId = this.notices.length ? this.notices.slice(-1)[0].id : null;
      const data = await userReceiveNoticeList({
        subject: this.subject,
        stage: this.curSubject.stage,
        receiveUserId,
        lastId,
        page: this.current,
        size: this.size
      });
      const notices = data.content.map(item => {
        return this.parseMarkerNotice(item);
      });
      notices.reverse();
      this.hasMore = this.current + 1 < data.totalPages;
      this.notices = [...notices, ...this.notices];
    },
    async getNewNotice() {
      this.clearSetTs();

      const receiveUserId = this.$ls.get("user", { id: "" }).id;
      const resData = await fetchReleaseUnreadNotice({
        subject: this.subject,
        stage: this.curSubject.stage,
        receiveUserId
      }).catch(() => {});
      const data = resData || [];
      const noticeIds = this.notices.map(item => item.id);
      const validNotices = data
        .filter(item => !noticeIds.includes(item.id))
        .map(item => this.parseMarkerNotice(item));
      if (validNotices.length) {
        this.notices.push(...validNotices);
        this.open();
        this.goToBottom();

        this.$nextTick(() => {
          this.setNoticeRead();
        });
      }

      this.addSetTime(() => {
        this.getNewNotice();
      }, 10 * 1000);
    },
    setNoticeRead() {
      const noticeIds = this.notices
        .filter(item => !item.read)
        .map(item => item.id);
      if (!noticeIds.length) return;
      readNotice(noticeIds);
    },
    cancel() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    selectChange() {
      this.userSelectAll = !this.markers.some(item => !item.selected);
    },
    selectUser(user) {
      user.selected = !user.selected;
      this.selectChange();
    },
    selectAll() {
      this.userSelectAll = !this.userSelectAll;
      this.markers.forEach(user => {
        user.selected = this.userSelectAll;
      });
    },
    async toSend() {
      if (!this.content) {
        this.$Message.error("请输入内容");
        return;
      }
      if (this.content.length > 300) {
        this.$Message.error("内容最多300个字符");
        return;
      }

      const user = this.$ls.get("user", { id: "", name: "" });
      const markers = this.markers
        .filter(item => item.selected)
        .map(item => {
          return {
            id: item.id,
            name: item.name
          };
        });

      if (!markers.length) {
        this.$Message.error("请选择评卷员");
        return;
      }

      if (this.loading) return;
      this.loading = true;

      const data = {
        subject: this.subject,
        stage: this.curSubject.stage,
        sendUserId: user.id,
        sendUserName: user.name,
        content: this.content,
        markers
      };
      const res = await sendNotice(data).catch(() => {});
      this.loading = false;
      if (!res) return;

      this.content = "";
      res.receiveUser = JSON.parse(res.receiveUser);
      res.relateUsers = res.receiveUser.map(item => item.name).join("，");
      this.notices.push({ ...res });
      this.goToBottom();
    }
  }
};
</script>
