<script setup lang="ts">
import {ref, watch, onMounted, defineAsyncComponent} from 'vue'

import {BasicApi} from '@/api/basic'
import {RequestError} from '@/utils/request'
import {isMobile} from "@/utils/useDeviceDetection.ts";
import {useGlobalStore} from '@/stores/global'
import {ElMessage} from 'element-plus'

const SsHeader = defineAsyncComponent(() => import('@/components/SsHeader.vue'))
const SsFooter = defineAsyncComponent(() => import('@/components/SsFooter.vue'))
const SsNavigation = defineAsyncComponent(() => import('@/components/SsNavigation.vue'))
const SsHeadline = defineAsyncComponent(() => import('@/components/SsHeadline.vue'))
const SsInputBox = defineAsyncComponent(() => import('@/components/SsInputBox.vue'))
const SsPanel = defineAsyncComponent(() => import('@/components/SsPanel.vue'))
const SsCommonProblem = defineAsyncComponent(() => import('@/components/SsCommonProblem.vue'))
const SsService = defineAsyncComponent(() => import('@/components/SsService.vue'))
const SsGridEntrance = defineAsyncComponent(() => import('@/components/SsGridEntrance.vue'))
const SsHotline = defineAsyncComponent(() => import('@/components/SsHotline.vue'))
const SsOpinion = defineAsyncComponent(() => import('@/components/SsOpinion.vue'))

const componentsLoaded = ref(0)
const totalComponents = ref(8)

const componentLoaded = () => {
  componentsLoaded.value++
  if (componentsLoaded.value >= totalComponents.value) {
    let warp = (document.querySelector('.first-loading-wrp') as HTMLElement | null)
    if (warp) {
        warp.style.display = 'none'
    }
  }
}

const global = useGlobalStore()

const problemIsRefresh = ref(false)
const mainBoxFlag = ref(true)
const timeoutFlag = ref()
const mainContentClass = ref({})

const inputBox = ref<InstanceType<typeof SsInputBox> | null>(null)
const commonProblem = ref<InstanceType<typeof SsCommonProblem> | null>(null)
const hotlineRef = ref<InstanceType<typeof SsHotline> | null>(null)
const opinionRef = ref<InstanceType<typeof SsOpinion> | null>(null)

const loadBasicData = async () => {
  try {
    const result = await BasicApi.getWebSet()
    global.setBasic(result)
  } catch (error) {
    const err = error as RequestError
    ElMessage.warning(err.message || '请求错误')
  }
}

const refreshProblem = () => {
  problemIsRefresh.value = true
  if (commonProblem.value) {
    commonProblem.value.refresh()
  }
}

const problemLoadFinish = () => {
  problemIsRefresh.value = false
}

const editMessage = (message: string) => {
  if (inputBox.value) {
    inputBox.value.editMessage(message)
  }
}

const setMainContentClass = () => {
  mainContentClass.value = {
    'input-line-1': global.spread && global.inputLine == 1,
    'input-line-2': global.spread && global.inputLine == 2,
    'input-line-3': global.spread && global.inputLine >= 3
  }
}

const quickSend = (msg: string) => {
  if (inputBox.value) {
    inputBox.value.quickSend(msg)
  }
}

const loadService = (categoryId: number, title: string, avatar: string) => {
  if (isMobile()) {
    global.setMenuSwitch(false)
  }
  if (inputBox.value) {
    inputBox.value.loadService(categoryId, title, avatar)
  }
}

const loadCommonProblem = () => {
  if (isMobile()) {
    global.setMenuSwitch(false)
  }
  if (inputBox.value) {
    inputBox.value.loadCommonProblem()
  }
}

const openHotlineDialog = () => {
  hotlineRef.value?.open()
}

const openOpinionDialog = () => {
  opinionRef.value?.open()
}

const openPolicyFile = () => {
  if (global.basic.policyFileUrl) {
    const newWindow = window.open(global.basic.policyFileUrl)
    if (newWindow) newWindow.opener = null
  }
}

const initPage = () => {
  let w = window.screen.width
  if (w <= 750) {
    global.setMenuSwitch(false)
  }
  setMainContentClass()
}

onMounted(() => {
  loadBasicData()
  initPage()
  window.addEventListener('resize', initPage)
})

watch(() => global.spread, (newValue, oldValue) => {
  setMainContentClass()
  if (timeoutFlag.value) {
    clearTimeout(timeoutFlag.value)
  }
  if (newValue) {
    timeoutFlag.value = setTimeout(() => {
      mainBoxFlag.value = false
    }, 50)
  } else {
    timeoutFlag.value = setTimeout(() => {
      mainBoxFlag.value = true
    }, 300)
  }
})
watch(() => global.inputLine, () => {
  setMainContentClass()
})

</script>

<template>
  <div class="root">
    <ss-header @loaded="componentLoaded"/>
    <ss-navigation
        @open-hotline="openHotlineDialog"
        @open-opinion="openOpinionDialog"
        @quick-send="quickSend"
        @load-service="loadService"
        @load-common-problem="loadCommonProblem"
        @loaded="componentLoaded"
    />
    <div class="container" :class="{spread:  global.spread, 'menu-close': !global.menuSwitch}">
      <div class="main">
        <div class="main-content" :class="mainContentClass">
          <ss-headline v-if="mainBoxFlag"/>
          <ss-input-box ref="inputBox" @loaded="componentLoaded"/>
          <div v-if="mainBoxFlag" class="main-box">
            <div class="ss-row ss-row-vertical">
              <div class="ss-col ss-col-service is-mobile">
                <ss-panel title="服务导航" :show-refresh="false">
                  <ss-service @load-service="loadService" @loaded="componentLoaded"/>
                </ss-panel>
              </div>
              <div class="ss-col ss-col-service is-pc">
                <ss-panel title="服务导航" :show-refresh="false">
                  <ss-service @load-service="loadService" @loaded="componentLoaded"/>
                </ss-panel>
              </div>
              <div class="ss-col ss-col-problem">
                <ss-panel title="常见问题" :show-refresh="true" :is-refresh="problemIsRefresh" @refresh="refreshProblem">
                  <ss-common-problem ref="commonProblem" @quick-send="quickSend" @finish="problemLoadFinish" @loaded="componentLoaded"/>
                </ss-panel>
              </div>
            </div>
            <div class="ss-row ss-flex no-margin-bottom">
              <div class="ss-col">
                <ss-grid-entrance title="意见反馈" subject="诚谢建言，共筑精品" image="/images/bg07.png" @click="openOpinionDialog" @loaded="componentLoaded"/>
              </div>
              <div class="ss-col">
                <ss-grid-entrance title="政策文件" subject="便捷获取最新政策信息" image="/images/bg08.png" sub-class="yellow" @click="openPolicyFile" @loaded="componentLoaded"/>
              </div>
            </div>
          </div>
        </div>
        <ss-footer @loaded="componentLoaded"/>
      </div>
    </div>
    <ss-hotline ref="hotlineRef"/>
    <ss-opinion ref="opinionRef"/>
  </div>
</template>
<style lang="scss">
.root {
  position: fixed;
  z-index: 1;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;

  .container {
    display: flex;
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 1;
    background: #ffffff url("/images/backgroup.png") no-repeat scroll center center;
    background-size: cover;

    .main {
      width: 100%;
      overflow: hidden auto;
      position: relative;

      .main-content {
        height: 100vh;
        padding: 4rem 0 2rem 0;
        overflow: hidden auto;
        position: relative;

        .main-box {
          max-width: calc(1200px + 2rem);
          margin: 0 auto 1.69rem auto;
          padding: 0 1rem;
          transition: all .3s linear;

          .ss-row {
            display: flex;
            justify-content: space-between;
            margin-bottom: 1.68rem;

            &.no-margin-bottom {
              margin-bottom: 0;
            }

            .ss-col {
              width: calc(50% - 0.9rem);
            }
          }
        }

        &.input-line-1 {
          padding-bottom: 9rem;
        }

        &.input-line-2 {
          padding-bottom: 10.5rem;
        }

        &.input-line-3 {
          padding-bottom: 12rem;
        }
      }
    }

    &.spread {
      padding-left: 18rem;
      background-image: none;

      .navigation {
        display: block;
      }

      .main {
        .main-content {
          padding-top: 3rem;
          padding-right: 0;
          padding-left: 0;
        }
      }

      &.menu-close {
        padding-left: 4.5rem;
      }
    }
  }
}

/* 1080x1920 中等尺寸设备优化 */
@media screen and (min-width: 751px) and (max-width: 1200px) and (min-height: 1700px) {
  .root {
    .container {
      .main {
        .main-content {
          padding: 5rem 0 5rem 0; /* 增加底部 padding 为 Footer 留空间 */

          .main-box {
            max-width: calc(1100px + 2rem);
            margin: 0 auto 2rem auto;
            padding: 0 1.5rem;

            .ss-row {
              margin-bottom: 2rem;

              /* 垂直布局：服务导航在上，常见问题在下 */
              &.ss-row-vertical {
                display: block;

                .ss-col-service {
                  width: 100%;
                  margin-bottom: 1.5rem;
                }

                .ss-col-problem {
                  width: 100%;
                }
              }

              .ss-col {
                width: calc(50% - 1rem);
              }
            }
          }

          &.input-line-1 {
            padding-bottom: 10rem;
          }

          &.input-line-2 {
            padding-bottom: 11.5rem;
          }

          &.input-line-3 {
            padding-bottom: 13rem;
          }
        }
      }
    }
  }
}

@media screen and (max-width: 750px) {
  .root {
    .container {
      .main {
        .main-content {
          padding-bottom: 0;

          .main-box {
            .ss-row {
              display: block;

              .ss-col {
                width: 100%;
                margin-bottom: 1rem;
              }

              &.ss-flex {
                display: flex;

                .ss-col {
                  width: calc(50% - 0.47rem);
                  margin-bottom: 0;
                }
              }
            }
          }

          &.input-line-1 {
            padding-bottom: 7rem;
          }

          &.input-line-2 {
            padding-bottom: 8.5rem;
          }

          &.input-line-3 {
            padding-bottom: 10rem;
          }
        }
      }

      &.spread {
        padding: 0;

        .main {
          .main-content {
            padding-top: 4rem;
          }
        }

        &.menu-close {
          padding-left: 0;
        }
      }
    }
  }
}
</style>