<template>
  <div>
    <!-- <Remark>
      <ul>
        <li>个人觉得以单选框的形式展现应该是勾选条件而不是查询条件</li>
      </ul>
    </Remark>
    <portal-header :goSearch="10"></portal-header> -->
    <div class=" portal-content">
      <div class="msg-nav">
        <div style="display: flex;align-items: center;">
          <div><el-checkbox v-model="checkAll" :indeterminate="isIndeterminate">多选</el-checkbox></div>
          <!-- <el-radio-group style="padding-left: 20px;" @change="queryMessage(true)" v-model="queryData.isRead">
            <el-radio :label="null">全部</el-radio>
            <el-radio :label="false">未读</el-radio>
            <el-radio :label="true">已读</el-radio>
          </el-radio-group> -->
        </div>
        <div>
          <el-button style="margin-left: 25px;" :disabled="disabledReadAll" :class="{ navbut: !disabledReadAll }"
            type="text" @click="isReadChooseList">设置已读</el-button>
          <el-button class="navbut" type="text" @click="delChooseList">删除所选</el-button>
        </div>
      </div>
      <div style="background-color: #FFFFFF;min-height: 600px;">
        <p style="line-height:30px;text-align: center;">{{ showMessage }}</p>


        <!-- 临时增加，上线一段时间后删除   开始
        <div class="msg-list">
          <a href="javascript:void(0);">
          <div class="msg-top">
            <div>
              <span style="padding-right: 10px;"><el-checkbox disabled></el-checkbox></span>
              <span @click="showGuideDialog()">系统消息</span>
            </div>
          </div>
          <div class="msg-body" @click="showGuideDialog()">
            <div class="msg-body-content">新版本上线！点击此处查看功能介绍</div>
          </div>
          <div class="msg-time">2022-10-20 10:21:50</div>
          </a>
        </div>
         -->


        <div class="msg-list">
          <a href="javascript:void(0);">
            <div class="msg-top">
              <div>
                <span style="padding-right: 10px;"><el-checkbox disabled></el-checkbox></span>
                <span @click="showMsgDg()">系统消息</span>
              </div>
            </div>
            <div class="msg-body" @click="dialogMsgVisible = true">
              <div class="msg-body-content">新功能说明</div>
            </div>
            <div class="msg-time">2022-12-30 11:23:33</div>
          </a>
        </div>


        <!--
        <div class="msg-list">
          <a href="javascript:void(0);">
          <div class="msg-top">
            <div>
              <span style="padding-right: 10px;"><el-checkbox disabled></el-checkbox></span>
              <span @click="jumResearch()">系统消息</span>
            </div>
          </div>
          <div class="msg-body" @click="jumResearch()">
            <div class="msg-body-content">学习平台 V2.0邀您进行用户调研体验</div>
          </div>
          <div class="msg-time">2022-11-23 12:40:50</div>
          </a>
        </div>
        -->



        <div class="msg-list" v-for="(item, index) in data" :key="index">

          <div class="msg-top">
            <div>
              <span style="padding-right: 10px;"><el-checkbox v-model="item.checked"
                  @change="setCheckAll(item)"></el-checkbox></span>
              <span v-if="!item.isRead"
                style="font-size:12px;padding:5px 7px; border-radius: 2px;background: #FF6562;color: #fff;margin-right: 5px">未读</span>
              <span v-else
                style="font-size:14px;padding:5px 7px; background: #eee;  border-radius: 2px; color: #666666;margin-right: 5px">已读</span>
              <!-- <a :href="returnRouter(item)"> -->
              <span style="cursor: pointer;" @click="returnRouter(item)">{{ item.title }}</span>
            </div>
          </div>
          <div class="msg-body">
            <!-- <a :href="returnRouter(item)"> -->
            <div v-if="item.refType !== '99'">
              <div style="cursor: pointer;" @click="returnRouter(item)" class="msg-body-content" v-if="item.content">
                {{ item.tip }}-{{ item.content }}
              </div>
              <div style="cursor: pointer;" @click="returnRouter(item)" class="msg-body-content" v-else>{{ item.tip }}
                <span style="color:#0078FC;" v-if="item.refType == '100'||item.refType == '101'">点击查看</span>
              </div>
              <div style="cursor: pointer;" @click="returnRouter(item)" class="msg-body-content" v-else-if="item.refType == '102'">
                {{ item.tip }}
              </div>
            </div>
            <div v-else :class="!item.isRead ? 'infoActive' : ''" style="cursor: pointer;" @click="goRouter(item)"
              class="msg-body-content">管理员{{ item.acceptName }}向您推荐了案例{{ item.content }}，点击查看>>>
            </div>
            <!-- </a> -->
            <div v-if="item.refType !== '99'" class="msg-body-but">
              <el-button type="danger" plain @click="delItem(item)">删除</el-button>
            </div>
          </div>
          <div class="msg-time">{{ item.msgTime }}</div>
        </div>
      </div>
      <div style="text-align: center;margin-top: 50px" v-if="total > queryData.pageSize">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="queryData.pageIndex" :page-sizes="[2, 4, 6, 8]" :page-size="queryData.pageSize"
          layout="total, sizes, prev, pager, next, jumper" :total="total"></el-pagination>
      </div>
      <!-- <div class="pagination-div" v-if="queryData.pageIndex < totalPages"><span class="pag-text" @click="loadMore()">加载更多</span></div> -->
    </div>
    <!-- <portal-footer></portal-footer> -->
    <guide-box ref="guide"></guide-box> <!-- 引导页 -->


    <!--  对话框 -->
    <el-dialog :visible.sync="dialogMsgVisible" title="新功能说明" width="30%" append-to-body>
      <div>
        教师端：<br />
        1、支持个人授课记录/案例记录查询<br />
        2、支持个人修改/完善教师介绍并在个人主页中展示<br />
        <br />
        <br />
        管理员端：<br />
        1、新增学习路径图功能<br />
        2、新增学习项目功能<br />
        3、新增课程库功能<br />
        4、升级案例管理（设置优秀案例等）<br />
        5、升级考试功能（试题及提干支持图片，修改已发布考试的部分信息等)<br />
        6、课件支持 Scorm 格式<br />
        及上述功能配套的学员端功能<br />
        <br />
        <br />
        我们会在1月份提供线上操作培训及详细的使用手册，便于大家熟悉和使用新增功能。
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogMsgVisible = false" type="primary">关闭</el-button>
        </span>
      </template>
    </el-dialog>

  </div>
</template>

<script>
import { mapGetters } from 'vuex';
import portalHeader from '@/components/PortalHeader.vue';
import portalFooter from '@/components/PortalFooter.vue';
import GuideBox from '@/components/Portal/guideBox.vue'
import apiMessage from '@/api/system/message.js';
import apiCase from '@/api/modules/cases.js';
export default {
  name: 'answer',
  components: {
    portalHeader,
    portalFooter,
    GuideBox
  },
  computed: {
    ...mapGetters(['userInfo'])
  },
  data() {
    return {
      dialogMsgVisible: false,
      queryData: {
        pageIndex: 1,
        pageSize: 6,
        isRead: null
      },
      disabledReadAll: false,
      total: 0,
      checkAll: false,
      data: [],
      totalPages: '',
      checkedIds: [],
      isIndeterminate: false,
      url: '',
      showMessage: '暂无消息'
    };
  },
  mounted() {
    this.queryMessage(true);
    // this.isReadChooseList();
  },
  updated() {
    // this.isReadChooseList();
  },
  watch: {
    checkAll(newVal) {
      this.data.forEach(msg => {
        msg.checked = newVal;
      });
    }
  },
  destroyed() {
    this.isReadChooseList();
  },
  methods: {
    showMsgDg() {
      this.dialogMsgVisible = true;
    },
    jumResearch() {
      this.$router.push('/user/research');
      // return this.webBaseUrl + '/src/views/user/myResearch.vue';
    },
    queryMessage(flag) {
      this.showMessage = '加载中...';
      if (flag) {
        this.data = [];
        this.checkAll = false;
        this.isIndeterminate = false;
      }
      this.disabledReadAll = false;
      apiMessage.list(this.queryData).then(res => {
        if (res.status == 200) {
          this.totalPages = res.result.totalPages;
          this.total = res.result.count;
          let allRead = true;
          res.result.list.forEach(item => {
            let name = this.filterContent(item.content);
            let num = name.slice(1, name.length);
            item.tip = name[0];
            item.content = num.join('-');
            item.checked = false;
            if (!item.isRead) {
              allRead = false;
            }
            this.data.push(item);
          });
          if (allRead) {
            this.disabledReadAll = true;
          }
          if (this.total == 0) { this.showMessage = '暂无消息'; }
          this.showMessage = this.total <= 0 ? '暂无消息' : '';
        } else {
          this.$message.error('获取数据失败');
        }
      });
    },
    handleSizeChange(val) {
      this.isReadChooseList();
      this.queryData.pageSize = val;
      this.queryMessage(true);
    },
    handleCurrentChange(val) {
      this.isReadChooseList();
      this.queryData.pageIndex = val;
      this.queryMessage(true);
    },
    //存在问题，待解决
    // async loadMore() {
    //   await this.isReadChooseList()
    //   if(this.queryData.pageIndex<this.totalPages){
    //     console.log(this.data,"点击加载中未操作的data数据")
    //     this.data.splice((this.queryData.pageIndex-1)*this.queryData.pageSize,this.queryData.pageSize)
    //     console.log(this.data,"点击加载中删除操作的data数据")
    //     await this.queryMessage(false);
    //     console.log(this.data,"点击加载中添加操作的data数据")
    //     this.queryData.pageIndex++;
    //     await this.queryMessage(false)
    //     console.log(this.data,"点击加载中最后一次添加操作的data数据")
    //   }
    // },
    setCheckAll(item) {
      if (item.checked) {
        this.checkedIds.push(item.id);
      } else {
        let obj = this.checkedIds.indexOf(item.id);
        this.checkedIds.splice(obj, 1)
      }
      let flag = !item.checked;
      let has = this.data.some(msg => {
        return msg.checked == flag;
      });

      if (has) {
        this.isIndeterminate = true;
      } else {
        this.isIndeterminate = false;
        this.checkAll = item.checked;
      }
    },

    //改变已读状态的操作
    isReadChooseList() {
      if (this.data.length == 0) return;
      let ids = [];
      for (let i = 0; i < this.data.length; i++) {
        if (!this.data[i].isRead) {
          ids.push(this.data[i].id);
        }
      }
      if (this.checkedIds.length > 0) {
        apiMessage.updateIsRead(this.checkedIds).then(res => {
          if (res.status == 200) {
            this.$store.dispatch('refrashMsg');
            this.queryMessage(true)
          }
        });
        this.checkedIds = [];
        return;
      }

      if (this.checkAll) {
        apiMessage.updateIsRead(ids).then(res => {
          if (res.status == 200) {
            this.$store.dispatch('refrashMsg');
            this.queryMessage(true)
          }
        });
        return;
      }
    },
    delChooseList() {
      // 全选的时候不能删除案例
      if (this.data.some((item) => item.refType == '99' && item.checked)) {
        this.$message.error('推荐案例不能删除，请重新选择');
        return;
      }
      let list = this.data.filter(item => item.checked).map(v => v.id);
      if (list.length == 0) {
        this.$message.error('请先选择要删除的消息');
        return;
      }

      this.$confirm('您确定要删除所选消息吗？', '删除提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        apiMessage.del(list).then(res => {
          if (res.status == 200) {
            this.$message.success('删除成功');
            this.queryData.pageIndex = 1;
            this.queryMessage(true);
            this.$store.dispatch('refrashMsg');
          } else {
            this.$message.error('删除失败' + res.message);
          }
        });
      });
    },
    delItem(item) {
      this.$confirm('您确定要删除此消息吗?', '删除提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        apiMessage.del([item.id]).then(res => {
          if (res.status == 200) {
            this.$message.success('删除成功');
            this.queryData.pageIndex = 1;
            this.queryMessage(true);
            this.$store.dispatch('refrashMsg');
          } else {
            this.$message.error('删除失败' + res.message);
          }
        });
      });
    },
    filterContent(content) {
      return content.split('-');
    },

    // 弹出新功能引导页弹窗事件(临时)
    showGuideDialog() {
      this.$refs.guide.guideCollection = true;
    },

    // 点击案例
    async goRouter(item) {
      console.log(item);
      apiMessage.updateIsRead([item.id]).then(res => {
        if (res.status == 200) {
          this.$store.dispatch('refrashMsg');
          item.isRead = true;
        }
      });
      //需要跳转
      if (item.pageUrl && item.pageUrl.length > 10) {
        await apiCase.startReadTimer(item.refId)
        this.$router.push('/case/detail?id=' + item.pageParams);
      } else {
        this.$router.push('/case?recommendId=' + item.refId);
      }
    },
    // 跳转详情事件11
    returnRouter(item) {
      apiMessage.updateIsRead([item.id]).then(res => {
        if (res.status == 200) {
          this.$store.dispatch('refrashMsg');
          // this.queryMessage(true)
          item.isRead = true;
        }
      });
      if (item.pageUrl && item.pageUrl.length > 10) {
        location.href = item.pageUrl;
      } else {
        if (item.pageType && item.pageParams) {
          if (item.pageType == 1) {
            this.$router.push('/course/studyindex?id=' + item.pageParams);
          } else if (item.pageType == 2) {
            this.$router.push('/article/detail?id=' + item.pageParams);
          } else if (item.pageType == 3) {
            this.$router.push('/case/detail?id=' + item.pageParams);
          } else if (item.pageType == 4) {
            this.$router.push('/qa/answer?id=' + item.pageParams);
          }
        } else {
          if (item.refType == 2) {
            this.$router.push('/article/detail?id=' + item.refId);
          } else if (item.refType == 3) {
            this.$router.push('/case/detail?id=' + item.refId);
          } else if (item.refType == 4 || item.refType == 5) {
            this.$router.push('/qa/answer?id=' + item.refId);
          } else if (item.refType == 1) {
            this.$router.push('/course/studyindex?id=' + item.refId);
          } else if (item.refType == 100) {
            this.$router.push('/need/draft?teacherId=' + item.pageParams);
          } else if (item.refType == 101) {
            this.$router.push('/need/finalsuccess?teacherId=' + item.pageParams);
          }
        }

      }

    }
  }
};
</script>

<style lang="scss" scoped>
.infoActive {
  color: #0078FC !important;
}

.navbut {
  width: 110px;
  height: 30px;
  border-radius: 2px;
  margin-left: 25px;
  text-align: center;
  border: 1px solid #0078FC;
  padding: 0;
  color: #0078FC;
}

.msg-nav {
  display: flex;
  // justify-content: space-between;
  border-bottom: 1px solid #f5f5f5;
  line-height: 40px;
  background-color: #ffffff;
  padding: 5px 10px;
}

.msg-list {
  border-bottom: 1px solid rgb(237, 237, 237);
  margin-top: 10px;
  line-height: 26px;
  background-color: #ffffff;
  padding: 5px 10px;

  &:first-of-type {
    padding-top: 15px;
  }

  .msg-top {
    display: flex;
    justify-content: space-between;
    line-height: 30px;
  }

  .msg-body {
    padding: 10px 10px 10px 25px;
    display: flex;
    width: 100%;

    .msg-body-content {
      flex: 1;
      word-break: break-all;
      color: #727272;

      a:hover {
        color: #409eff;
      }
    }

    .msg-body-but {
      margin-left: auto;

      button {
        width: 88px;
        height: 32px;
        background-color: #fff;
        border-radius: 16px;
        padding: 0;
        color: #F52F3E;
        line-height: 32px;
        text-align: center;
        border: 1px solid #F52F3E;
      }

      button:hover {
        background-color: rgba(255, 101, 98, 0.13);
        color: #F52F3E;


      }
    }
  }

  .msg-time {
    color: #a5a5a5;
    font-size: 14px;
    padding-left: 25px;
  }
}

.messageList {
  >p {
    display: flex;
    justify-content: space-between;
    border-bottom: 1px solid rgb(219, 219, 219);
    padding-bottom: 10px;
    margin: 0;
    align-items: center;
  }

  .messageItem:not(:first-child) {
    padding-top: 10px;
  }

  .messageItem {
    // width: 100%;
    padding-bottom: 10px;
    border-bottom: 1px solid rgb(219, 219, 219);
    display: flex;
    justify-content: space-between;
    align-items: center;

    .el-checkbox {
      margin-right: 5px;
    }

    .el-button {
      margin-left: auto;
    }

    // margin-bottom: 10px;
    p {
      margin: 0;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    p:first-of-type {
      >span {
        display: flex;
        justify-content: flex-start;
        align-items: center;

        span:first-of-type {
          font-size: 12px;
        }
      }

      >span:last-of-type {
        font-size: 14px;
        color: #b7b7b7;
        margin-left: 5px;
      }
    }

    p:last-of-type {
      font-size: 14px;
      text-indent: 3em;

      span:last-of-type {
        font-size: 14px;
        color: #b7b7b7;
      }
    }
  }
}

.pagination-div {
  cursor: pointer;
}
</style>
