<template>
  <q-layout view="lHh lpr lFf" style="background: #f5f8fa">
    <q-header reveal class="bg-white text-white q-px-md q-py-sm">
      <q-toolbar>
        <q-toolbar-title class="row items-center">
          <div class="col row items-center">
            <q-btn dense flat round @click="toggleLeftDrawer" class="mobile-only">
              <svg-icon icon="Text/Menu.svg" :size="32"></svg-icon>
            </q-btn>
            <div class="mobile-only q-ml-md text-dark text-h6 text-weight-bold">PIC</div>
            <div class="mls text-h6 text-dark desktop-only">{{ childPageTitle }}</div>
          </div>
          <div class="bg-grey-2 rounded-borders q-px-md f12 text-grey-800 q-mr-md desktop-only">
            {{ version }}
          </div>
          <div class="rounded-borders header-item q-mr-lg">
            <svg-icon color="grey" icon="design/component.svg" :size="25" :tips="$t('syslog')"></svg-icon>
          </div>
          <div class="rounded-borders header-item q-mr-lg" style="position: right">
            <div v-if="isDadge" class="header-badge bg-green-4"></div>
            <svg-icon color="grey" icon="Communication/Chat6.svg" :size="25" :tips="$t('sysmsg')"> </svg-icon>
            <q-popup-proxy :offset="[0, 15]" class="no-shadow">
              <Notifications :user="userInfo"></Notifications>
            </q-popup-proxy>
          </div>
          <q-avatar size="40px" rounded class="bg-blue-2 cursor-pointer">
            <q-img :src="userInfo.photo" v-if="userInfo?.photo" mode="cover" />
            <span class="text-primary text-h6" v-else>{{ userInfo.name?.substring(0, 1) }}</span>
            <q-popup-proxy :offset="[0, 15]" class="no-shadow">
              <user-info :user="userInfo"></user-info>
            </q-popup-proxy>
          </q-avatar>
        </q-toolbar-title>
      </q-toolbar>
    </q-header>

    <q-drawer show-if-above v-model="leftDrawerOpen" style="background: #1e1e2d; width: 265px" side="left"
      class="column">
      <div class="column items-center q-mt-sm" style="color: #fff;zoom: .5;">
        <img src="../assets/img/newLogo.jpg" style="height: 80px; filter: brightness(0) invert(1);">
        <!-- <div style="width: 50px; overflow: hidden">
          <img v-if="isDomainName_PIC" src="../assets/images/jvs-log.png" style="height: 40px" />
          <img v-else src="http://imgfile.oytour.com/Upload/WebSite/202303170746500900000000054.png" style="height: 40px" />
        </div>
        <div class="text-h6 text-weight-bold" style="font-family: math">PEACE INTERNATIONAL</div>
        <div class="text-body2 text-weight-thin text-italic" style="font-family: math">by MILLENNIUM</div> -->
      </div>
      <q-scroll-area :thumb-style="scrollStyle.thumbStyle" :bar-style="scrollStyle.barStyle"
        class="col nav-list q-pl-lg">
        <navs></navs>
      </q-scroll-area>
    </q-drawer>

    <q-page-container class="window-height" id="scrollId">
      <q-scroll-area ref="scrollAreaRef" :thumb-style="scrollStyle.thumbStyle" :bar-style="scrollStyle.barStyle"
        class="full-height">
        <router-view />
      </q-scroll-area>
    </q-page-container>

    <!-- <q-footer class="bg-white text-dark">
      <q-toolbar>
        <q-toolbar-title>
          <div class="text-body2">2022© PIC</div>
        </q-toolbar-title>
      </q-toolbar>
    </q-footer> -->
  </q-layout>
  <q-dialog class="no-padding" v-model="noticeDialogVisible" persistent>
    <q-card flat class="q-pa-md column" style="width:60vw;min-width: 375px; height: 80vh;">
      <div class="text-h6 text-weight-bold full-width text-center">
        {{ noticeDialogData.title }}
      </div>
      <div class="text-center" style="font-size: 12px; font-weight: 400;">
        <span class="text-grey-500">{{ $t('notice.column.releaseDate') }} {{ noticeDialogData.notice_date }}</span>
      </div>
      <div style="overflow-y: auto;" class="text-body2 q-mt-md full-width col q-pa-md" v-html="noticeDialogData.content"></div>
      <div class="q-mt-md row items-center" v-if="noticeDialogData.fileList.length > 0">
        <span class="text-grey-500">{{ $t('notice.detail.file') }}：</span>
        <q-btn v-for="(x,i) in noticeDialogData.fileList" class="q-mr-md" dense :key="i" color="primary" flat unelevated :label="x.name" @click="downloadFile(x)" />
      </div>
      <div class="q-mt-md text-right">
        <q-btn color="primary" flat unelevated @click="closeNoticeDialog" :label="$t('close')" />
      </div>
    </q-card>
  </q-dialog>
</template>

<script lang="ts">
import { inject, provide, reactive, ref, toRefs, onMounted, watch } from 'vue'
import { getStoreGetter } from '../store/utils'
import { UserGetter } from '../store/modules/user/getters'
import svgIcon from '../components/global/svg-icon.vue'
import useScrollModule from '../module/scrollbar/scrollModule'
import Navs from '../components/layout/navs.vue'
import userInfo from '../components/layout/userInfo.vue'
import Notifications from '../components/layout/Notifications.vue'
import { DirtionmaryHelper } from '../config/dictionary'
import { AppConfig } from 'src/config/app'
import scheduledTripService from 'src/api/scheduledTrip'
import Store from '../store'
import { ApiResult } from 'src/@types/enumHelper'
import message from 'src/utils/message'
import { useI18n } from 'vue-i18n'
import NoticeService from 'src/api/notice'
export default {
  components: { svgIcon, Navs, userInfo, Notifications },
  setup() {
    const leftDrawerOpen = ref(false)
    const noticeDialogVisible = ref(false)
    const noticeDialogData = ref<any>(null)
    const fileList = ref<any[]>([])
    const data = reactive({
      userInfo: {} as any,
      leftDrawerOpen: false,
      scrollStyle: {} as any,
      timer: 0,
      isDadge: true,
      version: '',
      isDomainName_PIC: true
    })
    const { t } = useI18n()
    const downloadFile = async (file: any) => {
      const url = 'http://imgfile.oytour.com/'+file.url
        try {
          const response = await fetch(url)
          const blob = await response.blob()
          const filename = url.split('/').pop() || 'download'
          const link = document.createElement('a')
          link.href = window.URL.createObjectURL(blob)
          link.download = filename
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
          window.URL.revokeObjectURL(link.href)
        } catch (error) {
          //message.errorMsg(t('downloadFailed'))
        }
      }

    // 根据域名渲染logo
    data.isDomainName_PIC = inject(DirtionmaryHelper.DOMAIN_NAME)

    const childPageTitle = ref('')
    provide(DirtionmaryHelper.NOTICE_DIALOG_DATA, noticeDialogData)
    provide(DirtionmaryHelper.PAGE_TITLE_KEY, childPageTitle)
    const activeMenu = ref(0)
    provide(DirtionmaryHelper.MENU_KEYS, activeMenu)
    data.userInfo = getStoreGetter<UserGetter>('user', 'getUser')
    data.scrollStyle = useScrollModule().scrollStyle

    const scrollAreaRef = ref()
    const scrollArea = reactive({
      pagesTop: 0
    })
    // 储存滚动位置
    provide(DirtionmaryHelper.SCROLL_AREA_OBJ, scrollArea)
    watch(
      () => scrollArea.pagesTop,
      (n, o) => {
        scrollAreaRef.value.setScrollPosition('vertical', n, 100)
      }
    )
    watch(
      () => noticeDialogData.value,
      (n, o) => {
        console.log(n)
        noticeDialogVisible.value = (noticeDialogData.value && noticeDialogData.value?.id > 0)
      },
      { immediate: true, deep: true }
    )

    const methods = {
      toggleLeftDrawer() {
        data.leftDrawerOpen = !data.leftDrawerOpen
      },
      //获取网站配置数据
      getConfigData() {
        scheduledTripService
          .GetWebSiteConfig({
            RB_Group_Id: Store.state.user?.userDetail?.groupId,
            B2BDomain: Store.state.user?.userDetail?.name
          })
          .then(r => {
            if (r.data.resultCode == ApiResult.SUCCESS) {
              if (r.data.data) {
                var jsonData = JSON.stringify(r.data.data)
                localStorage.setItem('baseifo', jsonData)
              }
            } else {
              message.errorMsg(r.data.message)
            }
          })
          .catch(e => {
            message.errorMsg(e.message)
          })
      }
    }
    const closeNoticeDialog = () => {
      noticeDialogVisible.value = false
      noticeDialogData.value = null
      //localStorage.removeItem('lastNotice')
    }
    const getNoticeList = async () => {
      try {
        const res = await NoticeService.getNoticeNewDetail({})
        if(res.data.resultCode == ApiResult.SUCCESS){
          const lastNotice = localStorage.getItem('lastNotice')
          if(lastNotice!=res.data.data.id){
            noticeDialogData.value = res.data.data
            localStorage.setItem('lastNotice',res.data.data.id)
          }
        }
      } catch (error) {
        console.log(error)
      }
    }
    onMounted(() => {
      if (!localStorage.getItem('baseifo')) {
        methods.getConfigData()
      }
      getNoticeList()
      setInterval(() => {
        data.isDadge = false
        setTimeout(() => {
          data.isDadge = true
        }, 200)
      }, 1000)
    })
    data.version = AppConfig.$version ?? ''
    return {
      ...toRefs(data),
      ...methods,
      childPageTitle,
      scrollAreaRef,
      scrollArea,
      noticeDialogVisible,
      noticeDialogData,
      downloadFile,
      closeNoticeDialog,
      fileList
    }
  }
}
</script>
<style>
.header-item {
  cursor: pointer;
  display: flex;
  height: 40px;
  width: 40px;
  align-items: center;
  justify-content: center;
}

.header-item svg g [fill] {
  fill: rgb(161, 165, 183) !important;
  cursor: pointer;
  padding: 4px;
}

.header-item:hover {
  background: rgba(0, 0, 0, 0.05);
}

.header-item:hover svg g [fill] {
  fill: var(--q-primary) !important;
}

.header-badge {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  position: absolute;
  margin-top: -40px;
}
</style>
