<script setup lang="ts">
import XForm from '@af-mobile-client-vue3/components/data/XForm/index.vue'
import { getConfigByName } from '@af-mobile-client-vue3/services/api/common'
import { Button as VanButton, Tab as VanTab, Tabs as VanTabs } from 'vant'
import { computed, onBeforeMount, onMounted, ref, useSlots } from 'vue'

const props = withDefaults(defineProps<{
  configName?: string
  serviceName?: string
  groupFormData?: object
  mode?: string
  isScrollspy?: boolean
  formShow?: any
  showTabHeader?: boolean
}>(), {
  configName: '',
  serviceName: undefined,
  groupFormData: () => ({}),
  mode: '查询',
  isScrollspy: true,
  formShow: undefined,
  showTabHeader: true,
})
const emit = defineEmits(['submit', 'xFormItemEmitFunc'])

const groupItems = ref([])
const formData = ref({})
const submitGroup = ref(false)
const submitSimple = ref(false)
const isInit = ref(false)

const slots = useSlots()
const renderableGroupItems = computed(() => {
  return groupItems.value.filter((item) => {
    if (props.formShow && (item.groupName || item.slotName)) {
      const showKey = `show${item.groupName || item.slotName}`
      if (props.formShow[showKey] === false) {
        return false
      }
    }
    if (item.formGroupType === 'slot') {
      return !!(item.slotName && slots[item.slotName])
    }
    return true
  })
})

// 组件初始化函数
function init() {
  formData.value = props.groupFormData
  getConfigByName(props.configName, (result) => {
    if (result?.groups) {
      groupItems.value = result.groups
      result.groups.forEach((group) => {
        if (!formData.value[group.groupName] && group.formGroupType !== 'slot')
          formData.value[group.groupName] = {}
        if (group.showSubmitBtn)
          submitGroup.value = true
      })
    }
    else {
      submitSimple.value = result?.showSubmitBtn
      groupItems.value = [{ ...result }]
    }
    isInit.value = true
  }, props.serviceName)
}
// watch(() => props.groupFormData, (_val) => {
//   formData.value = { ...formData.value, ...props.groupFormData }
// })
onBeforeMount(() => {
  init()
})
interface XFormLike {
  validate: () => Promise<void>
  formGroupName?: string
  form?: any
  getFormData?: () => object
}
const xFormListRef = ref<XFormLike[]>([])

// 注册表单实例，避免重复
function setRef(refValue: XFormLike) {
  if (refValue && !xFormListRef.value.includes(refValue)) {
    xFormListRef.value.push(refValue)
  }
}
// 注销表单实例
function removeRef(refValue: XFormLike) {
  const idx = xFormListRef.value.indexOf(refValue)
  if (idx !== -1)
    xFormListRef.value.splice(idx, 1)
}

async function submit() {
  console.log(props.groupFormData)
  const groupFormData = await getGroupFormData()
  if (!groupFormData) {
    return
  }
  emit('submit', formData.value)
}
async function getGroupFormData(isValidate = true) {
  for (const res of xFormListRef.value) {
    try {
      if (isValidate) {
        await res.validate()
      }
      if (res.formGroupName && typeof res.getFormData === 'function') {
        formData.value[res.formGroupName] = res.getFormData()
      }
    }
    catch (msg) {
      console.log('error:', msg)
      return
    }
  }
  return formData.value
}
function emitFunc(func: any, data: any, value: any) {
  emit(func, data, value)
  emit('xFormItemEmitFunc', func, data, value)
}
// 动态计算 offsetTop = var(--van-nav-bar-height) + 10px
const offsetTop = ref(0)
onMounted(() => {
  const root = document.documentElement
  const navBarHeight = getComputedStyle(root).getPropertyValue('--van-nav-bar-height')
  offsetTop.value = Number.parseInt(navBarHeight, 10) || 60 + 10
})

defineExpose({ init, removeRef, xFormListRef, getGroupFormData })
</script>

<template>
  <div v-if="isInit" id="x-form-group">
    <VanTabs :scrollspy="props.isScrollspy" sticky :offset-top="offsetTop" :show-header="props.showTabHeader">
      <VanTab
        v-for="(item, index) in renderableGroupItems"
        :key="item.groupName ? (item.groupName + index) : index"
        :title="item.describe ? item.describe : item.tableName "
      >
        <div
          class="x-form-group-item"
          :class="{ 'is-last': index === renderableGroupItems.length - 1 }"
        >
          <div v-if="item.describe && props.isScrollspy && (item.groupName || item.slotName)" class="form-group-title">
            <span class="form-group-bar" />
            <span class="form-group-text">{{ item.describe }}</span>
          </div>
          <template v-if="item.formGroupType === 'slot'">
            <slot
              :name="item.slotName"
              :item="item"
              :form-data="item.groupName ? formData[item.groupName] : formData"
              :set-ref="setRef"
              :remove-ref="removeRef"
            />
          </template>
          <template v-else>
            <XForm
              ref="xFormListRef"
              :mode="props.mode"
              :is-group-form="true"
              :group-form-items="item"
              :form-data="item.groupName ? formData[item.groupName] : formData"
              :form-name="item.groupName"
              :service-name="props.serviceName"
              :submit-button="submitSimple"
              @on-submit="submit"
              @x-form-item-emit-func="emitFunc"
            />
          </template>
        </div>
      </VanTab>
    </VanTabs>
    <div class="form-footer-fixed">
      <VanButton v-if="submitGroup" round block type="primary" @click="submit">
        提交
      </VanButton>
    </div>
  </div>
</template>

<style scoped lang="less">
#x-form-group {
  display: flex;
  flex-direction: column;
  background-color: rgb(247, 248, 250);
  height: 100%;
  flex: 1;
  overflow-y: auto;
  // 让 Tabs 区域自适应剩余空间
  .van-tabs {
    flex: 1;
    min-height: 0;
    overflow: auto;
  }
  .x-form-group-item {
    margin-bottom: 20px;
  }
  .form-footer-fixed {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;

    padding: 12px;
    box-sizing: border-box;

    /* 阴影效果 - 向上投射 */
    box-shadow:
      0 -4px 12px rgba(0, 0, 0, 0.1),
      0 -2px 4px rgba(0, 0, 0, 0.06);

    /* 毛玻璃背景 (移动端高级效果) */
    background-color: rgba(255, 255, 255, 0.85);
    -webkit-backdrop-filter: blur(10px);
    backdrop-filter: blur(10px);

    /* 边框增强立体感 */
    border-top: 1px solid rgba(0, 0, 0, 0.05);
  }
}
.x-form-group-item.is-last {
  min-height: calc(100vh - var(--van-nav-bar-height) - 40px);
}
.form-group-title {
  display: flex;
  align-items: center;
  padding-top: 12px;
  background: none;
  margin: 0 0 16px 4px;
}
.form-group-bar {
  width: 4px;
  height: 20px;
  background: #1989fa;
  border-radius: 4px;
  margin-right: 8px;
  flex-shrink: 0;
}
.form-group-text {
  font-weight: 600;
  font-size: 15px;
  color: #222;
  letter-spacing: 0.5px;
}
</style>
