<template>
  <div>
    <el-row
        class="flex flex-align-center flex-justify-between top"
        :class="dataType === 'project' ? 'bread' : 'bread-g'"
    >
      <el-col :span="12">
        <div class="flex flex-justify-start flex-align-center padding">
          <el-button
              icon="Menu"
              class="mr-20 white"
              circle
              color="#C1C4CB"
              @click="openMenu"
              v-if="mini && showMenu"
          />
          <router-link to="/">
            <div class="flex flex-center">
              <img v-if="dataType === 'project'" src="@/assets/svg/logo.svg"/>
              <img v-else src="@/assets/svg/logo-white.svg"/>
            </div>
          </router-link>
        </div>
      </el-col>
      <el-col :span="12">
        <div class="flex-child-average flex-justify-end flex padding-right">
          <div
              class="padding flex flex-align-center pointer"
              :class="dataType === 'project' ? 'black' : 'white'"
          >
            <!--            <el-button-->
            <!--              icon="Search"-->
            <!--              circle-->
            <!--              color="#C1C4CB"-->
            <!--              @click="show = true"-->
            <!--            />-->

            <el-badge
                :value="msgCount"
                :max="99"
                class="ml-20"
                :hidden="msgCount === null || msgCount === 0"
            >
              <el-button
                  icon="Bell"
                  circle
                  color="#C1C4CB"
                  @click="$router.push('/msg')"
              />
            </el-badge>
          </div>
          <div class="padding flex flex-align-center pointer">
            <el-avatar
                class="mr-10"
                :size="30"
                :src="
                user.info.avatarUrl && user.info.avatarUrl.length > 0
                  ? user.info.avatarUrl
                  : 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
              "
            />
            <el-dropdown @command="dropDown">
              <span class="flex flex-center">
                {{ user.info.userName }} / {{ user.info.deptName }}
                <el-icon class="el-icon--right">
                  <arrow-down/>
                </el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="info">个人中心</el-dropdown-item>
                  <el-dropdown-item command="manage">用户管理</el-dropdown-item>
                  <el-dropdown-item command="logout">退出登录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </el-col>
    </el-row>
    <search :show="show" @close="show = false"/>
  </div>
</template>

<script>
import navStore from '../store/nav.js'
import {useStore} from '../store/user.js'
import permissionStore from '@/store/permission.js'
import search from './search/index.vue'
import config from '../config/website.js'

export default {
  name: 'top',
  components: {search},
  setup() {
    const nav = navStore()
    const user = useStore()
    const permission = permissionStore()
    return {nav, user, permission}
  },
  props: {
    showMenu: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      lockReconnect: false, // 是否真正建立连接
      timeout: 58 * 1000, // 58秒一次心跳
      timeoutObj: null, // 心跳心跳倒计时
      serverTimeoutObj: null, // 心跳倒计时
      timeoutnum: null, // 断开 重连倒计时
      dataType: 'project',
      showImage: false,
      imgList: [],
      show: false,
      keywords: '',
      active: 0,
      type: [
        {
          key: 'project',
          value: '项目',
          count: 0
        },
        {
          key: 'file',
          value: '文档',
          count: 0
        },
        {
          key: 'picture',
          value: '图片',
          count: 0
        }
      ],
      params: {
        keyword: '',
        searchType: 'project',
        pages: 1,
        size: 10
      },
      data: [],
      total: '',
      isAll: 1,
      filterTypeName: '全部',
      resultCount: 0,
      title: '',
      mini: false,
      msgCount: 0
    }
  },
  created() {
    const tmp = localStorage.getItem('data-type')
    this.title = config.title
    if (tmp) {
      this.dataType = tmp
    }
    this.$bus.on('navChange', res => {
      console.log(res)
      this.dataType = res
    })
    this.$bus.on('sizeChange', res => {
      if (res < 1690) {
        this.mini = true
      } else {
        this.mini = false
      }
    })
    this.$bus.on('read', () => {
      this.msgCount = this.msgCount - 1
    })
    this.initWebSocket()
  },
  mounted() {
    this.initWebSocket()
    this.readCount()
  },
  unmounted() {
    this.websock.close() // 离开路由之后断开websocket连接
  },
  methods: {
    readCount() {
      this.$api.msg.count().then(res => {
        if (res.code === 200) {
          this.msgCount = res.data
        }
      })
    },
    initWebSocket() {
      const wsuri =
          location.host.indexOf('dev') > -1
              ? 'wss://dev.wutongshucloud.com/ws/websocket/' + this.user.info.userId
              : config.wss + this.user.info.userId
      this.websock = new WebSocket(wsuri)
      this.websock.onmessage = this.websocketonmessage
      // 连接建立时触发
      this.websock.onopen = this.websocketonopen
      // 通信发生错误时触发
      this.websock.onerror = this.websocketonerror
      // 连接关闭时触发
      this.websock.onclose = this.websocketclose
    },
    websocketonopen() {
      // 开启心跳
      this.start()
      // 连接建立之后执行send方法发送数据
      // const actions = {
      //   room: '007854ce7b93476487c7ca8826d17eba',
      //   info: '1121212'
      // }
      // this.websocketsend(JSON.stringify(actions))
    },
    // 通信发生错误时触发
    websocketonerror() {
      console.log('出现错误')
      this.reconnect()
    },
    // 客户端接收服务端数据时触发
    websocketonmessage(e) {
      console.log(e.data)
      const json = JSON.parse(e.data)
      // 收到服务器信息，心跳重置
      this.readCount()
      this.$notify({
        message: json.msgTxt,
        type: 'warning'
      })
      this.reset()
    },
    websocketsend(Data) {
      // 数据发送
      this.websock.send(Data)
    },
    // 连接关闭时触发
    websocketclose(e) {
      // 关闭
      console.log('断开连接', e)
      // 重连
      this.reconnect()
    },
    reconnect() {
      // 重新连接
      const that = this
      if (that.lockReconnect) {
        return
      }
      that.lockReconnect = true
      // 没连接上会一直重连，设置延迟避免请求过多
      that.timeoutnum && clearTimeout(that.timeoutnum)
      that.timeoutnum = setTimeout(function () {
        // 新连接
        that.initWebSocket()
        that.lockReconnect = false
      }, 5000)
    },
    reset() {
      // 重置心跳
      const that = this
      // 清除时间
      clearTimeout(that.timeoutObj)
      clearTimeout(that.serverTimeoutObj)
      // 重启心跳
      that.start()
    },
    start() {
      // 开启心跳
      console.log('开启心跳')
      const self = this
      self.timeoutObj && clearTimeout(self.timeoutObj)
      self.serverTimeoutObj && clearTimeout(self.serverTimeoutObj)
      self.timeoutObj = setTimeout(function () {
        // 这里发送一个心跳，后端收到后，返回一个心跳消息，
        console.log(self.websock)
        if (self.websock.readyState === 1) {
          // 如果连接正常
          self.websock.send('heartCheck') // 这里可以自己跟后端约定
        } else {
          // 否则重连
          // self.reconnect()
        }
        self.serverTimeoutObj = setTimeout(function () {
          // 超时关闭
          // self.websock.close()
        }, self.timeout)
      }, self.timeout)
    },

    dropDown(res) {
      if (res === 'info') {
        this.$router.push('/user')
      } else if (res === 'manage') {
        this.$router.push('/user/manage')
      } else if (res === 'logout') {
        this.$api.login.logout().then(res => {
          if (res.success === 'true') {
            this.nav.cleanMenu()
            try {
              // this.permission.cleanPermission()
            } catch (err) {
              console.log(err)
            }

            this.$message.success('退出登录')
            this.$router.replace('/login')
          } else {
            this.$message.error(res.msg)
          }
        })
      } else if (res === '全部') {
        this.filterTypeName = res
        this.params.searchType = 'all'
        this.isAll = 1
        this.searchTotal()
      } else if (res === '项目') {
        this.filterTypeName = res
        this.isAll = 0
        this.params.searchType = 'project'
        this.searchTotal()
      } else if (res === '文档') {
        this.filterTypeName = res
        this.isAll = 0
        this.params.searchType = 'file'
        this.searchTotal()
      } else if (res === '图片') {
        this.filterTypeName = res
        this.isAll = 0
        this.params.searchType = 'picture'
        this.searchTotal()
      }
    },
    change(index, key) {
      this.active = index
      this.params.searchType = key
      if (this.params.searchType === 'all') {
        this.isAll = 1
        this.getTotal()
        this.$api.project.totalSearch(this.params).then(res => {
          if (res.code === 200) {
            this.data = res.data.result
            this.total = res.data.total
          }
        })
      } else {
        this.getTotal()
        this.$api.project.totalSearch(this.params).then(res => {
          if (res.code === 200) {
            this.data = res.data.result
            this.total = res.data.total
          }
        })
      }
    },
    searchTotal(res) {
      if (res.key === 'Enter' || res === 1) {
        this.getTotal()
        this.$api.project.totalSearch(this.params).then(res => {
          if (res.code === 200) {
            this.data = res.data.result
            this.total = res.data.total
          }
        })
      }
    },
    getTotal() {
      this.resultCount = 0
      this.$api.project.total({keyword: this.params.keyword}).then(res => {
        if (res.code === 200) {
          this.type[0].count = res.data.projectTotal
          this.type[1].count = res.data.fileTotal
          this.type[2].count = res.data.pictureTotal
          this.type.forEach(sub => {
            this.resultCount = this.resultCount + sub.count
          })
        }
      })
    },
    detail(res) {
      if (this.params.searchType === 'project') {
        this.$api.project.projectInfo(res.projectId).then(res => {
          if (res.code === 200) {
            console.log(res)
            this.$router.push({
              path: '/home/details',
              query: {
                id: res.data.id,
                type: '0',
                ownerId: res.data.createUser
              }
            })
          }
        })
        this.show = false
      } else if (this.params.searchType === 'file') {
        const routeData = this.$router.resolve({
          path: '/home/file_detail',
          query: {
            id: res.fileId.replace('fileid-', ''),
            search: true,
            keywords: this.params.keyword
          }
        })
        window.open(routeData.href, '_blank')
      } else if (this.params.searchType === 'picture') {
        this.imgList = [res.url]
        this.showImage = true
      }
    },
    /**
     * 高级搜索框关闭
     */
    close() {
      this.params.keyword = ''
      this.show = false
    },
    openMenu() {
      this.$emit('openMenu')
    }
  }
}
</script>

<style lang="scss" scoped>
.top {
  height: 60px;
  z-index: 22;
  top: 0;
  left: 0;
  right: 0;
  padding: 0 40px;
  position: fixed;
  border-bottom: whitesmoke solid 1px;
  box-shadow: 0 6px 8px 0 rgba(51, 51, 51, 0.05098);
}

.avatar {
  background-color: #c4c3c3;
  width: 30px;
  height: 30px;
  border-radius: 15px;
}

.tab {
  width: 238px;
  height: 38px;
  background-color: #edf0f3;
  padding: 2px 10px;
  color: #707070;
  font-size: 13px;
}

.tab-active {
  width: 160px;
  flex-wrap: nowrap;
  color: white;
  font-size: 15px;
  background-color: #ab7630;
  font-weight: 500;
  padding: 4px 10px;
  border-radius: 20px;
  text-align: center;
}

.bread {
  background: white;
  color: black;
  min-width: 1300px;
}

:deep(.el-icon) {
  --color: white !important;
}

.bread-g {
  background: #3978f1;
  min-width: 1300px;

  :deep(.el-breadcrumb__inner a) {
    color: white;
  }

  :deep(.el-dropdown) {
    color: white;
  }

  :deep(.el-icon) {
    color: white;
  }

  :deep(.el-breadcrumb__separator) {
    color: white;
  }
}
</style>
