<template>
  <el-container class="home" v-loading="loading">
    <!--    侧边导航icon -->
    <el-aside width="60px" class="aside">
      <div>
        <div class="logo-image">
          <img src="../../assets/image/logo2.png" />
        </div>
      </div>
    </el-aside>
    <el-container class="nav-head">
      <NavMenu :isCollapse="isCollapse"/>
      <el-container>
        <el-header :class="{ header: isCollapse }">
          <el-row>
            <el-col :span="2">
              <div class="btn-control" @click="ChangeCollapse">
                <el-icon v-show="!isCollapse"><Fold /></el-icon>
                <el-icon v-show="isCollapse"><Expand /></el-icon>
              </div>
            </el-col>
            <el-col :span="22" class="tool-box">
              <!--            多语言-->
              <el-dropdown trigger="click" class="language" @command="chooseLang">
                <div>
                  <img v-if="currentFlag" :src="currentFlag" alt="flag" class="flag-icon" />
                  <span class="el-dropdown-link">
                    <span>{{ langList[langName]?.name || langName }}</span>
                    <el-icon><ArrowDown /></el-icon>
                  </span>
                </div>

                <template #dropdown>
                  <el-dropdown-menu class="language-dropdown">
                    <el-dropdown-item
                      v-for="lang in languageOptions"
                      :key="lang.code"
                      :command="lang.code"
                      :class="{ 'is-active': lang.code === langName }"
                    >
                      <div class="language-option">
                        <span>{{ lang.name }}</span>
                      </div>
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
              <!--            暗黑模式-->
              <div class="opt-dark" @click="changeDark">
                <i v-show="!themeConfig.isDark" class="bi bi-sun-fill sun-color"></i>
                <i v-show="themeConfig.isDark" class="bi bi-moon-fill moon-color"></i>
              </div>
              <el-icon class="crm-cursor" style="font-size: 20px; margin-left: 20px">
                <Bell />
              </el-icon>
              <i class="crm-cursor iconquanping iconfont icon" @click="fullScreen"></i>
              <el-dropdown trigger="click" class="username crm-cursor">
                <span class="el-dropdown-link">
                  <span>{{ user?.name || 'UserName' }}</span
                  ><el-icon><ArrowDown /></el-icon>
                </span>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="updatePwd">
                      <span>
                        {{ $t('Label.UpdatePwd') }}
                      </span>
                    </el-dropdown-item>
                    <el-dropdown-item @click="beforeLogout"> Logout </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </el-col>
          </el-row>
        </el-header>
        <el-main>
          <div class="container">
            <router-view />
          </div>
        </el-main>
      </el-container>
    </el-container>

    <!-- 修改密码弹出 -->
    <el-dialog
      key="pwd"
      v-model="dialogCheck"
      :title="$t('Label.UpdatePwd')"
      center
      class="dialog_header_w"
    >
      <div class="dia-content">
        <el-form
          ref="dialogCheckFormRef"
          :model="dialogCheck_form"
          :rules="rules"
          label-width="135px"
          class="dialogCheck_form"
        >
          <el-form-item
            prop="oldPassword"
            size="large"
            class="mb30"
            :label="$t('Label.oldPwd') + '：'"
          >
            <el-input
              v-model.trim="dialogCheck_form.oldPassword"
              :placeholder="$t('Placeholder.Input')"
            ></el-input>
          </el-form-item>
          <el-form-item size="large" prop="newPassword" :label="$t('Label.newPwd') + '：'">
            <el-input
              v-model.trim="dialogCheck_form.newPassword"
              :placeholder="$t('Placeholder.Input')"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="toVerified()">
            {{ $t('Btn.Confirm') }}
          </el-button>
          <el-button @click="cancel">
            {{ $t('Btn.Cancel') }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </el-container>
</template>

<script lang="ts" setup>
  import {
    ref,
    reactive,
    computed,
    watch,
    onMounted,
    onUnmounted,
    nextTick,
    inject,
    onBeforeMount,
  } from 'vue'
  import { useRouter, useRoute } from 'vue-router'
  import { useStore } from 'vuex'
  import {
    FullScreen,
    Refresh,
    ArrowDown,
    RefreshRight,
    Bell,
    Fold,
    Expand,
  } from '@element-plus/icons-vue'
  import axios from 'axios'
  import { useI18n } from 'vue-i18n'

  // 组件导入
  import NavMenu from './components/nav.vue'
  import BreadCrumb from '@/components/BreadCrumb.vue'
  import TabMenu from '@/components/TabMenu.vue'
  import Service from '@/service/login'
  import Config from '@/config/index'
  import { safeGetUser, safeGetDisplay } from '@/utils/safeJson'
  import { filterByShowTrue } from '@/utils/utils'
  import { langList, languageOptions } from '@/utils/const/langues'
  import { useSettingStore } from '@/store/modules/setting'

  // 计算当前国旗图标
  const currentFlag = computed(() => {
    const lang = langList[langName.value]
    return lang ? lang.flag : '/src/assets/images/lang_EN.jpg'
  })

  const { Code } = Config
  const { t, locale } = useI18n()
  // 引入注入的全局
  const session = inject('session')
  const reload = inject('reload')
  const pigeon = inject('pigeon')

  // Vue 相关
  const router = useRouter()
  const route = useRoute()
  const store = useStore()

  // 响应式数据
  const info = ref({})
  const loading = ref(false)
  const dialogCheck = ref(false)

  const dialogCheck_form = reactive({
    oldPassword: '',
    newPassword: '',
  })
  const time = ref('')
  const langName = ref('')
  const isCollapse = ref(false)
  const screenWidth = ref(
    window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth
  )

  const type = ref('')
  const currentAttachId = ref(null)

  const dialogCheckFormRef = ref(null)
  const SettingStore = useSettingStore()

  // 设置信息
  const themeConfig = computed(() => SettingStore.themeConfig)
  // 计算属性
  const user = computed(() => safeGetUser(session))
  const expire = computed(() => store.state.home.expire)

  // 验证规则
  const rules = reactive({
    oldPassword: [
      {
        required: true,
        message: t('vaildate.input.empty'),
        trigger: 'blur',
      },
    ],
    newPassword: [
      {
        required: true,
        message: t('vaildate.input.empty'),
        trigger: 'blur',
      },
    ],
  })

  // 初始化权限
  const initDisplay = () => {
    let display = {}
    const userData = safeGetUser(session)
    if (userData && userData.display) {
      userData.display.forEach((item) => {
        item.children?.forEach((item1) => {
          item1.children = item1.btns ? Object.values(item1.btns) : []
          item1?.children.forEach((item2) => {
            display[item2.code] = item2
          })
        })
      })
    }
    session.Set('display', JSON.stringify(display), true)
  }

  const chooseLang = async (key) => {
    console.log(key, langName.value)
    console.log(2)
    if (key !== langName.value) {
      locale.value = key
      langName.value = key
      session.Set('lang', key)
      axios.defaults.headers.common['Language'] = sessionStorage.getItem('lang')
      setTimeout(() => {
        // 使用注入的reload方法或刷新页面
        if (reload) {
          reload()
        } else {
          // 如果没有注入reload方法，可以手动刷新或更新组件
          window.location.reload()
        }
      })
    }
  }

  // 退出登录
  const beforeLogout = () => {
    pigeon.MessageConfirm(
      t('Msg.Logout'),
      t('Msg.SystemPrompt'),
      t('Btn.Confirm'),
      t('Btn.Cancel'),
      function () {
        logout()
      },
      function () {}
    )
  }
  // 查看商户管理员信息
  const goShopInfo = () => {
    router.push({
      path: '/user/shopInfo',
    })
  }

  const logout = async () => {
    const res = await Service.Logout({})
    if (res.code == Code.StatusOK) {
      sessionStorage.clear()
      router.push({ path: '/signin' })
      store.commit('InfoExpire', false)
    } else {
      pigeon.MessageError(res.msg)
    }
  }

  // 全屏功能
  const fullScreen = () => {
    if (!isFullScreen()) {
      const docElm = document.documentElement
      if (docElm.requestFullscreen) {
        docElm.requestFullscreen()
      } else if (docElm.mozRequestFullScreen) {
        docElm.mozRequestFullScreen()
      } else if (docElm.webkitRequestFullScreen) {
        docElm.webkitRequestFullScreen()
      } else if (docElm.msRequestFullscreen) {
        docElm.msRequestFullscreen()
      }
    } else {
      if (document.exitFullscreen) {
        document.exitFullscreen()
      } else if (document.mozCancelFullScreen) {
        document.mozCancelFullScreen()
      } else if (document.webkitCancelFullScreen) {
        document.webkitCancelFullScreen()
      } else if (document.msExitFullscreen) {
        document.msExitFullscreen()
      }
    }
  }

  const isFullScreen = () => {
    return !!(
      document.fullscreen ||
      document.mozFullScreen ||
      document.webkitIsFullScreen ||
      document.webkitFullScreen ||
      document.msFullScreen
    )
  }

  // 刷新
  const toReload = () => {
    reload()
    getDate()
  }

  // 时间
  const getDate = () => {
    const timezone = 3
    const offset_GMT = new Date().getTimezoneOffset()
    const nowDate = new Date().getTime()
    const now = new Date(nowDate + offset_GMT * 60 * 1000 + timezone * 60 * 60 * 1000)

    let month = now.getMonth() + 1
    let day = now.getDate()
    let hh = now.getHours()
    let mm = now.getMinutes()

    if (month < 10) month = '0' + month
    if (day < 10) day = '0' + day
    if (hh < 10) hh = '0' + hh
    if (mm < 10) mm = '0' + mm

    time.value = `${month}/${day} ${hh}:${mm}`
  }

  // 侧边栏控制
  const ChangeCollapse = () => {
    isCollapse.value = !isCollapse.value
    store.commit('SetCollapse', isCollapse.value)
  }

  // 修改密码
  const updatePwd = () => {
    console.log('updatePwd')
    dialogCheck.value = true
  }

  const toVerified = async () => {
    if (!dialogCheckFormRef.value) return

    try {
      const valid = await dialogCheckFormRef.value.validate()
      if (valid) {
        loading.value = true
        const res = await Service.updatePwd({
          oldPassword: dialogCheck_form.oldPassword,
          newPassword: dialogCheck_form.newPassword,
        })
        if (res.code == Code.StatusOK) {
          pigeon.MessageOK(t('Msg.ModifySuccess'))
          cancel()
        } else {
          pigeon.MessageError(res.msg)
        }
      }
    } catch (error) {
      // 验证失败
    } finally {
      loading.value = false
    }
  }

  const cancel = () => {
    dialogCheck.value = false
    if (dialogCheckFormRef.value) {
      dialogCheckFormRef.value.resetFields()
    }
  }

  // 角色相关
  const getAttachList = async () => {
    try {
      // const res = await Service.getUserAttachs({})
      // if (res.code == Code.StatusOK) {
      //   attachList.value = res.data || []
      //   if (attachList.value.length > 0) {
      //     const userData = user.value
      //     if (userData && userData.id) {
      //       currentAttachId.value = userData.id
      //     } else if (!currentAttachId.value) {
      //       currentAttachId.value = attachList.value[0].id
      //     }
      //   }
      // } else {
      //   pigeon.MessageError(res.msg)
      // }
    } catch (error) {
      console.error('获取角色列表失败:', error)
    }
  }

  const switchRole = (item) => {
    if (item.id === currentAttachId.value) return

    pigeon.MessageConfirm(
      '是否切换身份？',
      '系统提示',
      '确认',
      '取消',
      async () => {
        await confirmSwitchRole(item.id)
      },
      () => {}
    )
  }

  const confirmSwitchRole = async (attachId) => {
    try {
      loading.value = true
      const res = await Service.switchLogin({ attachId })
      if (res.code == Code.StatusOK) {
        if (res.data) {
          sessionStorage.setItem('access_token', res.data)
          axios.defaults.headers.common['Access-Token'] = res.data
        }
        await nextTick()
        await getLoginInfo(attachId)
      } else {
        pigeon.MessageError(res.msg)
      }
    } catch (error) {
      console.error('切换角色失败:', error)
      pigeon.MessageError('切换角色失败')
    } finally {
      loading.value = false
    }
  }

  const getLoginInfo = async () => {
    const res = await Service.CustomLoginInfo({})
    if (res.code == Code.StatusOK) {
      const { display, ...rest } = res.data
      // 权限需要处理，show为false的不展示了
      const menus = display.map((item) => {
        return filterByShowTrue(item)
      })
      console.log(menus, 'asdaw')
      const info = { ...rest, display: menus.filter((item) => item) }
      store.commit('InitInfo', info)
      store.commit('InfoExpire', false)
      sessionStorage.setItem('info', JSON.stringify(info))
      // store.commit('InitInfo', res.data)
      // store.commit('InfoExpire', false)
      // sessionStorage.setItem('info', JSON.stringify(res.data))
      pigeon.MessageOK(t('Msg.LoginSuccess'))
      setTimeout(() => {
        loading.value = false
        // reload()
        router.push({ path: '/' }).catch((arr) => arr)
      }, 1000)
    } else {
      store.commit('InfoExpire', false)
      pigeon.MessageError(t('Msg.SystemError'))
      loading.value = false
    }
  }

  // 初始化语言
  const InitLanguage = () => {
    if (!session.Get('lang')) {
      session.Set('lang', 'cn')
      store.commit('ChangeLanguage', 'cn')
    }
    const lang = session.Get('lang') || 'cn'
    // 这里需要根据实际情况处理i18n
    locale.value = lang
    langName.value = lang
  }

  // 响应式布局
  const ListenResize = () => {
    setTimeout(() => {
      const width = screenWidth.value
      if (width <= 1080) {
        isCollapse.value = true
        store.commit('SetCollapse', isCollapse.value)
      } else {
        isCollapse.value = sessionStorage.getItem('isCollapse') === 'true'
      }
    }, 20)
  }

  const resize = () => {
    window.onresize = () => {
      const width =
        window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth
      screenWidth.value = width
    }
  }
  // 切换暗黑模式
  const changeDark = () => {
    const body = document.documentElement as HTMLElement
    console.log(themeConfig.value.isDark)
    themeConfig.value.isDark = !themeConfig.value.isDark
    if (themeConfig.value.isDark) {
      body.setAttribute('class', 'dark')
    } else {
      body.setAttribute('class', '')
    }
  }

  // 生命周期
  onBeforeMount(() => {
    try {
      const infoData = session.Get('info')
      info.value = infoData ? JSON.parse(infoData) : {}
    } catch (error) {
      console.error('Error parsing info data:', error)
      info.value = {}
    }
  })
  onBeforeMount(() => {
    // 初始化权限  需要在初始化之前处理，不然下面页面拿不到数据
    initDisplay()
  })
  onMounted(() => {
    // 初始化侧边栏状态
    isCollapse.value = session.Get('isCollapse', false) === 'true'
    InitLanguage()
    ListenResize()
    resize()
    getDate()
    getAttachList()
  })

  onUnmounted(() => {
    window.onresize = null
  })

  // 监听器
  watch(screenWidth, (val) => {
    screenWidth.value = val
    ListenResize()
  })

  watch(route, () => {
    getDate()
  })

  watch(expire, (val) => {
    if (val) {
      pigeon.MessageConfirm(
        t('Msg.LogoutTime'),
        t('Msg.SystemPrompt'),
        t('Btn.Confirm'),
        t('Btn.Cancel'),
        function () {
          logout()
        },
        function () {
          store.commit('InfoExpire', false)
        }
      )
    }
  })
</script>

<style scoped lang="scss">
  .home {
    width: 100%;
    height: 100%;
    .aside {
      height: 100%;
      overflow: hidden;
      overflow-y: auto;
      .logo-image {
        margin: 10px;
        width: 40px;
        img {
          width: 40px;
          height: 40px;
        }
      }
    }
    .nav-head {


    }
    .el-header {
      height: 60px;
      background-color: var(--bg-color);
      color: var(--text-color);
      line-height: 60px;
      padding: 0 60px;

      &.header {
        padding: 0 30px;
        transition: padding 0.2s ease;
      }

      .btn-control {
        float: left;

        i {
          font-size: 24px;

          &:hover {
            cursor: pointer;
          }
        }
      }
      .tool-box {
        display: flex;
        align-items: center;
        justify-content: flex-end;
        text-align: right;
        .username {
          margin: 0 20px;
        }
        .icon {
          font-size: 18px;
          margin-left: 20px;
        }
        .language {
          width: 120px;
          height: 30px;
          border-radius: 15px;
          background-color: #e6ebf3;
          display: flex;
          justify-content: center;
          align-items: center;
          .language-selector {
            display: flex;
            align-items: center;
            cursor: pointer;
          }
          .menu {
            cursor: pointer;
            color: #fff;
            display: flex;
            align-items: center;

            .el-icon {
              margin-left: 4px;
            }
          }
        }
        .opt-dark {
          margin-left: 20px;
          cursor: pointer;
          .sun-color {
            color: #feaf37;
          }
          .moon-color {
            color: yellow;
          }
        }
      }
    }

    .el-aside {
      background-color: rgba(43, 48, 67, 1);
      color: #ffffff;
      overflow: hidden;
      overflow-y: auto;
    }

    .el-main {
      padding: 15px;
      overflow: hidden;
      background-color: var(--el-bg-color);

      .tool {
        margin-bottom: 15px;
        text-align: right;
        font-size: 14px;
        i.el-icon-refresh-right {
          margin-left: 10px;
          font-weight: bold;
        }
      }

      .container {
        height: calc(100% - 75px);
        overflow: hidden;
        position: relative;
      }
    }

    body > .el-container {
      margin-bottom: 40px;
    }
    .flag-icon {
      width: 15px;
      height: 10px;
      margin: 0 4px;
      object-fit: cover;
    }
  }
  .dark {
    .home .el-header .tool-box .language {
      background-color: #102047;
    }
  }
</style>
<style lang="scss">
  .dialog_header_qa.dialog_header_w.el-dialog {
    min-height: 80%;
  }
</style>
