<template>
  <el-drawer
    class="es-simplicity-message"
    modal-class="es-simplicity-message-modal"
    direction="rtl"
    size="648px"
    :withHeader="false"
    :visible.sync="show"
    :modal-append-to-body="false"
  >
    <div class="es-simplicity-message-header">
      <span class="es-simplicity-message-title">消息提示</span>
      <span class="es-simplicity-message-overlook" @click="handleIgnoreAll"
        >全部忽略</span
      >
    </div>
    <div class="es-simplicity-message-lists-box">
      <div class="es-simplicity-message-lists">
        <el-scrollbar class="es-scrollbar">
          <div v-infinite-scroll="getMsg" :infinite-scroll-disabled="disabled">
            <div
              v-for="(item, index) in msgs"
              :key="item.id"
              class="es-simplicity-message-item"
            >
              <div class="es-simplicity-message-item-title">
                {{ item.title }}
              </div>
              <div>
                <span class="es-simplicity-message-item-time">
                  {{ item.time }}
                </span>
                <span
                  class="es-simplicity-message-handler"
                  v-show="item.handlerUrl"
                  @click="handleMessage(item, index)"
                >
                  处理
                </span>
                <span
                  class="es-simplicity-message-overlook"
                  @click="handleIgnore(item, index)"
                >
                  忽略
                </span>
              </div>
            </div>
            <p class="es-simplicity-message-tips" v-if="loading">加载中...</p>
            <p class="es-simplicity-message-tips" v-if="noMore && count > 0">
              没有更多了
            </p>
          </div>
        </el-scrollbar>
      </div>
    </div>
    <div class="es-simplicity-message-total">共有 {{ count }} 条消息记录</div>
    <es-dialog
      title="处理"
      name="manage"
      width="90%"
      height="80%"
      :visible.sync="dialog.show"
      :url="dialog.url"
      :param="dialog.params"
      @close="handleClose"
    ></es-dialog>
  </el-drawer>
</template>
<script>
import {
  sysMsgPage,
  ignoreSysMsg,
  ignoreAllSysMsg
} from 'eoss-ui/src/config/api.js';
import util from 'eoss-ui/src/utils/util';
export default {
  name: 'Message',
  provide() {
    return {
      deleteMessage: this.handleRemove
    };
  },
  props: {
    visible: Boolean,
    total: {
      type: Number,
      default: 0
    },
    winopen: Boolean
  },
  computed: {
    show: {
      get() {
        return this.visible;
      },
      set(val) {
        this.$emit('update:visible', val);
      }
    },
    count: {
      get() {
        return this.total;
      },
      set(val) {
        this.$emit('update:total', val);
      }
    },
    noMore() {
      return this.msgs.length >= this.count;
    },
    disabled() {
      return this.loading || this.noMore;
    }
  },
  watch: {
    total(val, old) {
      if (parseInt(val, 10) < parseInt(old, 10) && this.index !== null) {
        this.handleRemove();
      } else {
        this.getMsg(true);
      }
    }
  },
  data() {
    return {
      //加载数据
      loading: false,
      //消息页码
      pageNum: 1,
      pageSize: 20,
      pageCount: 1,
      //消息数据,
      msgs: [],
      dialog: {
        params: {},
        url: '',
        show: false
      },
      index: null,
      deleteId: null
    };
  },
  mounted() {
    util.win.deleteMsg = this.handleRemove;
    const bus = this.bus || this.$root.Bus;
    bus && bus.$on('deleteMessage', this.handleRemove);
  },
  methods: {
    //获取消息列表
    getMsg(reload) {
      if (this.pageNum <= this.pageCount) {
        this.loading = true;
        util
          .ajax({
            url: sysMsgPage,
            params: {
              pageNum: reload ? 1 : this.pageNum,
              pageSize: this.pageSize
            }
          })
          .then((res) => {
            if (res && res.rCode === 0) {
              this.pageCount = res.results.pageCount;
              this.loading = false;
              if (reload || this.pageNum == 1) {
                this.msgs = JSON.parse(JSON.stringify(res.results.records));
              } else {
                this.msgs = this.msgs.concat(res.results.records);
              }
              this.pageNum++;
            } else {
              let msg = res.msg || '系统错误，请联系管理员！';
              this.$message.error(msg);
            }
          })
          .catch((err) => {
            this.loading = false;
            if (err.message && err.message !== 'canceled') {
              this.$message.error(err.message);
            }
          });
      }
    },
    //忽略
    handleIgnore(res, i) {
      util
        .ajax({
          url: ignoreSysMsg,
          params: {
            id: res.id
          }
        })
        .then((res) => {
          if (res.rCode == 0) {
            this.count -= 1;
            this.msgs.splice(i, 1);
          } else {
            let msg = res.msg || '系统错误，请联系管理员！';
            this.$message.error(msg);
          }
        });
    },
    //全部忽略
    handleIgnoreAll() {
      util
        .ajax({
          url: ignoreAllSysMsg
        })
        .then((res) => {
          this.count = 0;
          this.msgs = [];
          this.$emit('ignore', { type: 'ignore', value: 'all' });
        })
        .catch((err) => {
          if (err.message && err.message !== 'canceled') {
            this.$message.error(err.message);
          }
        });
    },
    //处理消息
    handleMessage(item, index) {
      const openModel = util.getStorage('openModel');
      if (openModel && openModel == 'dialog') {
        let { handlerUrl, title, id, metaData } = item;
        metaData &&
          (title =
            metaData.title ||
            metaData.pendtitle ||
            metaData.meetName ||
            title ||
            '办理');
        const jsonData =
          metaData && metaData.jsonData ? JSON.parse(metaData.jsonData) : {};
        util.busEmit(this, {
          method: 'windowOpen',
          args: {
            url: handlerUrl,
            title: title,
            id: id,
            msgIndex: index,
            ...jsonData,
            callback: 'deleteMessage'
          }
        });
        return;
      }
      this.count -= 1;
      this.msgs.splice(index, 1);
      if (this.winopen) {
        const mywin = util.win.open(item.handlerUrl);
        if (mywin) {
          let times = setInterval(() => {
            if (mywin.closed) {
              clearInterval(times);
              this.$parent.$emit('bus-emit', 'waitdone');
            }
          }, 1000);
        }
      } else {
        this.dialog = {
          show: true,
          url: item.handlerUrl,
          data: {
            id: item.id,
            pendingId: item.pendingId,
            userId: item.userId
          }
        };
        this.index = index;
      }
    },
    handleRemove(res) {
      let index = res ? res.msgIndex : this.index;
      if (index !== null) {
        this.count -= 1;
        this.msgs.splice(index, 1);
        this.index = null;
      }
      if (res) {
        this.$emit('handle', res);
      }
      this.dialog.show = false;
    },
    handleClose() {
      this.$parent.$emit('bus-emit', 'waitdone');
    }
  },
  destroyed() {
    const bus = this.bus || this.$root.Bus;
    bus.$off('deleteMessage', this.handleRemove);
  }
};
</script>
