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

import {BasicApi} from '@/api/basic'
import {RequestError} from '@/utils/request'
import {isMobile, isKioskDevice} 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({})

/**
 * 立式一体机模式下的常见问题列表
 * 从 global.commonProblem 派生，取前 4 条用于底部展示
 */
const kioskFaqList = computed(() => {
  return global.commonProblem.slice(0, 4)
})

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 goHome = () => {
  global.setSpread(false)
  global.setMenuSwitch(false)
  global.setInReply(false)
}

/**
 * 获取服务项样式类（复用 SsService 组件逻辑）
 */
const getServiceClass = (index: number) => {
  switch (index % 5) {
    case 0:
      return 'hover-scale'
    case 1:
      return 'hover-scale yellow'
    case 2:
      return 'center'
    case 3:
      return 'hover-scale yellow'
    case 4:
      return 'hover-scale'
    default:
      return ''
  }
}

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">
    <!-- 1080x1920 立式一体机对话模式：顶部导航栏替代 Header -->
    <div v-if="global.spread && isKioskDevice()" class="kiosk-top-nav">
      <div class="back-home-btn" @click="goHome">
        <span class="back-icon">←</span>
        <span>返回首页</span>
      </div>
      <h1 class="app-title">商小川<span>智能助手</span></h1>
      <div class="nav-spacer"></div>
    </div>
    
    <!-- 立式一体机对话模式：服务快捷入口栏（复用原有设计） -->
    <div v-if="global.spread && isKioskDevice()" class="kiosk-service-bar">
      <div class="service-bar-container">
        <div 
          v-for="(item, index) in global.categories" 
          :key="item.id"
          class="service-quick-item"
          :class="getServiceClass(index)"
          @click="loadService(item.id, item.categoryName, item.imgUrl)"
        >
          <div class="service-item-content">
            <div class="service-title">{{ item.categoryName }}</div>
          </div>
          <el-image class="service-item-image" fit="contain" :src="getImageUrl(item.imgUrl)"/>
        </div>
      </div>
    </div>
    
    <!-- 默认 Header（非立式一体机模式） -->
    <ss-header v-else @loaded="componentLoaded"/>
    
    <!-- 侧边栏导航：立式一体机对话模式下隐藏 -->
    <ss-navigation
        v-if="!(global.spread && isKioskDevice())"
        @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, 'kiosk-mode': isKioskDevice() && global.spread}">
      <div class="main">
        <div class="main-content" :class="mainContentClass">
          <ss-headline v-if="mainBoxFlag"/>
          <ss-input-box ref="inputBox" @loaded="componentLoaded"/>
          
          <!-- 立式一体机对话模式：底部常见问题展示区 -->
          <div v-if="global.spread && isKioskDevice()" class="kiosk-bottom-faq">
            <div class="faq-card">
              <div class="faq-title">热门问题</div>
              <div class="faq-list">
                <div 
                  v-for="(item, index) in kioskFaqList" 
                  :key="index" 
                  class="faq-item"
                  @click="quickSend(item.questionContent)"
                >
                  {{ item.questionContent }}
                </div>
              </div>
            </div>
          </div>
          
          <!-- 默认布局：服务导航 + 常见问题 -->
          <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>
        <!-- 立式一体机对话模式下隐藏 Footer，避免与底部 FAQ 区域重叠 -->
        <ss-footer v-if="!(global.spread && isKioskDevice())" @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 {
    /* 定义统一的内容区域宽度：屏幕宽度减去左右 padding */
    --kiosk-content-padding: 2rem;
    --kiosk-content-width: calc(100vw - var(--kiosk-content-padding) * 2);

    .container {
      .main {
        .main-content {
          padding: 5rem 0 5rem 0;

          .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;
          }
        }
      }

      /* 立式一体机对话模式：三段式布局 */
      &.kiosk-mode {
        padding-left: 0 !important;

        .main {
          .main-content {
            display: flex;
            flex-direction: column;
            height: 100vh;
            padding: 200px 0 0 0; /* 顶部留出导航栏(100px) + 服务栏(100px)空间 */

            /* 对话区域：占据主要空间 */
            .chat-container {
              flex: 1;
              display: flex;
              flex-direction: column;
              min-height: 0; /* 允许 flex 子元素收缩 */

              /* 聊天消息区域：保持原有宽度（768px），无需覆盖 */
              /* 输入框：保持原有宽度（768px），无需覆盖 */
            }

            /* 底部常见问题展示区：固定 420px，与输入框宽度对齐 */
            .kiosk-bottom-faq {
              flex-shrink: 0;
              height: 420px;
              background: transparent;
              padding: 0;
              margin-top: -2rem;
              overflow: hidden;
              display: flex;
              flex-direction: column;
              align-items: center;

              .faq-card {
                width: var(--kiosk-content-width); /* 与顶部导航栏内容区域对齐 */
                max-width: 100%;
                padding: 2rem;
                background: #ffffff; /* 白色卡片背景 */

                .faq-title {
                  font-size: 1.75rem;
                  font-weight: 600;
                  color: #101333;
                  margin-bottom: 1.5rem;
                  text-align: left; /* 左对齐 */
                }

                .faq-list {
                  display: flex;
                  flex-direction: column;
                  gap: 1rem;

                  .faq-item {
                    font-size: 1.25rem;
                    color: #545764;
                    line-height: 1.6;
                    padding: 0.75rem 1rem;
                    background: #ffffff;
                    border-radius: 0.75rem;
                    border: 1px solid #D5D6D8;
                    cursor: pointer;
                    transition: all 0.2s ease;

                    &:hover {
                      background: #F6F7FB;
                      border-color: #2943D6;
                      transform: translateX(0.25rem);
                    }

                    &:active {
                      background: #EAEDFB;
                      transform: translateX(0.125rem);
                    }
                  }
                }
              }
            }
          }
        }
      }
    }

    /* 立式一体机顶部导航栏：固定 100px */
    .kiosk-top-nav {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      height: 100px;
      background: #ffffff;
      border-bottom: 1px solid #E5E7EB;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0 2rem;
      z-index: 1000;

      .back-home-btn {
        display: flex;
        align-items: center;
        gap: 0.5rem;
        padding: 0.75rem 1.5rem;
        border-radius: 2.5rem; /* 胶囊形状 */
        border: 1px solid #e5e5e5;
        background: #ffffff;
        color: #333333;
        font-size: 1rem;
        font-weight: 400;
        cursor: pointer;
        transition: all 0.2s ease;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);

        &:hover {
          background: #f7f7f7;
          border-color: #d5d5d5;
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
        }

        &:active {
          background: #eeeeee;
          border-color: #cccccc;
          box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
          transform: scale(0.98);
        }

        .back-icon {
          font-size: 1.125rem;
          font-weight: 500;
        }
      }

      .app-title {
        font-size: 3rem;
        font-weight: 700;
        color: #555964;
        letter-spacing: 0.125rem;
        margin: 0;
        /* 核心：文字双重阴影营造新拟态效果 */
        text-shadow: 
          4px 4px 8px #d1d9e6,    /* 右下深色阴影 */
          -4px -4px 8px #ffffff;  /* 左上高光 */
        
        /* 让"智能助手"四个字稍微淡一点，突出"商小川" */
        span {
          font-weight: 300;
          color: #8990a0;
          font-size: 0.8em; /* 稍微小一点 */
        }
      }

      .nav-spacer {
        width: 120px; /* 占位，保持标题居中 */
      }
    }

    /* 立式一体机服务快捷入口栏：紧贴顶部导航栏下方，复用原有设计 */
    .kiosk-service-bar {
      position: absolute;
      top: 100px;
      left: 0;
      right: 0;
      height: 100px; /* 从 120px 减小到 100px */
      background: #ffffff;
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 0.75rem 0; /* 从 1rem 减小到 0.75rem */
      z-index: 999;
      overflow: hidden;

      .service-bar-container {
        width: var(--kiosk-content-width); /* 与顶部导航栏内容区域对齐 */
        max-width: 100%;
        margin: 0 auto; /* 居中对齐 */
        display: flex;
        justify-content: space-between; /* 均匀分布 */
        gap: 1rem;
        overflow: hidden;
        padding: 0;

        .service-quick-item {
          position: relative;
          flex: 1; /* 弹性宽度，均匀分布 */
          min-width: 140px; /* 最小宽度保证可读性 */
          height: 70px; /* 从 90px 减小到 70px */
          border-radius: 0.75rem;
          overflow: hidden;
          cursor: pointer;
          transition: transform 0.3s ease;
          /* 复用原有渐变背景 */
          background: linear-gradient(180deg, rgba(250, 255, 253, 0.8), rgba(225, 245, 248, 0.8));
          box-shadow: 0 0.25rem 1.25rem 0 rgba(52, 149, 239, 0.4);

          &.yellow {
            background: linear-gradient(180deg, rgba(255, 255, 255, 0.7), rgba(246, 240, 239, 0.7));
          }

          &.center {
            background: linear-gradient(90deg, #c2dff9, #c6e2fa);
          }

          &.hover-scale:hover {
            transform: scale(1.05);
          }

          .service-item-content {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            z-index: 2;
            padding: 1rem;
            display: flex;
            align-items: center;

            .service-title {
              color: #101333;
              font-size: 1.125rem; /* 1rem → 1.125rem */
              font-weight: 600;
              line-height: 1.2;
            }
          }

          .service-item-image {
            position: absolute;
            bottom: 0;
            right: 0.5rem;
            z-index: 1;
            width: 4rem;
            height: 3rem;
            opacity: 0.2;
          }
        }
      }
    }
  }
}

@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>