<template>
  <div id="userMessage-wrap" ref="userMessage">
    <el-drawer
      title="消息通知"
      :size="350"
      :visible.sync="drawerVisible"
      custom-class="el-drawer"
      :show-close="false"
      :append-to-body="true"
    >
      <div slot="title" class="drawer-head">
        <div class="tab-item" :class="tabSelected==='received'?'active':''" @click="tabClick('received')">
          <el-badge :value="viewData.unReadCount" class="custom-badge" :max="99" :hidden="viewData.unReadCount<1">收件箱</el-badge>
        </div>
        <div class="tab-item" :class="tabSelected==='sent'?'active':''" @click="tabClick('sent')">发件箱</div>
        <el-button size="small" type="primary" round @click="sendMessageHandle"> 发送消息</el-button>
      </div>

      <div class="message-content">
        <el-card
          v-for="(item,index) in viewData.msgList"
          :key="index"
          class="box-card"
          :body-style="{ padding: '10px 15px' }"
        >
          <div class="card-cont" @click="showMsgDetail(item)">
            <div class="top">
              <i v-if="tabSelected==='sent'" :class="item.msgCatId===1?'el-icon-chat-dot-round':'el-icon-message-solid'" />
              <el-badge v-else class="avatar-badge" is-dot :hidden="item.isRead!==0">
                <el-avatar class="avatar" size="small" :src="item.msgFrAvatar" />
              </el-badge>
              <div class="rt" :class="tabSelected">
                <h3 v-if="tabSelected==='received'" class="title">{{ item.msgFrName }}</h3>
                <h3 v-if="tabSelected==='sent'" class="title">{{ item.msgTo|formatMsgTo }}</h3>
                <p class="cont">{{ item.msgContent }}</p>
                <p class="flex-between">
                  <span class="time">{{ item.msgTime|formatTime|niceDateFilter }}</span>
                  <span v-if="item.isDetailed===1" class="more">详情</span>
                </p>
              </div>
            </div>
            <!-- <div class="desc">{{ item.msgContent }}</div> -->
          </div>
        </el-card>
      </div>
      <el-empty v-if="viewData.msgList&&viewData.msgList.length<1" :image-size="200" description="暂无信息" />
    </el-drawer>

    <el-dialog title="发送消息" :visible.sync="dialogVisible" width="40%" :close-on-click-modal="false" :fullscreen="formData.msgCatId===2">
      <el-form ref="sendForm" :model="formData" label-width="120px" :rules="rules">
        <el-form-item label="收件人" prop="msgTo">
          <template>
            <el-radio v-model="formData.msgCatId" :label="1">消息</el-radio>
            <el-radio v-model="formData.msgCatId" :label="2">通知</el-radio>
          </template>
        </el-form-item>

        <el-form-item label="收件人" prop="msgTo">
          <user-selector
            key="msgTo-selectUser"
            :default-val="viewData.msgTs"
            :multiple="true"
            @setUserInfo="handleMsgTo"
          />
        </el-form-item>

        <el-form-item label="抄送人" prop="msgCc">
          <user-selector
            :default-val="viewData.msgCs"
            :multiple="true"
            @setUserInfo="handleMsgCc"
          />
        </el-form-item>

        <el-form-item label="内容" prop="msgContent">
          <el-input v-model="formData.msgContent" />
        </el-form-item>

        <el-form-item v-if="formData.msgCatId===2" label="详情">
          <el-input v-model="formData.msgDetail" type="textarea" :rows="15" :maxlength="5000" show-word-limit />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="sendMessage">确 定</el-button>
      </div>
    </el-dialog>

    <el-drawer
      :size="320"
      direction="rtl"
      :visible.sync="msgContentDrawer"
      :show-close="false"
    >
      <template slot="title"><i class="el-icon-arrow-left" @click="msgContentDrawer=false" />{{ viewData.msgDetail.msgCatTitle }}</template>
      <div class="msgContent">
        <h4 class="title">{{ viewData.msgDetail.msgContent }}</h4>
        <p>{{ viewData.msgDetail.msgDetail }}</p>
      </div>
    </el-drawer>
  </div>
</template>
<script>
import { sendMsg, getMsgSentByPage, getMsgReceivedByPage, getUnReadCounter, putReadStatus, getMsgById } from '@/api/system/msgApi'
import UserSelector from '@/components/UserSelector/index'
import { isNotNull, parseTime } from '@/utils'
import { mapGetters } from 'vuex'
import commonMixins from '@/mixin/commonMethodMixin'

export default {
  name: 'MsgList',
  components: {
    UserSelector
  },
  filters: {
    formatTime(val) {
      return parseTime(new Date(val))
    },

    formatMsgTo(val) {
      let result = ''
      if (isNotNull(val)) {
        const arr = val.split(',')
        for (const item of arr) {
          const arrItem = item.split('/')
          if (result === '') {
            result += arrItem[1]
          } else {
            result += ',' + arrItem[1]
          }
        }
      }
      return result
    }
  },
  mixins: [commonMixins],
  data() {
    return {
      title: '',
      drawerVisible: false,
      dialogVisible: false,
      msgContentDrawer: false,
      tabSelected: 'received',
      conditions: {
        page: 1,
        limit: 10,
        keywords: ''
      },
      viewData: {
        total: 0,
        msgList: [],
        msgTs: [],
        msgCs: [],
        msgDetail: '',
        unReadCount: 0
      },
      formData: {
        msgToGroup: undefined,
        msgCc: [],
        msgCatId: 1,
        msgTo: [],
        msgTitle: '',
        msgContent: ''
      },
      rules: {
        msgTo: [
          { required: true, trigger: 'blur', message: '请填写收件人' }
        ],
        msgCc: [
          { required: true, trigger: 'blur', message: '请填写抄送人' }
        ],
        msgContent: [
          { required: true, trigger: 'blur', message: '请填写发送内容' }
        ]
      }
    }
  },
  computed: {
    ...mapGetters([
      'userData'
    ])
  },
  methods: {

    // 初始化
    init() {
      this.drawerVisible = true
      this.tabSelected = 'received'
      this.getReceivedMsg()
      this.getUnReadMsgCount()
    },

    // 获取未读数目
    getUnReadMsgCount() {
      getUnReadCounter().then((resp) => {
        this.viewData.unReadCount = resp.data
      })
    },

    // 获取已发送消息
    getSentMsg() {
      this.listLoading = true
      getMsgSentByPage(this.conditions).then((resp) => {
        const { data, total } = resp
        this.listLoading = false
        this.total = total
        this.viewData.msgList = data
      }).catch((error) => {
        console.log(error)
      })
    },

    // 获取接收到的消息
    getReceivedMsg() {
      this.listLoading = true
      getMsgReceivedByPage(this.conditions).then((resp) => {
        const { data, total } = resp
        this.listLoading = false
        this.conditions.total = total
        this.viewData.msgList = data
      }).catch((error) => {
        console.log(error)
      })
    },

    // 抄送人选择
    handleMsgCc(item, user) {
      this.formData.msgCc = user.map(item => `${item.accountId}/${item.accountName}`).join(',')
    },

    // 收件人选择
    handleMsgTo(item, user) {
      this.formData.msgTo = user.map(item => `${item.accountId}/${item.accountName}`).join(',')
    },

    //
    sendMessageHandle() {
      this.dialogVisible = true
      this.resetForm()
      this.viewData.msgTs = []
      this.viewData.msgCs = []
    },
    resetForm() {
      this.formData = {
        msgToGroup: '',
        msgCc: '',
        msgTo: '',
        msgDetail: '',
        msgCatId: 1,
        msgContent: ''
      }
    },

    sendMessage() {
      this.$refs['sendForm'].validate((valid) => {
        if (valid) {
          sendMsg(this.formData).then((res) => {
            this.$message.success(res.msg)
            this.dialogVisible = false
            this.tabSelected = 'received'
            this.getReceivedMsg()
          })
        } else {
          this.$message.error('请检查数据')
          return false
        }
      })
    },

    tabClick(type) {
      this.tabSelected = type
      this.msgList = []
      if (type === 'sent') {
        this.getSentMsg()
      } else if (type === 'received') {
        this.getReceivedMsg()
      }
    },
    showMsgDetail(item) {
      if (this.tabSelected === 'received' && item.isRead === 0) {
        putReadStatus(item.msgId).then(() => {
          this.getReceivedMsg()
          this.getUnReadMsg()
        })
      }
      if (item.isDetailed === 1) {
        this.viewData.msgDetail = ''
        this.msgContentDrawer = true
        getMsgById(item.msgId).then((res) => {
          this.viewData.msgDetail = res.data
        })
      }
    }
  }
}
</script>
<style lang="scss" scoped>
  .el-drawer {
    .drawer-head {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .tab-item {
        padding: 0 20px;
        height: 40px;
        -webkit-box-sizing: border-box;
        box-sizing: border-box;
        line-height: 40px;
        display: inline-block;
        list-style: none;
        font-size: 14px;
        font-weight: 500;
        position: relative;
        color: #fff;
        cursor: pointer;

        &::after {
          width: 100%;
          height: 2px;
          background-color: transparent;
          position: absolute;
          bottom: 0;
          left: 0;
          border-radius: 2px;
          display: block;
          content: "";
          transition: 0.3s;
        }

        &.active {
          &::after {
            background-color: #1890ff;
          }
        }
      }
    }
    .card-cont-box{
      width: 100%;
    }
    .card-cont {
      color: #FFFFFF;
      cursor: pointer;
      .top {
        display: flex;
        justify-content: flex-start;
        align-items: flex-start;

        i {
          font-size: 28px;
          color: #42c5bf;
          font-weight: normal;
          padding: 0 10px 0 0;
          margin: 0;
        }
        .avatar{
          margin-right: 10px;
        }
        h3 {
          font-weight: normal;
          font-size: 14px;
          line-height: 1.2;
          padding: 0;
          margin: 0;
        }

        p {
          line-height: 1.5;
          font-size: 10px;
          margin: 0;
          padding-top: 4px;
        }
      }
      .rt{
        width: 100%;
        .title{
          font-size: 14px;
          color: #c7c5c5;
        }
        p{
          font-size: 18px;
          color: #fff;
        }
        .time{
          font-size: 10px;
          color: #b5b5b5;
        }
      }
      .flex-between{
        width: 100%;
        display: flex;
        justify-content: space-between;
        align-items: center;
      }
      .more{
        color: #1890ff;
        font-size: 8px;
      }
      .desc {
        font-size: 14px;
        line-height: 1.4;
        padding-top: 8px;
      }
    }
  }
  .msgContent{
    padding: 10px;
    color: #fff;
    text-align: justify;
    h1,h2,h3,h4,h5{margin: 0;}
    .title{
      padding-bottom: 10px;
    }
    p{
      text-indent: 24px;
      margin: 0;
      line-height: 1.8;
      font-size: 14px;
    }
  }
</style>
<style lang="scss">
  .el-badge.custom-badge{
    .el-badge__content{
      height: 14px;
      line-height: 14px;
      font-size: 8px;
      border: 0;
      padding: 0 5px;
      &.is-fixed{
        top: 11px;
        right: 4px;
      }
    }
  }
  .avatar-badge{
    .el-badge__content{
      height: 6px;
      width: 6px;
      border: 0;
       &.is-fixed{
        right: 12px;
      }
    }
  }
</style>
