<template>
  <div class="msg-container-bdx12"  @click.stop>
    <el-dialog title="详情" v-model="dialogVisible" width="640px" custom-class="dialog_box1">
      <div>
        <detail-table2 :list="detailData">
          <template v-slot:action="{data}">
            <div :style="{backgroundColor:item.buttonHex,color:item.textHex}" @click="gotoPage(item.links)" class="ac-button-bdx12" v-for="(item,index) in data.value" :key="'btn'+index">{{item.desc}}</div>
          </template>

          <template v-slot:file="{data}">
            <div class="content-file-bdx12 content-no-scroll">
              <div @click="downLoadPage(item)" class="file-button-bdx12" v-for="(item,index) in data.value" :key="'file'+index">{{item.fileName}}</div>
            </div>
          </template>

          <template v-slot:content="{data}">
            <div class="content-box-bdx12 content-no-scroll">
              <template v-if="data.value.msgType==1||data.value.msgType==3">
                <div class="markdown-body" v-html="mdRender(data.value.msgInfo)"></div>
              </template>
              <template v-if="data.value.msgType==2">
                <div style="margin-bottom:20px;" v-for="(item,index) in data.value.image" :key="'img'+index">
                  <el-image style="width: 430px;height:200px;" :src="item.url" fit="contain" :preview-src-list="[item.url]">
                    <template #error>
                      <div class="el-image__error">
                        <span>图片链接失效，无法加载</span>
                      </div>
                    </template>
                  </el-image>
                  <!-- <p @click="gotoPage(item.link)" style="line-height:24px;font-size:12px;text-align:center;margin-top:-20px;cursor: pointer;">点击前往图片地址</p> -->
                  <div class="markdown-body" v-html="mdRender(item.content)"></div>
                </div>
              </template>
            </div>
          </template>
        </detail-table2>
      </div>
    </el-dialog>

    <div class="msg-box-bdx12" :style="modelValue?{top:'75px'}:''">
      <div class="msg-box-header">
        <div class="msg-title">消息盒子</div>
        <div class="msg-action">
          <el-input prefix-icon="Search" v-model.trim ="msgText" style="width:240px;border-color: #dadee7;" @input="changeText" placeholder="请输入搜索内容"></el-input>
          <bg-icon class="el-icon-close" icon="#bg-ic-close" style="font-size:14px;margin-left: 16px;color: #909bb6;"></bg-icon>
        </div>
      </div>

      <div class="msg-box-content">
        <div class="msg-box-read">
          <div @click="changeRead(0)" :style="activeName==0?{color:'#3759be',}:{border:0,}">全部</div>
          <div @click="changeRead(1)" :style="activeName==1?{color:'#3759be',}:{border:0,}">
            <div class="unread-num" v-if="unReadNum">{{unReadNum}}</div>
            未读
          </div>

          <span class="can_click_text" @click="allRead">
            <bg-icon icon="#bg-ic-mail-open" style="font-size:16px;margin-right: 8px;"></bg-icon>全部已读
          </span>
        </div>

        <div class="msg-box-list content-no-scroll">
          <div class="msg-box-item" v-for="(item,index) in msgList" :key="'msgitem'+index">
            <p :class="{'msg-title':item.readStatus==1}" class="msg-title1">{{item.msgTitle}}</p>
            <p>{{megDeal(item)}}</p>
            <p>
              <span>{{item.createTime}}</span>
              <span>{{item.systemName}}</span>
              <span class="can_click_text" @click="getDetail(item.msgId)">查看详情</span>
            </p>
          </div>
        </div>

        <div class="msg-box-page">
          <el-pagination @current-change="readPageChange" :current-page="readPage" :page-size="10" layout="total, prev, pager, next" :total="readTotal">
          </el-pagination>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import "github-markdown-css/github-markdown.css";
import detailTable2 from "./detail-table2.vue";
import MarkdownIt from "markdown-it";
import axios from "axios";
var md = new MarkdownIt();
export default {
  // model: {
  //   prop: "value",
  //   event: "change",
  // },
  props: {
    modelValue: {
      type: Boolean,
      default: false,
    },
  },
  emits: ['update:modelValue'],
  components: {
    detailTable2,
  },
  data() {
    return {
      dialogVisible: false,
      msgText: "",
      md,
      unReadNum: 0,
      activeName: 0,
      url: "https://fuss10.elemecdn.com/1/8e/aeffeb4de74e2fde4bd74fc7b4486jpeg.jpeg",
      srcList: [
        "https://fuss10.elemecdn.com/8/27/f01c15bb73e1ef3793e64e6b7bbccjpeg.jpeg",
        "https://fuss10.elemecdn.com/1/8e/aeffeb4de74e2fde4bd74fc7b4486jpeg.jpeg",
      ],
      detailData: [
        {
          label: "标题",
          value: "",
          width: "100%",
        },
        {
          label: "消息来源",
          value: "",
          width: "100%",
        },
        {
          label: "发送时间",
          value: "",
          width: "100%",
        },
        {
          label: "消息类型",
          value: "",
          width: "100%",
        },
        {
          label: "消息内容",
          value: '',
          width: "100%",
          childSlot: "content",
        },
      ],
      readTotal: 0,
      readPage: 1,
      textTime: null,
      msgList: [],
      timer:null,
    };
  },
  watch: {
    modelValue(n,o){
      console.log(n)
      if(n==true){
        this.getUnreadNum();
        this.changeRead(0)
      }
    }
  },
  computed: {},
  created() {
    this.timer = setInterval(() => {
      this.getNowMsg()
    }, 60000);
  },
  mounted() {
    this.getReadList();
    this.getUnreadNum();
  },
  destroyed(){
    clearInterval(this.timer)
  },
  methods: {
    getNowMsg(){
      axios
        .get(`${this.$trace.option.requestUrl}/msg/api/current`, {
          params: {
            appId: this.$trace.option.appID,
            userId: this.$trace.option.userId,
            userType: this.$trace.option.userType,
            roleId: this.$trace.option.roleId,
            organization: this.$trace.option.organization,
          },
        })
        .then((res) => {
          if (res.data.code == 200) {
            let data = res.data.data||[]
            data.forEach(e => {
              setTimeout(() => {
                this.msgTipsAdd(e)
              }, 1000);
            });
          }else{
            this.$message.error(res.data.desc)
          }
        });
    },
    //消息推送
    msgTipsAdd(data) {
      const h = this.$createElement;
      this.$notify({
        title: data.msgTitle,
        dangerouslyUseHTMLString: true,
        message: h("div", { class: "msg-tips-xxb1" }, [
          h("div", { class: "msg-text-xxb1" }, this.megDeal(data)),
          h(
            "p",
            {
              class: "detail-xxb1",
              on: {
                click: () => {
                  this.getDetail(data.msgId);
                },
              },
            },
            "查看详情"
          ),
          h("p", { class: "msg-time-info-xxb1" }, [
            h("span", data.createTime),
            h("span", data.systemName),
          ]),
        ]),
        iconClass: "el-icon-info",
      });
    },
    //获取详情
    getDetail(id) {
      this.dialogVisible = true;
      //刷新未读数量
      
      console.log(id);
      axios
        .get(`${this.$trace.option.requestUrl}/msg/api/my/msg/detail`, {
          params: {
            msgId: id,
            userId: this.$trace.option.userId,
            userType: this.$trace.option.userType,
            roleId: this.$trace.option.roleId,
            organization: this.$trace.option.organization,
          },
        })
        .then((res) => {
          if (res.data.code == 200) {
            let data = res.data.data
            this.detailData = [
              {
                label: "标题",
                value: data.msgTitle,
                width: "100%",
              },
              {
                label: "消息来源",
                value: data.systemName,
                width: "100%",
              },
              {
                label: "发送时间",
                value: data.createTime,
                width: "100%",
              },
              {
                label: "消息类型",
                value: ['','文本消息','图片消息','动作消息'][data.msgType],
                width: "100%",
              },
              {
                label: "消息内容",
                value: data,
                width: "100%",
                childSlot: "content",
              },
            ];

            if(data.file){
              this.detailData.push({
                label: "附件",
                childSlot: "file",
                value: JSON.parse(data.file),
                width: "100%",
              })
            }

            if(data.msgType==3){
              this.detailData.push({
                label: "快捷操作",
                childSlot: "action",
                value: data.action,
                width: "100%",
              })
            }else{
              console.log(md.render(data.msgInfo));
              console.log(this.mdRender(data.msgInfo))
            }
            this.getUnreadNum();
            this.getReadList();
          }else{
            this.$message.error(res.data.desc)
          }
        });
    },
    mdRender(val){
      let str = md.render(val)
      return str.replace(/<a/g,'<a target="_blank" style="text-decoration: underline;"')
    },
    //调整页面
    gotoPage(url) {
      this.dialogVisible = false;
      if (url) {
        window.open(url, "_blank");
      }
    },
    //下载
    downLoadPage(file){
      if(file.url){
        const filename = file.fileName;
        const a = document.createElement('a');
        a.href = file.url;
        a.download = filename;
        a.click();
        a.remove()
      }
    },
    //切换全部和未读
    changeRead(val) {
      this.activeName = val;
      this.readPage = 1
      this.getUnreadNum();
      this.getReadList();
    },
    //翻页
    readPageChange(page) {
      this.readPage = page;
      this.getReadList();
    },
    //消息列表
    getReadList() {
      let url = "";
      if (this.activeName == 0) {
        url = `/msg/api/my/list/10`;
      } else {
        url = `/msg/api/my/unRead/list/10`;
      }
      axios
        .get(`${this.$trace.option.requestUrl}${url}/${this.readPage}`, {
          params: {
            appId: this.$trace.option.appID,
            userId: this.$trace.option.userId,
            userType: this.$trace.option.userType,
            roleId: this.$trace.option.roleId,
            organization: this.$trace.option.organization,
            content: this.msgText,
          },
        })
        .then((res) => {
          if (res.data.code == 200) {
            this.msgList = res.data.data || [];
            this.readTotal = res.data.total;
          }else{
            this.$message.error(res.data.desc)
          }
        });
    },
    //输入消息查询
    changeText() {
      if (this.textTime) {
        clearTimeout(this.textTime);
      }
      this.textTime = setTimeout(() => {
        this.getReadList();
      }, 500);
    },
    // 关闭消息列表
    closeRead() {
      this.$emit("update:modelValu", false);
    },
    //全部已读
    allRead() {
      axios
        .put(`${this.$trace.option.requestUrl}/msg/api/read?appId=${this.$trace.option.appID}&userId=${this.$trace.option.userId}&userType=${this.$trace.option.userType}&roleId=${this.$trace.option.roleId}&organization=${this.$trace.option.organization}`
            )
        .then((res) => {
          if (res.data.code == 200) {
            this.changeRead(0)
            this.$message.success("全部已读成功");
          }else{
            this.$message.error(res.data.desc)
          }
        });
    },
    //获取未读数量
    getUnreadNum() {
      axios
        .get(`${this.$trace.option.requestUrl}/msg/api/my/unRead/count`, {
          params: {
            appId: this.$trace.option.appID,
            userId: this.$trace.option.userId,
            userType: this.$trace.option.userType,
            roleId: this.$trace.option.roleId,
            organization: this.$trace.option.organization,
          },
        })
        .then((res) => {
          if (res.data.code == 200) {
            this.unReadNum = res.data.data;
            this.$store.commit("setUnreadNum",this.unReadNum)
          }else{
            this.$message.error(res.data.desc)
          }
        });
    },
    //消息内容处理
    megDeal(obj){
      //文本
      // debugger
      if(obj.msgType==1){
        return obj.msgInfo 
      }else if(obj.msgType==2){//图文
        let img = obj.image||[]
        let str = ''
        img.forEach(e => {
          str = str+'[img]'+e.content
        });

        return str
      }else{//动作消息
        let act = obj.action||[]
        let actStr = ''
        act.forEach(e => {
          actStr = actStr + `[${e.desc}]`+' '
        });

        return actStr
      }
    },
    replaceImg(html) {
      let imgReg = /<img[^>]+>/g;
      let text = html.replace(imgReg, "[图片]");
      return text;
    },
  },
};
</script>

<style lang="scss" scoped>
.ac-button-bdx12,.file-button-bdx12 {
  height: 39px;
  line-height: 39px;
  background-color: #fff;
  color: #000;
  font-size: 14px;
  padding: 0 15px;
  border-radius: 4px;
  display: inline-block;
  cursor: pointer;
  margin-right: 15px;
}
.file-button-bdx12{
  color: #3759be;
  text-decoration: underline;
}
.content-box-bdx12 {
  height: 367px;
  overflow-x: hidden;
  overflow-y: scroll;
}
.content-file-bdx12 {
  max-height: 100px;
  overflow-x: hidden;
  overflow-y: scroll;
}
.content-no-scroll::-webkit-scrollbar {
  width: 0px;
  height: 0px;
}
.msg-box-bdx12 {
  width: 720px;
  height: 560px;
  background-color: #ffffff;
  box-shadow: 0px 4px 12px 0px rgba(18, 30, 63, 0.1);
  border-radius: 4px;
  border: solid 1px #e6e9ef;
  z-index: 1999;
  position: fixed;
  right: 15px;
  bottom: -700px;
  transition: all 0.5s;
  .msg-box-header {
    width: 100%;
    height: 64px;
    border-bottom: 1px solid #e6e9ef;
    padding: 0 15px;
    display: flex;
    justify-content: space-between;
    .msg-title {
      font-size: 18px;
      font-weight: 600;
      line-height: 64px;
      color: #202531;
      &::before {
        content: "";
        width: 4px;
        height: 16px;
        background-color: #2b4695;
        border-radius: 2px;
        display: inline-block;
        vertical-align: -1px;
        margin-right: 10px;
      }
    }
    .msg-action {
      display: flex;
      align-items: center;
      .el-icon-close {
        cursor: pointer;
      }
    }
  }
  .msg-box-content {
    .msg-box-read {
      width: 100%;
      height: 50px;
      border-bottom: 2px solid #f7f7f9;
      padding: 0 15px;
      div {
        float: left;
        line-height: 48px;
        margin-right: 40px;
        border-bottom: 3px solid #2b4695;
        cursor: pointer;
        position: relative;
        .unread-num {
          position: absolute;
          padding: 0 6px;
          border: 0;
          line-height: 16px;
          height: 16px;
          background-color: #d14731;
          border-radius: 8px;
          font-size: 12px;
          color: #ffffff;
          left: 28px;
          top: 9px;
        }
      }
      span {
        font-size: 14px;
        float: right;
        margin-top: 14px;
      }
    }
    .msg-box-list {
      width: 100%;
      height: 382px;
      overflow-x: hidden;
      overflow-y: scroll;
      .msg-box-item {
        height: 126px;
        border-bottom: 1px solid #e6e9ef;
        margin: 15px;
        .msg-title1 {
          font-size: 16px;
          font-weight: 700;
          color: #202531;
        }
        .msg-title{
          &::before{
            content:'';
            display:inline-block;
            width: 6px;
            height: 6px;
            vertical-align: 2px;
            margin-right: 8px;
            border-radius: 50%;
            background-color: #d75138;
          }
        }
        P {
          margin-bottom: 16px;
        }
        p:nth-of-type(1) {
          font-size: 16px;
          font-weight: 600;
          color: #202531;
        }
        p:nth-of-type(2) {
          font-size: 14px;
          height: 40px;
          color: #404a62;
          text-overflow: -o-ellipsis-lastline;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          line-clamp: 2;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
        }
        p:nth-of-type(3) {
          font-size: 14px;
          color: #909bb6;
          span {
            margin-right: 20px;
            &:nth-last-of-type(1){
              float: right;
            }
          }
        }
      }
    }
    .msg-box-page {
      width: 100%;
      height: 60px;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 14px;
      :deep() .el-pager li.active {
        color: #3759be;
      }
    }
  }
}
.markdown-body{
  font-size: 14px;
  color: rgb(64, 74, 98);
}
</style>
<style>
.el-notification .el-icon-info:before {
  color: #2b4695;
}
.el-notification .msg-tips-xxb1 {
  width: 100%;
}
.el-notification .msg-text-xxb1 {
  text-overflow: -o-ellipsis-lastline;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  line-clamp: 3;
  -webkit-line-clamp: 3;
  font-size: 14px;
  -webkit-box-orient: vertical;
}
.el-notification .detail-xxb1 {
  text-align: right;
  color: #3759be;
  cursor: pointer;
  font-size: 14px;
  margin: 15px 0;
}
.el-notification .msg-time-info-xxb1 {
  display: flex;
  justify-content: space-between;
  font-size: 14px;
  color: #909bb6;
  overflow: hidden;
  text-overflow: ellipsis;
  word-break: break-all;
  white-space: nowrap;
}
.el-notification__group {
  flex-grow: 1;
}
</style>
