<template>
  <el-container id="home" v-loading="loading">
    <el-aside width="auto">
      <nav-menu></nav-menu>
    </el-aside>
    <el-container>
      <el-header>
        <el-row :gutter="10">
          <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-button-->
            <!--              v-if="isQAlist"-->
            <!--              plain-->
            <!--              round-->
            <!--              size="small"-->
            <!--              type="primary"-->
            <!--              icon="el-icon-chat-line-round"-->
            <!--              style="margin-right: 20px"-->
            <!--              @click="openQA"-->
            <!--            >-->
            <!--              {{ 'Q&A' }}-->
            <!--            </el-button>-->
            <el-dropdown trigger="click" class="language">
              <span class="el-dropdown-link">
                <span>{{ langName }}</span
                ><el-icon><ArrowDown /></el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="SwitchLanguage('cn')">中文简体</el-dropdown-item>
                  <el-dropdown-item @click="SwitchLanguage('en')">English</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            <el-dropdown v-if="info.roteCode == 'ROLE_SALE'" trigger="click" class="role-switch">
              <span class="el-dropdown-link">
                <span>{{ currentRoleName }}</span
                ><el-icon><ArrowDown /></el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item
                    v-for="item in attachList"
                    :key="item.id"
                    :class="{ 'is-active': item.id === currentAttachId }"
                    @click="switchRole(item)"
                  >
                    {{ item.name }}
                    <i v-if="item.id === currentAttachId" class="el-icon-check"></i>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            <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>
        <el-row class="tool">
          <el-col :span="16">
            <bread-crumb></bread-crumb>
          </el-col>
          <el-col :span="8">
            <span>
              {{ $t('Home1.Time') }}
            </span>
            <span class="crm-cursor" @click="toReload">{{ time }}</span>
            <el-icon class="crm-cursor el-icon-refresh-right" @click="toReload">
              <RefreshRight />
            </el-icon>
          </el-col>
        </el-row>
        <tab-menu></tab-menu>
        <div class="container">
          <router-view />
        </div>
      </el-main>
    </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 { ElMessage, ElMessageBox } from 'element-plus'
  import { FullScreen, Refresh, ArrowDown, RefreshRight } from '@element-plus/icons-vue'
  import axios from 'axios'
  import { useI18n } from 'vue-i18n'

  // 组件导入
  import NavMenu from '@/components/NavMenu.vue'
  import BreadCrumb from '@/components/BreadCrumb.vue'
  import TabMenu from '@/components/TabMenu.vue'
  // import QaList from './global/QAList'
  // import QaAdd from './global/QAAdd'
  import Service from '@/service/login'
  import Config from '@/config/index'
  import { safeGetUser, safeGetDisplay } from '@/utils/safeJson'

  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 dialogCheckQA = ref(false)
  const qaType = ref(1)
  const myId = ref('')
  const type = ref('')
  const isQAlist = ref(false)
  const attachList = ref([])
  const currentAttachId = ref(null)

  const dialogCheckFormRef = ref(null)

  // 语言映射
  const langs = {
    cn: '中文简体',
    en: 'English',
  }

  // 计算属性
  const user = computed(() => safeGetUser(session))
  const expire = computed(() => store.state.home.expire)
  const currentRoleName = computed(() => {
    if (attachList.value.length === 0) return ''
    const currentRole = attachList.value.find((item) => item.id === currentAttachId.value)
    return currentRole ? currentRole.name : ''
  })

  // 验证规则
  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 = Object.values(item1.btns)
          item1.children.forEach((item2) => {
            display[item2.code] = item2
          })
        })
      })
    }
    session.Set('display', JSON.stringify(display), true)
  }

  // QA相关方法
  const openQA = () => {
    dialogCheckQA.value = true
    qaType.value = 1
  }

  const toNew = (val) => {
    const link = window.location.href
    if (link.indexOf('system/qa/add') > -1) {
      router.push({ path: '/system/qa/list' }).catch((arr) => arr)
    }
    dialogCheckQA.value = true
    myId.value = -1
    type.value = 'add'
    qaType.value = val
  }

  const cancelQa = () => {
    qaType.value = 1
  }

  const toUpdate = (id) => {
    const link = window.location.href
    if (link.indexOf('system/qa/add') > -1) {
      router.push({ path: '/system/qa/list' }).catch((arr) => arr)
    }
    dialogCheckQA.value = true
    myId.value = id
    type.value = 'update'
    qaType.value = 2
  }

  const toCheck = (id) => {
    dialogCheckQA.value = true
    myId.value = id
    type.value = 'check'
    qaType.value = 2
  }

  const isQAlistGet = () => {
    const display = safeGetDisplay(session)
    if (display && display['R-System-QAList-Search'] && display['R-System-QAList-Search'].show) {
      isQAlist.value = true
    } else {
      isQAlist.value = false
    }
  }

  // 退出登录
  const beforeLogout = () => {
    pigeon.MessageConfirm(
      t('Msg.Logout'),
      t('Msg.SystemPrompt'),
      t('Btn.Confirm'),
      t('Btn.Cancel'),
      function () {
        logout()
      },
      function () {}
    )
  }

  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 SwitchLanguage = (lang) => {
    if (lang !== session.Get('lang')) {
      switchLang(lang)
    }
  }

  const switchLang = async (lang) => {
    // 这里需要根据实际情况处理i18n
    locale.value = lang
    // 如果是使用 vue-i18n@next，可能需要通过 useI18n() 来处理
    langName.value = langs[lang]
    session.Set('lang', lang)
    store.commit('ChangeLanguage', lang)
    axios.defaults.headers.common['Language'] = lang
    setTimeout(() => {
      // reload()
    }, 800)
  }

  // 修改密码
  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) {
      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 = langs[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
    }
  }

  // 生命周期
  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()
    isQAlistGet()
    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%;

    .el-header {
      height: 60px;
      background-color: #ffffff;
      color: #333;
      line-height: 60px;

      .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 {
          .el-dropdown-link {
            background-color: rgba(247, 247, 250, 1);
            border: none;
            border-radius: 30px;
            padding: 6px 20px;
            cursor: pointer;
          }
        }
        .role-switch {
          margin-left: 20px;
          .el-dropdown-link {
            background-color: rgba(247, 247, 250, 1);
            border: none;
            border-radius: 30px;
            padding: 6px 20px;
            cursor: pointer;
          }
        }
      }
    }

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

    .el-main {
      padding: 15px;
      overflow: hidden;
      background-color: #f5f5f5;

      .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;
    }
  }
</style>
<style lang="scss">
  .dialog_header_qa.dialog_header_w.el-dialog {
    min-height: 80%;
  }

  // 角色切换下拉框样式
  .el-dropdown-menu .el-dropdown-item.is-active {
    color: #409eff;
    background-color: #f5f7fa;

    .el-icon-check {
      float: right;
      color: #409eff;
    }
  }
</style>
