<template>
  <div class="head-com">
    <div class="logo">
      <img src="@/assets/images/logo.png" />
    </div>
    <div class="title">{{ titleCpt }}</div>
    <div class="menus">
      <template v-for="item in menusCpt.children.filter((v) => !v.meta.root)">
        <div
          class="menu-item __hover"
          :class="{
            active:
              $route.matched.some((v) => v.name === item.name) ||
              $route.meta.root === item.name,
          }"
          @click="$router.push(item.path)"
        >
          {{ item.meta.title }}
        </div>
      </template>
    </div>
    <div class="mr-4 ml-auto">
      <el-button type="primary" @click="state.drawer = true"
        >临时字典</el-button
      >
    </div>
    <el-dropdown :disabled="AppStore.tenants.length < 2">
      <div class="__hover flex items-center gap-2 text-[#303133]">
        {{ AppStore.tenantInfo?.name }}
        <SvgIcon
          name="czr_arrow"
          :rotate="90"
          size="10"
          color="#303133"
          v-if="AppStore.tenants.length > 1"
        />
      </div>
      <template #dropdown>
        <el-dropdown-menu>
          <template
            v-for="item in AppStore.tenants.filter(
              (v) => v.id !== AppStore.tenantInfo?.id,
            )"
          >
            <el-dropdown-item @click="onChangeTenant(item)">{{
              item.name
            }}</el-dropdown-item>
          </template>
        </el-dropdown-menu>
      </template>
    </el-dropdown>
    <el-dropdown>
      <div
        class="__hover mr-4 ml-4 flex items-center gap-2 text-sm text-[#303133]"
      >
        <img src="@/assets/images/avatar-default.png" class="size-8" />
        {{ AppStore.userInfo?.name }}
        <SvgIcon name="czr_arrow" :rotate="90" size="10" color="#303133" />
      </div>
      <template #dropdown>
        <el-dropdown-menu>
          <el-dropdown-item @click="logout">退出登录</el-dropdown-item>
        </el-dropdown-menu>
      </template>
    </el-dropdown>
    <el-drawer v-model="state.drawer" title="临时字典管理">
      <div class="h-full w-full overflow-y-auto">
        <el-collapse v-model="state.activeNames">
          <template v-for="[key, value] in state.dictMap">
            <el-collapse-item :name="key">
              <template #title>
                <el-button
                  type="primary"
                  size="small"
                  @click.stop="copyDict(value.name, key)"
                  >复制</el-button
                >
                {{ `${value.name} ${key}` }}
              </template>

              <el-descriptions :column="1" border>
                <template v-for="item in value.children">
                  <el-descriptions-item>
                    <template #label>
                      <div @click="copy(item.dictValue)">
                        {{ item.dictValue }}
                      </div>
                    </template>
                    {{ item.dictName }}
                  </el-descriptions-item>
                </template>
              </el-descriptions>
            </el-collapse-item>
          </template>
        </el-collapse>
      </div>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { computed, getCurrentInstance, onMounted, reactive } from 'vue'
import { useAppStore, useDialogStore, useDictionaryStore } from '@/stores'
import { useRoute, useRouter } from 'vue-router'
import { sysDict } from '@/api/modules/global/dictionary'
import { copy } from '@/utils/czr-util'
import { ElMessage } from 'element-plus'
import { loginChangeTenant, loginLogout } from '@/api/modules/global/login'

const AppStore = useAppStore()
const DictionaryStore = useDictionaryStore()
const DialogStore = useDialogStore()
const router = useRouter()
const route = useRoute()
const state: any = reactive({
  drawer: false,
  dictMap: new Map(),
  activeNames: '',
})
const titleCpt = computed(() => import.meta.env.VITE_TITLE)
const menusCpt: any = computed(() => {
  return router.getRoutes().filter((v) => v.name === 'root')[0]
})

const copyDict = (label, value) => {
  try {
    const key = value.replace(/_([a-z])/g, (match, letter) =>
      letter.toUpperCase(),
    )
    const str = `${value}: ['${key}List', '${key}Map'], //  ${label}`
    copy(str)
    ElMessage.success('复制成功')
  } catch (e) {
    console.log(e)
  }
}
const onChangeTenant = (row) => {
  DialogStore.confirm({
    content: `请确认是否切换到租户${row.name}？`,
    onSubmit: () => {
      loginChangeTenant(row.id)
        .then(({ data }: any) => {
          localStorage.setItem((import.meta as any).env.VITE_TOKEN, data)
          window.location.reload()
        })
        .catch(() => {})
        .finally(() => {})
    },
  })
}
const logout = () => {
  DialogStore.confirm({
    content: `请确认是否退出登录？`,
    onSubmit: () => {
      loginLogout()
        .then(({ data }: any) => {
          localStorage.clear()
          window.location.reload()
        })
        .catch(() => {})
        .finally(() => {})
    },
  })
}
onMounted(() => {
  sysDict().then(({ data }: any) => {
    data.forEach((v) => {
      const d = state.dictMap.get(v.dictType)
      if (d) {
        d.children.push(v)
      } else {
        state.dictMap.set(v.dictType, { name: v.remark, children: [v] })
      }
    })
  })
})
</script>

<style lang="scss" scoped>
.head-com {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  .logo {
    margin-left: 1.5rem;
  }
  .title {
    margin-left: 0.75rem;
    font-weight: bold;
    font-size: 1.38rem;
    background: linear-gradient(180deg, #3dc8fe 0%, #2d6bd0 46%, #6255f6 100%);
    color: transparent;
    background-clip: text;
    font-family: Alimama;
    word-break: keep-all;
  }
  .menus {
    margin-left: 5rem;
    display: flex;
    align-items: center;
    gap: 3.13rem;
    .menu-item {
      font-weight: bold;
      font-size: 1.13rem;
      color: #303133;
      word-break: keep-all;
      &.active {
        color: var(--czr-main-color);
      }
    }
  }
}
</style>
