<template>
  <div>
    <div class="navbar">
      <!-- 菜单展开缩起 -->
      <hamburger :is-active="sidebar.opened" class="hamburger-container" @toggleClick="toggleSideBar" />
      <div class="menu_module">
        <div class="menu_module_view">
          <v-scroll-view
            :x="true"
            :y="false"
            slidingBgClassName="slidingBgClassName"
            slidingBlockClassName="slidingBlockClassName"
          >
            <div class="menu_module_fj">
              <div
                v-for="(item, index) in routes"
                :key="index"
                :class="{ item: true, select: path === item.path }"
                @click="tizhuanyemian(item)"
              >
                {{ item.meta.title }}
              </div>
            </div>
          </v-scroll-view>
        </div>
      </div>

      <!-- 右侧 -->
      <div class="right-menu">
        <div class="right-menu-item" v-if="bigViewsBool" @click="goBigViews">
          <el-button size="mini">数据大屏</el-button>
        </div>
        <div class="right-menu-item">
          <el-autocomplete
            v-model="pathurl"
            :fetch-suggestions="querySearchAsync"
            s
            placeholder="搜索菜单"
            @select="handleSelect"
          ></el-autocomplete>
        </div>
        <div
          style="margin-right: 20px; cursor: pointer"
          @click="
            getList()
            isShow = true
          "
        >
          <i class="el-icon-message-solid"></i>
          <el-badge :is-dot="isDot1 || isDot2"></el-badge>
        </div>
        <shortcut />
        <template v-if="device !== 'mobile'">
          <!-- 全屏控制 -->
          <screenfull id="screenfull" class="right-menu-item hover-effect" />
        </template>
        <el-dropdown class="user-container" trigger="click">
          <div class="user right-menu-item hover-effect">
            <div class="flex">
              {{ Vue_Translation_Of_Text_Type }}
            </div>
          </div>
          <el-dropdown-menu slot="dropdown" class="user-dropdown">
            <el-dropdown-item divided @click.native="$setLanguage('zh')">
              <span style="display: block">中文</span>
            </el-dropdown-item>
            <el-dropdown-item divided @click.native="$setLanguage('ru')">
              <span style="display: block">俄文</span>
            </el-dropdown-item>
            <el-dropdown-item divided @click.native="$setLanguage('en')">
              <span style="display: block">英文</span>
            </el-dropdown-item>
            <el-dropdown-item divided @click.native="$setLanguage('ja')">
              <span style="display: block">日文</span>
            </el-dropdown-item>
            <el-dropdown-item divided @click.native="$setLanguage('ar')">
              <span style="display: block">阿拉伯文</span>
            </el-dropdown-item>
            <el-dropdown-item divided @click.native="$setLanguage('tr')">
              <span style="display: block">土耳其</span>
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <el-dropdown class="user-container" trigger="click">
          <div class="user right-menu-item hover-effect">
            <div class="flex">
              <i class="el-icon-user-solid" />
              <span :class="name.length > 5 ? 'ellipsis' : ''">{{ name }}</span>
            </div>
          </div>
          <el-dropdown-menu slot="dropdown" class="user-dropdown">
            <router-link :to="{ name: 'profile' }">
              <el-dropdown-item>个人信息</el-dropdown-item>
            </router-link>
            <el-dropdown-item divided @click.native="logout">
              <span style="display: block">退出登录</span>
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
    </div>
    <notice-bar />
    <el-drawer
      title="系统消息"
      :visible.sync="isShow"
      :append-to-body="true"
      :with-header="false"
      direction="rtl"
      size="25%"
    >
      <div class="message">
        <div class="head">
          <div class="flex_asb">
            <el-radio-group size="small" v-model="messageType" @change="getList">
              <el-badge :is-dot="isDot1" class="item">
                <el-radio-button
                  :label="[
                    'WBI',
                    'WBK',
                    'CRE_ORDER',
                    'SEND_MALL',
                    'RP_MALL',
                    'CR_SALES',
                    'ENGIN_PAY_ORDER',
                    'CR_ES_SALES'
                  ]"
                  >系统消息</el-radio-button
                >
              </el-badge>
              <el-badge :is-dot="isDot2" class="item">
                <el-radio-button :label="['NOTICE']">平台公告</el-radio-button>
              </el-badge>
            </el-radio-group>
            <el-switch
              v-model="isOpen"
              @change="updateIsNotice"
              inactive-text="消息弹窗"
              active-color="#13ce66"
              inactive-color="#ff4949"
            >
            </el-switch>
          </div>
          <el-radio-group size="mini" v-model="dateType" @change="getList" style="margin: 10px 0">
            <el-radio-button label="">全部</el-radio-button>
            <el-radio-button :label="0">今天</el-radio-button>
            <el-radio-button :label="1">昨天</el-radio-button>
            <el-radio-button :label="6">近7天</el-radio-button>
            <el-radio-button :label="29">近30天</el-radio-button>
          </el-radio-group>
          <div class="flex_asb">
            <el-radio-group size="mini" v-model="readFlag" @change="getList">
              <el-radio-button label="">全部</el-radio-button>
              <el-badge :hidden="count > 0 ? false : true" :value="count" class="item" style="margin: 0 10px">
                <el-radio-button label="NO">未读</el-radio-button>
              </el-badge>
              <el-badge :value="count" :hidden="true" class="item">
                <el-radio-button label="YES">已读</el-radio-button>
              </el-badge>
            </el-radio-group>
            <div style="color: #409eff; cursor: pointer" @click="confirmRead">
              <i class="el-icon-message-solid"></i>
              <span style="font-size: 14px">全部已读</span>
            </div>
          </div>
        </div>
        <el-card class="box-card" v-for="(item, index) in messageData" style="margin-top: 10px">
          <div
            @click="
              isShow = false
              toDetail(
                item.adminNoticeType,
                item.paidType,
                item.adminNoticeType == 'NOTICE' ? item.noticeId : item.orderId,
                item.id
              )
            "
          >
            <div v-if="item.adminNoticeType == 'NOTICE'">
              <div class="flex_asb item">
                <div>
                  <span>公告类型：</span>
                  <span>{{ statusFilter(item.adminNoticeType) }}</span>
                </div>
                <div class="read1" v-if="item.readFlag == 'NO'">未读</div>
                <div class="read2" v-if="item.readFlag == 'YES'">已读</div>
              </div>
              <div class="item">
                <div>
                  <span>文件标题：</span>
                  <span style="color: #409eff">{{ item.title }}</span>
                </div>
              </div>
              <div class="item">
                <div>
                  <span>发布人：</span>
                  <span>{{ item.issueNickName | '' }}</span>
                </div>
              </div>
              <div class="item">
                <div>
                  <span>发布时间：</span>
                  <span>{{ item.issueTime }}</span>
                </div>
              </div>
              <div v-if="item.readFlag == 'YES'" class="item">
                <span>阅读人：</span>
                <span>{{ item.adminNickName }} {{ item.readTime }}</span>
              </div>
            </div>
            <div v-else>
              <div class="flex_asb item">
                <div>
                  <span>消息类型：</span>
                  <span>{{ statusFilter(item.adminNoticeType) }}</span>
                </div>
                <div class="read1" v-if="item.readFlag == 'NO'">未读</div>
                <div class="read2" v-if="item.readFlag == 'YES'">已读</div>
              </div>
              <div class="item">
                <div>
                  <span>订单编号：</span>
                  <span style="color: #409eff">{{ item.orderId }}</span>
                </div>
              </div>
              <div class="item">
                <div>
                  <span>消息内容：</span>
                  <span>{{ item.content }}</span>
                </div>
              </div>
              <div class="item">
                <div>
                  <span>创建时间：</span>
                  <span>{{ item.createTime }}</span>
                </div>
              </div>
              <div v-if="item.readFlag == 'YES'" class="item">
                <span>阅读人：</span>
                <span>{{ item.adminNickName }} {{ item.readTime }}</span>
              </div>
            </div>
          </div>
        </el-card>
        <el-empty v-if="messageData.length == 0" description="暂无数据"></el-empty>
        <div class="flex_ac bottom">
          <el-pagination
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-size="pageSize"
            layout="prev, pager, next"
            background
            :total="listTotal"
          ></el-pagination>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import Hamburger from '@/components/Hamburger'
import Shortcut from '@/components/Shortcut'
import Screenfull from '@/components/Screenfull'
import NavMenu from '@/components/NavMenu'
import vScrollView from 'v-scroll-view'
import NoticeBar from '@/components/NoticeBar'
import { pages } from '@/settings'
import request from '@/utils/request'
function getc(obj) {
  if (!obj.children || !obj.children.length) {
    return obj
  } else {
    return getc(obj.children[0])
  }
}
export default {
  components: {
    NoticeBar,
    Hamburger,
    Screenfull,
    NavMenu,
    Shortcut,
    vScrollView
  },
  data() {
    return {
      Vue_Translation_Of_Text_Type: window?.Vue_Translation_Of_Text_Type || 'zh',
      pathurl: '',
      visible: false,
      noticeCount: 0,
      path: `/${this.$route.path.split('/')[1] || ''}`,
      isShow: false,
      isOpen: true,
      checked: false,
      messageType: ['WBI', 'WBK', 'CRE_ORDER', 'SEND_MALL', 'RP_MALL', 'CR_SALES', 'ENGIN_PAY_ORDER', 'CR_ES_SALES'],
      messageData: [],
      dateType: '',
      readFlag: '',
      timer: null,
      listTotal: 0,
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页数量
      count: 0,
      isDot1: false,
      isDot2: false
    }
  },
  computed: {
    routes() {
      return global.antRouter.filter(item => item.meta)
    },
    bigViewsBool() {
      return !!global.antRouter.find(item => item.code == 'bigViews')
    },
    noticeVisible() {
      return this.noticeCount > 0
    },
    ...mapGetters(['userid']),
    ...mapGetters(['sidebar', 'avatar', 'device', 'name', 'isNotice']),
    filterTime() {
      if (this.dateType === '') {
        return ['', '']
      } else {
        var date = new Date()
        var base = Date.parse(date) // 转换为时间戳
        var year = date.getFullYear() //获取当前年份
        var mon = date.getMonth() + 1 //获取当前月份
        var day = date.getDate() //获取当前日
        var oneDay = 24 * 3600 * 1000

        var daytimeArr = []
        var now = new Date(base - oneDay * this.dateType)
        var myear = now.getFullYear()
        var month = now.getMonth() + 1
        var mday = now.getDate()
        if (this.dateType == 1) {
          return [
            `${myear}-${month > 9 ? month : '0' + month}-${mday > 9 ? mday : '0' + mday} 00:00:00`,
            `${myear}-${month > 9 ? month : '0' + month}-${mday > 9 ? mday : '0' + mday} 23:59:59`
          ]
        } else {
          return [
            `${myear}-${month > 9 ? month : '0' + month}-${mday > 9 ? mday : '0' + mday} 00:00:00`,
            `${year}-${mon > 9 ? mon : '0' + mon}-${day > 9 ? day : '0' + day} 23:59:59`
          ]
        }
      }
    },
    statusFilter() {
      return function (val) {
        const MAP = {
          NOTICE: '平台公告',
          WBI: '维保消息费用申请',
          WBK: '维保费用申请审批',
          CRE_ORDER: '创建工单',
          SEND_MALL: '商城订单发货',
          RP_MALL: '商城订单维权',
          CR_SALES: '订单支付成功',
          ENGIN_PAY_ORDER: '工程收款单',
          CR_ES_SALES: '二手商品订单'
        }
        return MAP[val]
      }
    },
    typeFilter() {
      return function (val, paidType) {
        const MAP = {
          NOTICE: 'systemMessage',
          WBI: 'applicationWithoutFee',
          WBK: 'applicationWithoutFee',
          CRE_ORDER: 'workOrderPool',
          SEND_MALL: 'order_detail',
          RP_MALL: 'order_refund_detail',
          CR_SALES:
            paidType == 'M'
              ? 'auxiliarySalesOrder'
              : paidType == 'P'
              ? 'attachmentSalesOrder'
              : paidType == 'YB'
              ? 'orderSettleManag'
              : paidType == 'MALL'
              ? 'order_detail'
              : '',
          ENGIN_PAY_ORDER: 'projectCollectionManagement',
          CR_ES_SALES: 'orderManagement'
        }
        return MAP[val]
      }
    }
  },
  watch: {
    $route() {
      this.path = `/${this.$route.path.split('/')[1] || ''}`
    },
    path(newVal) {
      this.$store.commit('app/SET_L1_PATH', newVal)
      if (
        !~this.$route.path
          .split('/')
          .map(str => `/${str}`)
          .indexOf(newVal)
      ) {
        var item = getc(this.routes.find(item => item.path === newVal))
        if (item) {
          this.$router.push(item.path)
        }
      }
    }
  },
  created() {
    clearInterval(this.timer)
    this.getUserInfo()
    this.redDot()
  },
  mounted() {
    this.$store.commit('app/SET_L1_PATH', this.path)
  },
  methods: {
    tizhuanyemian(item) {
      if (item.type == 4) {
        this.$router.push({ name: item.name })
      } else {
        this.path = item.path
      }
    },

    goBigViews() {
      this.$router.push({
        name: 'bigViews'
      })
    },
    querySearchAsync(queryString, cb) {
      var data = pages.filter(
        item =>
          !~item.path.indexOf(':pageName?/:pageType?/:pageCode?/:pagePam?') && !!~item.meta.title.indexOf(queryString)
      )
      cb(
        data.map(item => ({
          value: item.meta.title,
          path: item.path
        }))
      )
    },
    handleSelect(item) {
      if (item.path) {
        this.$router.push({
          path: item.path
        })
      }
      this.pathurl = ''
    },
    async logout() {
      await this.$store.dispatch('user/logout')
      this.$store.commit('tagsView/SET_RESET_VIES')
      this.$router.push(`/login`)
    },
    toggleSideBar() {
      this.$store.dispatch('app/toggleSideBar')
    },
    //获取最新消息并弹窗
    getMessageTips() {
      const that = this
      this.timer = setInterval(() => {
        request({
          url: `/notice/list/out`,
          method: 'get',
          params: {
            num: 30
          }
        }).then(res => {
          res.data.forEach(item => {
            this.$notify({
              title: '新消息',
              position: 'bottom-right',
              duration: 30000,
              message: that.$createElement(
                'div',
                {
                  style: 'cursor: pointer;text-align: left;',
                  on: {
                    click: that.toDetail.bind(
                      that,
                      item.adminNoticeType,
                      item.paidType,
                      item.adminNoticeType == 'NOTICE' ? item.noticeId : item.orderId,
                      item.id
                    )
                  }
                },
                [
                  that.$createElement('span', null, that.statusFilter(item.adminNoticeType) + ' '),
                  that.$createElement(
                    'span',
                    {
                      style: 'color: #409EFF;'
                    },
                    ' ' + item.adminNoticeType == 'NOTICE' ? item.title : item.orderId
                  ),
                  that.$createElement('span', null, item.adminNoticeType == 'NOTICE' ? '' : item.content)
                  // that.$createElement(
                  // 	"el-checkbox",
                  // 	{
                  // 		on: {
                  // 			change: that.updateIsNotice.bind(that)
                  // 		},
                  // 	}, '不再弹窗新消息'
                  // )
                ]
              )
            })
          })
        })
      }, 30000)
    },
    getCount() {
      request({
        url: `/notice/list/count`,
        method: 'get',
        params: {
          noticeType: this.messageType.join(','),
          readFlag: 'NO'
        }
      }).then(res => {
        this.count = res.data
      })
    },
    redDot() {
      request({
        url: `/notice/list/count`,
        method: 'get',
        params: {
          noticeType: ['WBI', 'WBK', 'CRE_ORDER', 'SEND_MALL', 'RP_MALL', 'CR_SALES'].join(','),
          readFlag: 'NO'
        }
      }).then(res => {
        this.isDot1 = res.data > 0 ? true : false
      })
      request({
        url: `/notice/list/count`,
        method: 'get',
        params: {
          noticeType: ['NOTICE'].join(','),
          readFlag: 'NO'
        }
      }).then(res => {
        this.isDot2 = res.data > 0 ? true : false
      })
    },
    getUserInfo() {
      const that = this
      request({
        url: `/admin/user/detail`,
        method: 'get',
        params: {
          adminUserId: this.userid
        }
      }).then(res => {
        this.isOpen = res.data.isNotice == 'YES' ? true : false
        if (res.data.isNotice == 'NO') {
          clearInterval(this.timer)
        } else {
          clearInterval(this.timer)
          this.getMessageTips()
        }
      })
    },
    //全部已读
    confirmRead() {
      this.$confirm('是否全部设为已读, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          request({
            url: `/notice/mark/read/all`,
            method: 'post',
            data: {}
          }).then(res => {
            if (res.code == 200) {
              this.getList()
              this.$message.success('全部已读成功！')
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
    },
    //点击不再弹窗新消息
    updateIsNotice(e) {
      request({
        url: `/notice/updateIsNotice`,
        method: 'post',
        params: {
          isNotice: e ? 'YES' : 'NO'
        }
      }).then(res => {
        if (res.code == 200) {
          this.getUserInfo()
          this.$message.success(e ? '已开启弹窗消息提醒' : '已关闭弹窗消息提醒')
          if (!e) {
            clearInterval(this.timer)
          }
        }
      })
    },
    getList() {
      request({
        url: `/notice/list`,
        method: 'post',
        data: {
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          params: [
            { param: 'nr.read_flag', compare: '=', value: this.readFlag },
            { param: 'nr.admin_notice_type', compare: '=', value: this.messageType },
            { param: 'nr.issue_time', compare: '>=', value: this.filterTime[0] },
            { param: 'nr.issue_time', compare: '<=', value: this.filterTime[1] }
          ]
        }
      }).then(res => {
        this.getCount()
        this.redDot()
        this.listTotal = res.data.total
        this.messageData = res.data.records
      })
    },
    // 更改当前页
    handleCurrentChange(val) {
      this.currentPage = val
      this.getList()
    },
    toDetail(type, paidType, orderId, id) {
      console.log(this.typeFilter(type, paidType))
      this.read(id)
      this.$router.push({
        name: this.typeFilter(type, paidType),
        params: {
          pageName: orderId,
          pageType: 'detail',
          pageCode: orderId
        },
        query: {
          id: orderId,
          orderId: orderId
        }
      })
    },
    read(id) {
      request({
        url: `/notice/mark/read`,
        method: 'post',
        params: {
          noticeIds: id
        }
      }).then(res => {})
    }
  }
}
</script>

<style lang="scss" scoped>
@import '~@/styles/variables.scss';
// ::v-deep .el-drawer__container{
//   top: 50px;

// }
::v-deep .is-fixed {
  right: 10px !important;
}

::v-deep .slidingBgClassName {
  background: rgba(0, 0, 0, 0.01) !important;
}

::v-deep .slidingBlockClassName {
  background: rgba(0, 0, 0, 0.05) !important;
}

.flex_asb {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.flex_ac {
  display: flex;
  justify-content: center;
}

.message {
  padding: 20px;
  position: relative;
  min-height: 100%;
  padding-bottom: 60px;
  padding-top: 150px;
  box-sizing: border-box;

  .head {
    width: 25%;
    position: fixed;
    top: 0;
    right: 0;
    background: #ffffff;
    padding: 20px;
  }

  .bottom {
    width: 25%;
    position: fixed;
    bottom: 0;
    right: 0;
    background: #ffffff;
    padding: 10px 0;
  }
}

.box-card {
  .item {
    cursor: pointer;
    margin-bottom: 6px;
  }

  .read1 {
    color: #f5680e;
    background: #fff2da;
    padding: 2px 4px;
    border-radius: 4px;
    font-size: 14px;
  }

  .read2 {
    color: #42b983;
    background: #d7fdde;
    padding: 2px 4px;
    border-radius: 4px;
    font-size: 14px;
  }
}

.navbar {
  width: 100%;
  height: 50px;
  overflow: hidden;
  background: #{$navbarBg};
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
  display: flex;
  flex-direction: row;
  align-items: center;

  .hamburger-container {
    line-height: 46px;
    height: 100%;
    color: #{$navbarText};
    cursor: pointer;
    transition: background 0.3s;
    -webkit-tap-highlight-color: transparent;
    border-right: 1px solid #eaeaea;

    &:hover {
      background: rgba(0, 0, 0, 0.025);
    }
  }

  .menu_module {
    height: 100%;
    flex: 1;
    position: relative;

    .menu_module_view {
      position: absolute;
      top: 0;
      left: 0;
      bottom: 0;
      right: 0;

      .menu_module_fj {
        height: 100%;
        width: fit-content;
        white-space: nowrap;
        box-sizing: border-box;
        padding: 0 10px;

        .item {
          display: inline-block;
          height: 100%;
          line-height: 50px;
          box-sizing: border-box;
          padding: 0 10px;
          cursor: pointer;
          font-size: 14px;
        }

        .select {
          border-bottom: 1px solid #000;
        }
      }
    }
  }

  .flex {
    display: flex;
    align-items: center;
  }

  .ellipsis {
    display: inline-block;
    width: (16px * 6);
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .right-menu {
    height: 100%;
    line-height: 50px;

    & > div {
      float: left;
    }

    &:focus {
      outline: none;
    }

    .user-container {
      height: 50px;

      .user {
        i {
          font-size: 18px;
          margin-right: 5px;
        }

        span {
          font-size: 16px;
        }
      }
    }

    .right-menu-item {
      display: inline-block;
      padding: 0 15px;
      height: 100%;
      font-size: 18px;
      color: #{$navbarText};
      vertical-align: text-bottom;
      border-left: 1px solid #eaeaea;

      &.hover-effect {
        cursor: pointer;
        transition: background 0.3s;

        &:hover {
          background: rgba(0, 0, 0, 0.025);
        }
      }

      .notice-icon {
        padding-top: 0;
        padding-bottom: 0;
      }

      .right-menu-item {
        .notice-icon > i {
          font-size: 18px;
        }

        sup {
          top: 12px;
          right: 25px;
        }
      }
    }
  }
}

::v-deep .el-badge__content.is-fixed {
  z-index: 99;
}
</style>
