<template>
  <div class="navbar">
    <hamburger id="hamburger-container" :is-active="appStore.sidebar.opened" class="hamburger-container"
      @toggleClick="toggleSideBar" />
    <breadcrumb id="breadcrumb-container" class="breadcrumb-container" v-if="!settingsStore.topNav" />
    <top-nav id="topmenu-container" class="topmenu-container" v-if="settingsStore.topNav" />

    <div class="right-menu">
      <div style="color: #fff; padding-right: 16px; font-size: 14px">
        <span>当前厂别：</span>
        <template v-if="currentTenantName != '超级管理员'">
          <span style="cursor: pointer" @click="handleShowTenantDialog">{{ currentTenantName }}</span>
        </template>
        <template v-else>
          <span style="cursor: pointer">{{ currentTenantName }}</span>
        </template>
        <el-badge :value="messageCount" :max="99" class="navbar-item" :hidden="messageCount == 0">
          <el-icon style="margin-left: 10px;" @click="handleShowMessageDialog">
            <ChatDotRound />
          </el-icon>
          <!-- <span style="margin-left: 10px;cursor: pointer">站内信</span> -->
        </el-badge>
        <!-- <span style="cursor: pointer"  @click="handleShowTenantDialog">{{ currentTenantName }}</span> -->
      </div>
      <template v-if="appStore.device !== 'mobile'">
        <!--
        <header-search id="header-search" class="right-menu-item" />
        <el-tooltip content="源码地址" effect="dark" placement="bottom">
          <ruo-yi-git id="ruoyi-git" class="right-menu-item hover-effect" />
        </el-tooltip>
        <el-tooltip content="文档地址" effect="dark" placement="bottom">
          <ruo-yi-doc id="ruoyi-doc" class="right-menu-item hover-effect" />
        </el-tooltip> 
        <screenfull id="screenfull" class="right-menu-item hover-effect" />
        <el-tooltip content="布局大小" effect="dark" placement="bottom">
          <size-select id="size-select" class="right-menu-item hover-effect" />
        </el-tooltip>
        -->
      </template>
      <div class="avatar-container">
        <el-dropdown @command="handleCommand" class="right-menu-item hover-effect" trigger="click">
          <div class="avatar-wrapper">
            <img :src="userStore.avatar" class="user-avatar" />
            <el-icon><caret-bottom /></el-icon>
          </div>
          <template #dropdown>
            <el-dropdown-menu>
              <router-link to="/user/profile">
                <el-dropdown-item>个人中心</el-dropdown-item>
              </router-link>
              <el-dropdown-item command="setLayout">
                <span>布局设置</span>
              </el-dropdown-item>
              <!-- <el-dropdown-item command="message" v-if="settingsStore.showMessage">
                <el-badge :value="messageCount" :max="99" class="item" :hidden="messageCount == 0">
                  <span>站内信</span>
                </el-badge>
              </el-dropdown-item> -->
              <!-- <el-dropdown-item command="sendMessage" v-if="settingsStore.showMessage">
                <span>发站内信</span>
              </el-dropdown-item> -->
              <el-dropdown-item divided command="logout">
                <span>退出登录</span>
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>

    <el-dialog title="切换厂别" v-model="showDialog" width="450" top="10vh" center @close="showDialog = false">
      <el-table :data="tenantList" v-loading="tenantLoading">
        <el-table-column label="厂别" prop="orgName" header-align="center" />
        <el-table-column label="选择" prop="createTime" width="50" align="center">
          <template #default="scope">
            <el-button link type="success" icon="Check" size="small"
              @click="handleChangeTenant(scope.row)">选择</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    <el-dialog title="站内信" v-model="showMessageDialog" width="650" center @close="showMessageDialog = false">
      <div class="page-container column-container">
        <el-table ref="dialogTable" :data="messageList" height="460px" row-key="id" align="center">
          <el-table-column label="行号" type="index" width="50" align="center" />
          <el-table-column label="消息来源" prop="fromNickName" align="center" width="80" />
          <el-table-column label="消息内容" prop="message" align="center" show-overflow-tooltip />
          <el-table-column label="状态" prop="msgRead" align="center" width="50">
            <template #default="scope">
              <el-tag v-if="scope.row.msgRead == 0" type="warning">未读</el-tag>
              <el-tag v-else type="info">已读</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="查看" width="120" align="center">
            <template #default="scope">
              <el-button type="success" icon="view" circle @click="handleView(scope.row)" />
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize" @pagination="getMessages" size="small"
          layout="total, prev, next, jumper" />
      </div>
    </el-dialog>
    <el-dialog title="发消息" v-model="addMessageDialog" width="450" center @close="closeMessageFormDialog">
      <el-form ref="addMessageFormRef" v-model="messageData" label-width="100">
        <el-row :gutter="10">
          <el-col :span="24">
            <el-form-item label="收件人">
              <el-autocomplete :fetch-suggestions="querySearchAsync" :trigger-on-focus="true" style="width: 100%"
                v-model="messageData.toNickName" placeholder="选择人员" popper-class="my-autocomplete"
                @select="handleSelectEmployee">
                <template #default="{ item }">
                  <div style="
                      display: flex;
                      flex-direction: row;
                      justify-content: space-between;
                    ">
                    <div class="name" style="font-size: 12px">
                      {{ item.nickName }}
                    </div>
                    <span class="code" style="font-size: 10px; color: darkgrey">{{ item.userName }}</span>
                  </div>
                </template>
              </el-autocomplete>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="发送信息">
              <el-input type="textarea" v-model="messageData.message"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="sendMessage">发送</el-button>
      </template>
    </el-dialog>
    <el-dialog title="查看站内信" v-model="viewMessageDialog" :width="450" center @close="closeViewMessageDialog">
      <el-form ref="addMessageFormRef" v-model="messageData" label-width="100">
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="发件人">
              <div>{{ messageData.fromNickName }}</div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="收件人">
              <div>{{ messageData.toNickName }}</div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="信息">
              <div v-html="messageData.message"></div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup>
import { ElMessageBox } from 'element-plus'
import Breadcrumb from '@/components/Breadcrumb'
import TopNav from '@/components/TopNav'
import Hamburger from '@/components/Hamburger'
import Screenfull from '@/components/Screenfull'
import { selectUserList, getInfo } from "@/api/business/noCurrentReject";
// import SizeSelect from '@/components/SizeSelect'
// import HeaderSearch from '@/components/HeaderSearch'
// import RuoYiGit from '@/components/RuoYi/Git'
// import RuoYiDoc from '@/components/RuoYi/Doc'
import useAppStore from '@/store/modules/app'
import useUserStore from '@/store/modules/user'
import useSettingsStore from '@/store/modules/settings'
import { setTenant, getTenant } from '@/utils/auth'
import { listTenant } from '@/api/business/tenant.js'
import { listMessage, readMessage } from '@/api/business/message.js'
import router from '@/router'
import useMessageStore from '@/store/modules/message'
import { nextTick, onBeforeUnmount, onMounted } from 'vue'

const { proxy } = getCurrentInstance()
const appStore = useAppStore()
const userStore = useUserStore()
const settingsStore = useSettingsStore()
const messageCount = ref(0)
const showMessageDialog = ref(false)
const tenantLoading = ref(false)
const showDialog = ref(false)
const addMessageDialog = ref(false)
const tenantList = ref([])
const messageList = ref([])
const viewMessageDialog = ref(false)
const messageData = ref({
  fromUserId: useUserStore().user.userId,
  toUserId: null,
  toUserName: null,
  toNickName: null,
  message: null
})
const currentTenantName = ref(getTenant().tenantName)
const total = ref(0)
const queryParams = ref({
  pageSize: 10,
  pageNum: 1
})

function toggleSideBar() {
  appStore.toggleSideBar()
}

function handleCommand(command) {
  switch (command) {
    case 'setLayout':
      setLayout()
      break
    case 'logout':
      logout()
      break
    case 'message':
      showMessageDialog.value = true
      getMessages()
      break
    case 'sendMessage':
      addMessageDialog.value = true
      break
    default:
      break
  }
}

function logout() {
  ElMessageBox.confirm('确定注销并退出系统吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      userStore.logOut().then(() => {
        setTenant({})
        location.href = '/index'
      })
    })
    .catch(() => { })
}

const emits = defineEmits(['setLayout'])
function setLayout() {
  emits('setLayout')
}

const handleShowTenantDialog = () => {
  showDialog.value = true
  loadTenant()
}

const handleChangeTenant = (row) => {
  ElMessageBox.confirm('确定切换到该厂别吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      // 切换
      setTenant({ tenantId: row.id, tenantName: row.orgName })
      currentTenantName.value = row.orgName
      showDialog.value = false
      // 更换厂别后，刷新当前路由
      const { path, query } = router.currentRoute.value
      router.replace({
        path: '/redirect' + path,
        query: query
      })
      location.reload()
    })
    .catch(() => { })
}

const loadTenant = () => {
  tenantLoading.value = true
  listTenant().then((res) => {
    if (res.code === 200) {
      tenantList.value = res.rows
    }
    tenantLoading.value = false
  })
}

const messageCountChanged = (count) => {

}
const getMessages = () => {
  console.log(userStore)
  queryParams.value.toUserId = useUserStore().user.userId
  listMessage(queryParams.value).then(res => {
    if (res.code === 200) {
      messageList.value = res.rows
      total.value = res.total
    } else {
      messageList.value = []
      total.value = 0
    }

  })
}

const closeMessageFormDialog = () => {
  addMessageDialog.value = false
  messageData.value = {
    fromUserId: useUserStore().user.userId,
    toUserId: null,
    toUserName: null,
    toNickName: null,
    message: null
  }
}
function querySearchAsync(queryString, cb) {
  if (queryString) {
    selectUserList(queryString).then((res) => {
      cb(res.rows);
    });
  }
}

function handleSelectEmployee(item) {
  messageData.value.toNickName = item.nickName;
  messageData.value.toUserId = item.userId;
  messageData.value.toUserName = item.userName;
}

function sendMessage() {
  useMessageStore().sendMsg(messageData.value)
  closeMessageFormDialog()
}

onMounted(() => {
  window.addEventListener('messageChange', (target) => {
    const count = target.detail
    if (count != messageCount.value) {
      messageCount.value = count
    }
    // console.log(messageCount)
  })
})
onBeforeUnmount(() => {
  window.removeEventListener('messageChange')
})

function handleView(row) {
  viewMessageDialog.value = true
  readMessage(row)
  messageData.value = row
}
function closeViewMessageDialog() {
  getMessages()
}

function handleShowMessageDialog() {
  showMessageDialog.value = true
  getMessages()
}
</script>

<style lang="scss" scoped>
.navbar {
  height: 50px;
  overflow: hidden;
  position: relative;
  background: #282b33;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);

  .hamburger-container {
    line-height: 46px;
    height: 100%;
    float: left;
    cursor: pointer;
    transition: background 0.3s;
    -webkit-tap-highlight-color: transparent;
    color: #fff;

    &:hover {
      background: rgba(255, 255, 255, 0.1);
    }
  }

  .breadcrumb-container {
    float: left;
  }

  .topmenu-container {
    position: absolute;
    left: 50px;
  }

  .errLog-container {
    display: inline-block;
    vertical-align: top;
  }

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

    &:focus {
      outline: none;
    }

    .right-menu-item {
      display: inline-block;
      padding: 0 8px;
      height: 100%;
      font-size: 18px;
      color: #5a5e66;
      vertical-align: text-bottom;

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

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

    .avatar-container {
      margin-right: 40px;

      .avatar-wrapper {
        margin-top: 5px;
        position: relative;

        .user-avatar {
          cursor: pointer;
          width: 40px;
          height: 40px;
          border-radius: 10px;
        }

        i {
          cursor: pointer;
          position: absolute;
          right: -20px;
          top: 25px;
          font-size: 12px;
        }
      }
    }
  }
}
</style>
<style>
.navbar-item .el-badge__content.is-fixed {
  top: 10px;
}
</style>
