<script setup lang="ts">
import XBadge from '@af-mobile-client-vue3/components/data/XBadge/index.vue'
import XCellListFilter from '@af-mobile-client-vue3/components/data/XCellListFilter/index.vue'
import { isDark } from '@af-mobile-client-vue3/composables/dark'
import { getConfigByName, query } from '@af-mobile-client-vue3/services/api/common'
import useUserStore from '@af-mobile-client-vue3/stores/modules/user'
import { getRangeByType } from '@af-mobile-client-vue3/utils/queryFormDefaultRangePicker'
import { executeStrFunctionByContext } from '@af-mobile-client-vue3/utils/runEvalFunction'
import LoadError from '@af-mobile-client-vue3/views/common/LoadError.vue'
import {
  showConfirmDialog,
  showToast,
  ActionSheet as VanActionSheet,
  BackTop as VanBackTop,
  Button as VanButton,
  Checkbox as VanCheckbox,
  Col as VanCol,
  Icon as VanIcon,
  List as VanList,
  Popover as VanPopover,
  PullRefresh as VanPullRefresh,
  Row as VanRow,
  Search as VanSearch,
  Space as VanSpace,
  Tag as VanTag,
} from 'vant'
import { computed, getCurrentInstance, onBeforeMount, ref, useSlots, watch } from 'vue'
import { useRouter } from 'vue-router'

const {
  configName = '',
  fixQueryForm = null,
  idKey = 'o_id',
  serviceName,
  scanOptions,
  customAdd = false,
  customEdit = false,
  customDelete = false,
  hideAllActions = false,
  // 多选相关配置
  enableMultiSelect = false, // 是否启用多选功能
  multiSelectActions = [], // 多选操作按钮配置
  // 是否限制查询参数
  isLimitQuery = false,
  showFilter = true,
} = defineProps<{
  configName?: string
  fixQueryForm?: object
  idKey?: string
  serviceName?: string
  scanOptions?: {
    show?: boolean // 是否显示扫码按钮
    type?: string | string[] // 显示类型：可以是单个类型或类型数组 'nfc' / ['scan', 'nfc']
    defaultMode?: string // 默认模式
  }
  // 是否自定义新增、编辑、删除按钮
  customAdd?: boolean
  customEdit?: boolean
  customDelete?: boolean
  // 是否隐藏所有操作按钮
  hideAllActions?: boolean
  // 多选相关配置
  enableMultiSelect?: boolean // 是否启用多选功能
  multiSelectActions?: Array<{
    name: string
    key?: string
    color?: string
    icon?: string
  }> // 多选操作按钮配置
  showFilter?: boolean // 是否显示筛选模块
  // 是否限制查询参数
  isLimitQuery?: boolean
}>()

const emit = defineEmits<{
  (e: 'toDetail', item: any): void
  (e: 'update', item: any): void
  (e: 'delete', item: any): void
  (e: 'add'): void
  (e: string, item: any): void
  (e: 'updateCondition', params: any): void
  // 多选相关事件
  (e: 'multiSelectAction', action: string, selectedItems: any[], selectedItemsArray: any[]): void
  (e: 'selectionChange', selectedItems: any[]): void
  // 查询参数
  (e: 'queryParams', params: any): void
  // XFormItem 触发的事件(查询表单)
  (e: 'xFormItemEmitFunc', func: any, data: any, value: any): void
}>()

let rowKey = idKey ?? 'o_id'

const userState = useUserStore().getLogin()

const router = useRouter()

const orderVal = ref(undefined)

const sortordVal = ref(undefined)

// 配置内容
const configContent = ref({})

// 表单加载后是否立即执行查询
const isInitQuery = ref(false)

// 主列
const mainColumns = ref([])

// 副标题列
const subTitleColumns = ref([])

// 详情列
const detailColumns = ref([])

// 标签列
const tagList = ref([])

// 标题按钮列
const btnList = ref([])

// 底部列
const footColumns = ref([])

// 所有的复杂操作列
const allActions = ref([])

// 复杂操作列前三项
const mainActions = ref([])

// 复杂操作列其余项
const otherActions = ref([])

// 数据集
const list = ref([])

// 每个 Popover 的显示状态
const showPopover = ref<boolean[]>(list.value.map(() => false))

// 排序集
const orderList = ref([])

// 表单查询数组
const formQueryList = ref([])

// 总数据
const totalCount = ref(0)

// 当前页数
const pageNo = ref(1)

// 每页数量
const pageSize = 20

const searchValue = ref('')

// 数据加载状态
const loading = ref(false)
const refreshing = ref(false)
const finished = ref(false)
const isError = ref(false)
// 避免查询多次
const isLastPage = ref(false)

// 多选相关状态
const isMultiSelectMode = ref(false) // 是否处于多选模式
const selectedItems = ref<Set<string>>(new Set()) // 选中的项目ID集合
const longPressTimer = ref<number | null>(null) // 长按定时器
const longPressDelay = 1000 // 长按延迟时间（毫秒）

// 条件参数(查询框)
const conditionParams = ref(undefined)

// 主要按钮的状态
const buttonState = ref(undefined)

// 新增or查询的表单配置
const groupFormItems = ref({})
const title = ref('')

// 按钮权限
const buttonPermissions = ref([])

// 默认参数
const defaultParams = {}

// ActionSheet相关状态
const showActionSheet = ref(false)
const actionSheetActions = ref([])

// 行样式函数
const rowStyleFunction = ref<Function | string | null>(null)

// 行边框颜色映射（亮色模式）
const ROW_BORDER_COLORS_LIGHT: Record<string, string> = {
  success: 'rgba(82, 196, 26, 0.3)',
  error: 'rgba(245, 34, 47, 0.3)',
  magic: 'rgba(114, 46, 209, 0.3)',
  warn: 'rgba(250, 173, 20, 0.3)',
  info: 'rgba(0, 0, 0, 0.04)',
}

// 行边框颜色映射（深色模式）
const ROW_BORDER_COLORS_DARK: Record<string, string> = {
  success: 'rgba(82, 196, 26, 0.4)',
  error: 'rgba(245, 34, 47, 0.4)',
  magic: 'rgba(114, 46, 209, 0.4)',
  warn: 'rgba(250, 173, 20, 0.4)',
  info: 'rgba(255, 255, 255, 0.08)',
}

const slots = useSlots()

// 当前组件实例（不推荐使用，可能会在后续的版本更迭中调整，暂时用来绑定函数的上下文）
const currInst = getCurrentInstance()

// 定义主键
const primaryKey = ref('')
// 数据列
const tableColumns = ref([])

// 自定义操作按钮
const editButtonStateData = ref([])

// 初始化第一次查询状态(防止初始化时的下拉刷新导致的查询)
const firstStatus = ref(true)

// 列表底部的文字显示
function finishedBottomText() {
  if (!hideAllActions && buttonState.value?.add && buttonState.value.add === true && (filterButtonPermissions('add').state === false || ((filterButtonPermissions('add').state === true && userState.f.resources.f_role_name.includes((filterButtonPermissions('add').roleStr))))))
    return '已加载全部内容，如需新增请点击右上角的 + 号'
  else
    return '已加载全部内容'
}

// 判断当前是否有查询参数
const hasQueryParams = computed(() => {
  return Object.keys(defaultParams).length > 0 || searchValue.value || conditionParams.value
})

onBeforeMount(() => {
  initComponent()
})

// 组件初始化
function initComponent() {
  getConfigByName(configName, (result) => {
    groupFormItems.value = result

    // 数据主键名称
    primaryKey.value = result.primaryKey
    tableColumns.value = JSON.parse(JSON.stringify(result.columnJson))
    rowKey = getPrimaryKeyName()

    // 行样式函数
    rowStyleFunction.value = result?.rowStyleFunction

    title.value = result?.title
    const isQuery = result.createdQuery
    for (let i = 0; i < result.columnJson.length; i++) {
      const item = result.columnJson[i]
      item.span = item.flexSpan
      if (item.slotType === 'badge')
        item.dictName = item.slotKeyMap

      if (item.mobileColumnType === 'mobile_header_column') {
        mainColumns.value.push(item)
      }
      else if (item.mobileColumnType === 'mobile_subtitle_column') {
        subTitleColumns.value.push(item)
      }
      else if (item.mobileColumnType === 'mobile_details_column') {
        detailColumns.value.push(item)
      }
      else if (item.mobileColumnType === 'mobile_footer_column') {
        footColumns.value.push(item)
      }
      else if (item.mobileColumnType === 'mobile_tag_column') {
        tagList.value.push(item)
      }
      else if (item.slotType === 'action' && item.actionArr) {
        for (let j = 0; j < item.actionArr.length; j++) {
          allActions.value.push({
            text: item.actionArr[j].text,
            func: item.actionArr[j].func,
            customFunction: item.actionArr[j].customFunction,
          })
        }
      }

      if (item.mobileColumnType === 'mobile_header_column') {
        try {
          if (typeof item.btnIcon === 'string') {
            // 字符串 => 直接作为数组的一项
            btnList.value = [item.btnIcon]
          }
          else if (Array.isArray(item.btnIcon)) {
            // 已经是数组 => 直接赋值
            btnList.value = item.btnIcon
          }
          // 其他类型不处理
        }
        catch (e) {
          console.error('btnIcon 处理异常：', e)
        }
      }

      if (result.showSortIcon && item.sortable) {
        orderList.value.push({
          title: item.title,
          value: item.dataIndex,
        })
      }
    }
    configContent.value = result
    // 扁平化 type=group 的 groupItems，保持顺序
    const flatFormJson = []
    result.formJson.forEach((item) => {
      if (item.type === 'group' && Array.isArray(item.groupItems)) {
        item.groupItems.forEach((groupItem) => {
          if (!groupItem.isOnlyAddOrEdit) {
            flatFormJson.push(groupItem)
          }
        })
      }
      else {
        if (!item.isOnlyAddOrEdit && item.type !== 'group') {
          flatFormJson.push(item)
        }
      }
    })
    formQueryList.value = flatFormJson
    console.log('formQueryList', formQueryList.value)
    if (result.buttonState) {
      buttonState.value = result.buttonState
      buttonPermissions.value = result.buttonPermissions
      if (buttonState.value.edit && buttonState.value.edit === true && (filterButtonPermissions('edit').state === false || ((filterButtonPermissions('edit').state === true && userState.f.resources.f_role_name.includes((filterButtonPermissions('edit').roleStr))))))
        allActions.value.push({ text: '修改', func: 'update' })
      if (buttonState.value.delete && buttonState.value.delete === true && (filterButtonPermissions('delete').state === false || ((filterButtonPermissions('delete').state === true && userState.f.resources.f_role_name.includes((filterButtonPermissions('delete').roleStr))))))
        allActions.value.push({ text: '删除', func: 'delete' })
    }
    splitArrayAt(allActions.value, 3)

    // 初始化条件参数（从表单默认值中获取）
    initConditionParams(result.formJson, isQuery)

    // 自定义操作按钮
    editButtonStateData.value = result.editButtonStateData
  }, serviceName)
}

// 获取主键列名称
function getPrimaryKeyName() {
  if (primaryKey.value)
    return primaryKey.value
  const indexColumn = tableColumns.value.find(i => i?.slotType === 'index')
  return indexColumn ? indexColumn.dataIndex : tableColumns.value[0].dataIndex
}

// 初始化条件参数
function initConditionParams(formItems, isQuery) {
  let hasDefaults: boolean

  // 从表单配置中获取所有默认值
  formItems.forEach((item) => {
    if (item.model) {
      // 根据查询模式获取对应的默认值
      if (item.queryFormDefault !== undefined && item.queryFormDefault !== null) {
        if (item.type === 'rangePicker' && item.queryType === 'BETWEEN') {
          defaultParams[item.model] = getRangeByType(item.queryFormDefault, false)
        }
        else if (['treeSelect', 'select', 'checkbox'].includes(item.type) && ['curOrgId', 'curDepId', 'curUserId'].includes(item.queryFormDefault)) {
          if (item.queryFormDefault === 'curOrgId') {
            defaultParams[item.model] = item.type === 'select' ? userState.f.resources.orgid : [userState.f.resources.orgid]
          }
          if (item.queryFormDefault === 'curDepId') {
            defaultParams[item.model] = item.type === 'select' ? userState.f.resources.depids : [userState.f.resources.depids]
          }
          if (item.queryFormDefault === 'curUserId') {
            defaultParams[item.model] = item.type === 'select' ? userState.f.resources.id : [userState.f.resources.id]
          }
        }
        else {
          defaultParams[item.model] = item.queryFormDefault
        }
      }
    }
  })
  // eslint-disable-next-line prefer-const
  hasDefaults = true

  // 如果有默认值，则设置到条件参数中并立即执行查询
  isInitQuery.value = isQuery
  if (hasDefaults && isInitQuery.value) {
    // 延迟执行第一次查询，确保组件完全加载
    setTimeout(() => {
      onLoad(defaultParams)
    }, 100)
  }
  else if (hasDefaults) {
    firstStatus.value = false
  }
  else { /* empty */ }
}

// 刷新数据
function onRefresh() {
  if (firstStatus.value)
    return

  isError.value = false
  setTimeout(() => {
    // 重新加载数据
    // 将 loading 设置为 true，表示处于加载状态
    refreshing.value = true
    finished.value = false
    onLoad(defaultParams)
  }, 100)
}

// 加载数据
function onLoad(defaultParams = {}) {
  if (loading.value || (isLimitQuery && !hasQueryParams.value)) {
    return
  }
  loading.value = true
  if (refreshing.value) {
    list.value = []
    pageNo.value = 1
    isLastPage.value = false
  }
  if (!isLastPage.value) {
    let searchVal = searchValue.value
    if (searchVal === '')
      searchVal = undefined

    // 确保conditionParams不是undefined
    if (conditionParams.value === undefined)
      conditionParams.value = {}
    const mergedParams = mergeParams(defaultParams, conditionParams.value)
    // 输出查询条件，便于调试
    console.log('查询条件:', {
      pageNo: pageNo.value,
      pageSize,
      conditionParams: {
        $queryValue: searchVal,
        ...fixQueryForm,
        ...mergedParams,
      },
    })

    // 加载完成后，触发afterLoad事件
    emit('queryParams', { searchVal, ...fixQueryForm, ...mergedParams })

    query({
      queryParamsName: configName,
      pageNo: pageNo.value,
      pageSize,
      conditionParams: {
        $queryValue: searchVal,
        ...fixQueryForm,
        ...mergedParams,
      },
      sortField: orderVal?.value,
      sortOrder: sortordVal?.value,
    }, serviceName).then((res: any) => {
      totalCount.value = res.totalCount
      if (res.data.length === 0)
        isLastPage.value = true

      for (const item of res.data)
        list.value.push(item)
      if (list.value.length >= res.totalCount)
        finished.value = true
      else
        pageNo.value = pageNo.value + 1
    }).catch(() => {
      finished.value = true
      isError.value = true
    }).finally(() => {
      // 加载状态结束
      loading.value = false
      refreshing.value = false
      firstStatus.value = false
    })
  }
}

// 合并参数
function mergeParams(defaultParams: object, overrideParams: object) {
  const result = { ...defaultParams }
  for (const [key, value] of Object.entries(overrideParams)) {
    // 只有当overrideParams中的值不是undefined或空字符串时才覆盖
    if (value !== undefined) {
      result[key] = value
    }
  }
  return result
}

// 区分主要操作列与其他操作列
function splitArrayAt<T>(array: T[], index: number) {
  mainActions.value = array.slice(0, index)
  otherActions.value = array.slice(index)
}

// 新增：动态获取按钮分组
function getActionGroups(item: any, index: number) {
  const main: any[] = []
  const more: any[] = []
  let mainCount = 0

  // 遍历所有按钮，同时处理显示/隐藏和样式，避免多次遍历
  for (const action of allActions.value) {
    let visible = true
    let buttonStyle = {}

    // 处理有 customFunction 的按钮
    if (action.customFunction) {
      try {
        const result = executeStrFunctionByContext(currInst, action.customFunction, [item, index])

        if (typeof result === 'boolean') {
          visible = result
        }
        else if (result && typeof result === 'object') {
          visible = true
          buttonStyle = result
        }
      }
      catch (error) {
        console.error('Error in getActionGroups customFunction:', error)
        visible = false
      }
    }

    // 只处理可见的按钮
    if (visible) {
      const processedAction = { ...action, buttonStyle }

      // 直接分配到 main 或 more，避免后续的 slice 和 reverse 操作
      if (mainCount < 3) {
        main.unshift(processedAction) // 使用 unshift 实现逆序
        mainCount++
      }
      else {
        more.unshift(processedAction) // 使用 unshift 实现逆序
      }
    }
  }

  return { main, more }
}

watch(() => searchValue.value, (newVal) => {
  if (newVal === '')
    onRefresh()
})

// 配置中心->表单项展示函数
function handleFunctionStyle(funcString, record) {
  if (!funcString) {
    return {}
  }

  try {
    // 同步执行函数
    const obj = executeStrFunctionByContext(currInst, funcString, [record])
    // 如果返回的是对象，则直接返回
    if (obj && typeof obj === 'object') {
      return obj
    }
    // 其他情况返回空对象
    return {}
  }
  catch (error) {
    console.error('Error in handleFunctionStyle:', error)
    return {}
  }
}
function handleFunctionShow(funcString, record) {
  if (!funcString) {
    return true
  }

  try {
    // 同步执行函数
    const obj = executeStrFunctionByContext(currInst, funcString, [record])
    // 如果返回的是对象，则直接返回
    // 如果返回的是布尔值，则直接返回
    if (typeof obj === 'boolean') {
      return obj
    }
    // 其他情况返回空对象
    return true
  }
  catch (error) {
    console.error('Error in handleFunctionShow:', error)
    return true
  }
}
// 逆序排列主要按钮
const reversedMainActions = computed(() => {
  return [...mainActions.value].reverse()
})

// 设置 Popover 的事件
function onSelectMenu(item: any, event: any) {
  if (event.text === '删除') {
    if (customDelete) {
      emit('delete', item)
    }
    else {
      showConfirmDialog({
        title: '删除',
        message:
          '请确认是否删除！！！',
      }).then(() => {
        emit(event.func, item)
      }).catch(() => {
      })
    }
  }
  else if (event.text === '修改') {
    if (customEdit) {
      emit('update', item)
    }
    else {
      // 默认行为 - 导航到XForm页面
      router.push({
        name: 'XForm',
        // params: { id: item },
        query: {
          groupFormItems: JSON.stringify(groupFormItems.value),
          serviceName,
          formData: JSON.stringify(item),
          mode: '修改',
        },
      })
    }
  }
  else {
    emit(event.func, item)
  }
}

// 抛出新增按钮的事件
function addOption() {
  if (customAdd) {
    emit('add')
  }
  else {
    // 默认行为 - 导航到XForm页面
    router.push({
      name: 'XForm',
      query: {
        groupFormItems: JSON.stringify(groupFormItems.value),
        serviceName,
        formData: JSON.stringify({}),
        mode: '新增',
      },
    })
  }
}

// 按钮权限信息筛选
function filterButtonPermissions(btn) {
  return buttonPermissions.value.find(item => item.btnName === btn)
}

// 处理按钮点击
function handleButtonClick(btn, item) {
  emit(`${btn}`, item)
}

/**
 * 函数描述： 传入自定义条件进行查询(传入字段必须在琉璃中配置生成查询项才会生效)
 * @param {string} params - 查询条件map 例: { os_id:1 }
 * // 小提示：此处传入的条件会覆盖掉fixQueryForm(固定查询条件参数)
 */
function updateConditionAndRefresh(params: any) {
  if (params) {
    // 遍历参数，更新对应的表单值
    Object.entries(params).forEach(([key, value]) => {
      // 找到对应的表单项
      conditionParams.value[key] = value
    })
  }

  // 触发刷新
  onRefresh()
}
// 返回当前查询结果列表
function getCurrentList() {
  return list.value
}

// 暴露方法给父组件
defineExpose({
  getCurrentList,
  updateConditionAndRefresh,
  onRefresh,
})

// 多选相关计算属性
const selectedItemsArray = computed(() => {
  return list.value.filter(item => selectedItems.value.has(item[rowKey]))
})

const hasSelectedItems = computed(() => {
  return selectedItems.value.size > 0
})

// 多选相关方法
function startLongPress(item: any) {
  if (!enableMultiSelect)
    return

  longPressTimer.value = window.setTimeout(() => {
    enterMultiSelectMode(item)
  }, longPressDelay)
}

function cancelLongPress() {
  if (longPressTimer.value) {
    clearTimeout(longPressTimer.value)
    longPressTimer.value = null
  }
}

function enterMultiSelectMode(item: any) {
  isMultiSelectMode.value = true
  selectedItems.value.clear()
  const itemId = item[rowKey]
  selectedItems.value.add(itemId)
  updateActionSheetActions()
}

function exitMultiSelectMode() {
  isMultiSelectMode.value = false
  selectedItems.value.clear()
  showActionSheet.value = false
}

function updateActionSheetActions() {
  if (multiSelectActions.length > 0) {
    actionSheetActions.value = multiSelectActions.map(action => ({
      name: action.name,
      key: action.key || action.name,
      color: action.color || '#000000',
      icon: action.icon || 'records-o',
    }))
  }
  else {
    // 默认操作按钮
    actionSheetActions.value = [
      { name: '批量操作', key: 'batchOperation', color: '#000000', icon: 'records-o' },
    ]
  }

  if (hasSelectedItems.value) {
    showActionSheet.value = true
  }
}

function handleActionSheetSelect(action: any) {
  if (Array.from(selectedItems.value).length === 0 || selectedItemsArray.value.length === 0) {
    showToast('请选择至少一条数据')
    return
  }
  showActionSheet.value = false
  emit('multiSelectAction', action, Array.from(selectedItems.value), selectedItemsArray.value)

  // 执行操作后退出多选模式
  exitMultiSelectMode()
}

// 触发多选功能
function handleCardContainerClick(item: any) {
  if (!isMultiSelectMode.value)
    return

  const key = item[rowKey]
  if (selectedItems.value.has(key)) {
    selectedItems.value.delete(key)
  }
  else {
    selectedItems.value.add(key)
  }
  // 更新ActionSheet状态，但不退出多选模式
  updateActionSheetActions()

  emit('selectionChange', selectedItemsArray.value)
}

function handleCardClick(item: any, event: any) {
  // 如果处于多选模式，阻止默认的详情跳转
  if (isMultiSelectMode.value) {
    return
  }

  // 正常点击跳转到详情
  emit('toDetail', item)
}

// 主标题副标题点击 popover 展示
const showTitlePopoverKey = ref<string | null>(null)
const textPopoverLabel = ref('')
const textPopoverContent = ref('')

// 主标题
function openTextPopover(item: any, column: any, key: string, event: any) {
  event.stopPropagation()

  if (isMultiSelectMode.value) {
    handleCardContainerClick(item)
    return
  }

  textPopoverLabel.value = column?.title || ''
  const rawValue = item?.[column?.dataIndex]
  textPopoverContent.value = rawValue === undefined || rawValue === null ? '' : String(rawValue)
  showTitlePopoverKey.value = key
}

function handleTextPopoverShow(val: boolean, key: string) {
  if (!val && showTitlePopoverKey.value === key)
    showTitlePopoverKey.value = null
}

// 处理 XFormItem 触发的事件
function emitFunc(func: any, data: any, value: any) {
  emit('xFormItemEmitFunc', func, data, value)
}

// 自定义操作按钮点击
function editButtonClick(item: any) {
  emit(item.functionName)
}

/**
 * 获取行样式类型
 * @param record 当前行数据
 * @param index 当前行索引
 * @returns 样式类型字符串: success | error | magic | warn | info
 */
function getRowStyleType(record: any, index: number): string {
  if (rowStyleFunction.value) {
    try {
      // 如果是函数对象，直接执行
      if (typeof rowStyleFunction.value === 'function') {
        return rowStyleFunction.value(record, index)
      }
      // 如果是字符串函数，使用 executeStrFunctionByContext 执行
      if (typeof rowStyleFunction.value === 'string') {
        return executeStrFunctionByContext(currInst, rowStyleFunction.value, [record, index])
      }
    }
    catch (e) {
      console.warn('Row style function error:', e)
      return 'info'
    }
  }
  return 'info'
}
/**
 * 获取行边框颜色
 * @param styleType 样式类型
 * @returns 边框颜色值
 */
function getRowBorderColor(styleType: string): string {
  const colorMap = isDark ? ROW_BORDER_COLORS_DARK : ROW_BORDER_COLORS_LIGHT
  return colorMap[styleType] || colorMap.info
}

/**
 * 获取当前行的样式
 * @param item 当前行数据
 * @param index 当前行索引
 * @returns 包含边框颜色的对象
 */
function getRowStyle(item: any, index: number): { border: string } | Record<string, never> {
  // 多选模式下不应用行样式，保持原有样式
  if (isMultiSelectMode.value) {
    return {}
  }

  // 获取当前行的样式类型
  const styleType = getRowStyleType(item, index)

  // 获取边框颜色
  const borderColor = getRowBorderColor(styleType)

  // 返回完整的 border 样式（需要覆盖 CSS 中的 border 简写）
  return {
    border: `2px solid ${borderColor}`,
  }
}

// 因为vant组件会自己将loading设置为true，所以这里自己设置false
function onLoadData() {
  loading.value = false
  onLoad(defaultParams)
}
</script>

<template>
  <div id="XCellList">
    <VanRow v-if="showFilter" class="filter-condition" :class="{ dark: isDark }">
      <!-- 左侧动态插槽区域 -->
      <template v-for="(_, name) in slots" :key="name">
        <template v-if="typeof name === 'string' && name.startsWith('search-left-')">
          <div class="filter-icon-box">
            <slot :name="name" />
          </div>
        </template>
      </template>
      <VanCol class="search-col">
        <VanSearch
          v-model="searchValue"
          class="title-search"
          :class="{ 'multi-select-mode': isMultiSelectMode }"
          clearable
          placeholder="综合查询框..."
          shape="round"
          @search="onRefresh"
        />
      </VanCol>
      <!-- 新增按钮，放在查询框后、查询条件下拉按钮前 -->
      <VanCol
        v-if="!hideAllActions && buttonState?.add && buttonState.add === true && (filterButtonPermissions('add').state === false || ((filterButtonPermissions('add').state === true && userState.f.resources.f_role_name.includes((filterButtonPermissions('add').roleStr)))))"
        class="add-col"
      >
        <VanButton
          icon="add"
          type="primary"
          size="small"
          class="add-action-btn"
          :disabled="isMultiSelectMode"
          @click="addOption"
        />
      </VanCol>
      <!-- 自定义操作按钮 -->
      <VanCol
        v-if="editButtonStateData && editButtonStateData.length > 0"
        class="add-col edit-button"
      >
        <div v-for="(item, index) in editButtonStateData" :key="index">
          <VanButton
            :icon="item.buttonName"
            type="primary"
            size="small"
            class="add-action-btn"
            :disabled="isMultiSelectMode"
            @click="editButtonClick(item)"
          />
        </div>
      </VanCol>
      <!-- 右侧动态插槽区域 -->
      <template v-for="(_, name) in slots" :key="name">
        <template v-if="typeof name === 'string' && name.startsWith('search-right-')">
          <div class="filter-icon-box">
            <slot :name="name" />
          </div>
        </template>
      </template>
      <VanCol class="search-icon">
        <XCellListFilter
          v-model:sortord-val="sortordVal"
          v-model:order-val="orderVal"
          v-model:condition-params="conditionParams"
          :fix-query-form="fixQueryForm"
          :service-name="serviceName"
          :order-list="orderList"
          :form-query="formQueryList"
          :button-state="buttonState"
          :button-permissions="buttonPermissions"
          :scan-options="scanOptions"
          @on-refresh="onRefresh"
          @x-form-item-emit-func="emitFunc"
        />
      </VanCol>
    </VanRow>
    <slot name="search-after" />

    <!-- 多选功能提示 -->
    <div v-if="enableMultiSelect && !isMultiSelectMode" class="multi-select-tip">
      <VanIcon name="info-o" />
      <span>长按卡片可进入多选模式</span>
    </div>

    <!-- 多选模式提示 -->
    <div v-if="isMultiSelectMode" class="multi-select-tip">
      <VanIcon name="info-o" />
      <span>多选模式 - 已选择 {{ selectedItems.size }} 项</span>
      <VanButton
        size="small"
        type="default"
        @click="exitMultiSelectMode"
      >
        退出
      </VanButton>
    </div>

    <div class="main">
      <VanPullRefresh v-model="refreshing" success-text="加载完成" head-height="70" @refresh="onRefresh">
        <template v-if="!isError">
          <VanList
            v-model:loading="loading"
            class="list_main"
            :finished="finished"
            :finished-text="finishedBottomText()"
            :immediate-check="false"
            @load="onLoadData"
          >
            <div
              v-for="(item, index) in list"
              :key="`card_${index}`"
              class="card_item_main"
              :class="{ 'multi-select-mode': isMultiSelectMode }"
              :style="getRowStyle(item, index)"
              @click="handleCardContainerClick(item)"
              @touchstart="startLongPress(item)"
              @touchend="cancelLongPress"
              @touchcancel="cancelLongPress"
              @mousedown="startLongPress(item)"
              @mouseup="cancelLongPress"
              @mouseleave="cancelLongPress"
            >
              <VanRow gutter="20" class="card_item_header" align="center" @click="handleCardClick(item, $event)">
                <VanCol :span="24">
                  <div class="title-row" :class="{ 'multi-select-title-row': isMultiSelectMode }">
                    <!-- 多选模式下的选择框 -->
                    <div v-if="isMultiSelectMode" class="selection-checkbox">
                      <VanCheckbox
                        :model-value="selectedItems.has(item[rowKey])"
                        shape="square"
                        @click.stop
                        @update:model-value="(checked) => handleCardContainerClick(item)"
                      />
                    </div>
                    <div v-for="(column) in mainColumns" :key="`main_${column.dataIndex}`" class="main-title">
                      <VanPopover
                        :show="showTitlePopoverKey === `main_${index}_${column.dataIndex}`"
                        placement="bottom-start"
                        :overlay="false"
                        @update:show="(v) => handleTextPopoverShow(v, `main_${index}_${column.dataIndex}`)"
                      >
                        <template #reference>
                          <p
                            class="card_item_title"
                            :style="handleFunctionStyle(column.styleFunctionForTitle, item)"
                            :class="{ 'selectable-title': isMultiSelectMode }"
                            @click="(e) => openTextPopover(item, column, `main_${index}_${column.dataIndex}`, e)"
                          >
                            <XBadge
                              :style="handleFunctionStyle(column.styleFunctionForValue, item)"
                              :dict-name="column.dictName"
                              :dict-value="item[column.dataIndex]"
                              :dict-type="column.slotType"
                              :service-name="serviceName"
                            />
                          </p>
                        </template>
                        <div style="max-width: 80vw; padding: 6px 8px; font-size: 14px; line-height: 1.5;">
                          <div style="white-space: normal; word-break: break-word;">
                            {{ textPopoverContent }}
                          </div>
                        </div>
                      </VanPopover>
                    </div>
                    <div v-for="(column) in subTitleColumns" :key="`subtitle_${column.dataIndex}`" class="sub-title">
                      <VanPopover
                        :show="showTitlePopoverKey === `sub_${index}_${column.dataIndex}`"
                        placement="bottom-start"
                        :overlay="false"
                        @update:show="(v) => handleTextPopoverShow(v, `sub_${index}_${column.dataIndex}`)"
                      >
                        <template #reference>
                          <p
                            class="card_item_subtitle"
                            :style="handleFunctionStyle(column.styleFunctionForTitle, item)"
                            @click="(e) => openTextPopover(item, column, `sub_${index}_${column.dataIndex}`, e)"
                          >
                            <XBadge
                              :style="handleFunctionStyle(column.styleFunctionForValue, item)"
                              :dict-name="column.dictName"
                              :dict-value="item[column.dataIndex]"
                              :dict-type="column.slotType"
                              :service-name="serviceName"
                            />
                          </p>
                        </template>
                        <div style="max-width: 80vw; padding: 6px 8px; font-size: 14px; line-height: 1.5;">
                          <div style="white-space: normal; word-break: break-word;">
                            {{ textPopoverContent }}
                          </div>
                        </div>
                      </VanPopover>
                    </div>
                    <div v-if="!hideAllActions" class="action-buttons">
                      <VanButton
                        v-for="btn in btnList"
                        :key="btn.dataIndex"
                        class="action-button"
                        :icon="btn"
                        size="small"
                        :disabled="isMultiSelectMode"
                        @click.stop="handleButtonClick(btn, item)"
                      />
                    </div>
                  </div>
                </VanCol>
              </VanRow>
              <VanRow gutter="20" class="card_item_details" @click="handleCardClick(item, $event)">
                <VanCol v-for="column of detailColumns" :key="`details_${column.dataIndex}`" :span="column.span">
                  <p v-if="handleFunctionShow(column.showFormItemFuncForMobile, item)">
                    {{ (column.showLabel === undefined || column.showLabel) ? `${column.title}: ` : '' }}
                    <XBadge
                      :style="handleFunctionStyle(column.styleFunctionForValue, item)"
                      :dict-name="column.dictName"
                      :dict-value="item[column.dataIndex]"
                      :dict-type="column.slotType"
                      :service-name="serviceName"
                    />
                  </p>
                </VanCol>
              </VanRow>
              <VanRow v-if="tagList.length > 0" gutter="20" class="tag-row" @click="handleCardClick(item, $event)">
                <VanCol :span="24">
                  <div class="tag-container">
                    <div class="tag-wrapper">
                      <template
                        v-for="column of tagList"
                        :key="`tag_${column.dataIndex}`"
                      >
                        <VanTag
                          :show="handleFunctionShow(column.showFormItemFuncForMobile, item)"
                          :text-color="column.tagColor || '#991b1b'"
                          :color="column.tagBorderColor || '#fee2e2'"
                          size="large"
                          class="tag-item"
                        >
                          <div class="tag-content">
                            <VanIcon v-if="column.tagIcon" :name="column.tagIcon" class="tag-icon" />
                            <span v-if="column.showLabel === undefined || column.showLabel" class="tag-title">{{ `${column.title}:` }}</span>
                            <XBadge
                              :dict-name="column.dictName"
                              :dict-value="item[column.dataIndex]"
                              :service-name="serviceName"
                            />
                          </div>
                        </VanTag>
                      </template>
                    </div>
                  </div>
                </VanCol>
              </VanRow>
              <VanRow
                v-if="footColumns && footColumns.length > 0"
                gutter="20"
                class="card_item_footer"
                @click="handleCardClick(item, $event)"
              >
                <VanCol v-for="column of footColumns" :key="`foot_${column.dataIndex}`" :span="12">
                  <p v-if="handleFunctionShow(column.showFormItemFuncForMobile, item)">
                    <span :style="handleFunctionStyle(column.styleFunctionForTitle, item)">
                      {{ (column.showLabel === undefined || column.showLabel) ? `${column.title}: ` : '' }}
                    </span>
                    <XBadge
                      :style="handleFunctionStyle(column.styleFunctionForValue, item)"
                      :dict-name="column.dictName"
                      :dict-value="item[column.dataIndex]"
                      :dict-type="column.slotType"
                      :service-name="serviceName"
                    />
                  </p>
                </VanCol>
              </VanRow>
              <!-- 添加详情插槽 -->
              <slot name="item-detail" :item="item" />
              <VanRow v-if="!hideAllActions && allActions.length > 0" gutter="20" class="card_item_bottom">
                <VanCol span="4">
                  <VanPopover
                    v-if="!isMultiSelectMode && getActionGroups(item, index).more.length"
                    v-model:show="showPopover[index]"
                    placement="bottom-start"
                    :actions="getActionGroups(item, index).more"
                    @select="onSelectMenu(item, $event)"
                  >
                    <template #reference>
                      <div class="more-button">
                        <span>⋯</span>
                      </div>
                    </template>
                  </VanPopover>
                </VanCol>
                <VanCol span="20">
                  <VanRow justify="end">
                    <VanSpace>
                      <VanButton
                        v-for="button in getActionGroups(item, index).main"
                        :key="button.func"
                        :type="button.buttonStyle?.type || 'primary'"
                        :color="button.buttonStyle?.color"
                        size="normal"
                        class="action-btn"
                        :disabled="isMultiSelectMode"
                        @touchstart.stop
                        @mousedown.stop
                        @click="onSelectMenu(item, button)"
                      >
                        {{ button.text }}
                      </VanButton>
                    </VanSpace>
                  </VanRow>
                </VanCol>
              </VanRow>
            </div>
          </VanList>
        </template>
        <template v-else>
          <LoadError />
        </template>
      </VanPullRefresh>
      <VanBackTop />
    </div>

    <!-- 多选操作面板 -->
    <VanActionSheet
      v-model:show="showActionSheet"
      :actions="actionSheetActions"
      :overlay="false"
      @select="handleActionSheetSelect"
    />
  </div>
</template>

<style scoped lang="less">
#XCellList {
  height: 100%;
  display: flex;
  flex-direction: column;
  --van-search-padding: 3px;
  --van-dropdown-menu-title-padding: 3px;
  --van-text-color-2: rgb(75, 85, 99);
  --van-button-normal-font-size: 13px;
  .main {
    flex: 1;
    min-height: 0;
    overflow-y: auto;
    background-color: var(--van-background);
    padding: var(--van-padding-base) var(--van-padding-sm);

    p {
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      margin: 0;
    }

    .card_item_main {
      background-color: var(--van-background-2);
      border-radius: var(--van-radius-lg);
      margin: 0 0 var(--van-padding-xs) 0;
      padding: var(--van-padding-sm);
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.03);
      transition: all 0.3s ease;
      border: 1px solid rgba(0, 0, 0, 0.04);
      position: relative;

      &.multi-select-mode {
        border-color: var(--van-primary-color);
        background-color: rgba(25, 137, 250, 0.02);
      }

      .selection-checkbox {
        position: relative;
        margin-right: 8px;
        z-index: 1;
        flex-shrink: 0;

        :deep(.van-checkbox__icon) {
          border-color: var(--van-primary-color);
          border-radius: 2px;
        }

        :deep(.van-checkbox__icon--checked) {
          background-color: var(--van-primary-color);
          border-color: var(--van-primary-color);
          border-radius: 2px;
        }
      }

      &:active {
        transform: scale(0.98);
        box-shadow: 0 1px 4px rgba(0, 0, 0, 0.02);
      }

      .card_item_header {
        margin-bottom: var(--van-padding-base);

        .title-row {
          display: flex;
          align-items: center;
          margin-bottom: 2px;
          width: 100%;
          flex-wrap: nowrap; // 不换行，按钮保持同一行最右侧
          overflow: hidden; // 内容过长时在左侧截断

          &.multi-select-title-row {
            padding-left: 0;
          }

          .main-title {
            display: inline-flex;
            align-items: center;
            min-width: 0; // 允许缩小以便省略号生效
            :deep(.van-popover__wrapper) {
              display: inline-flex;
              max-width: 100%;
              min-width: 0;
            }
            .card_item_title {
              font-size: var(--van-font-size-lg);
              font-weight: 700;
              color: var(--van-text-color);
              margin: 0;

              &.selectable-title {
                cursor: pointer;
                padding: 4px 8px;
                border-radius: 4px;
                transition: all 0.2s ease;

                &:hover {
                  background-color: rgba(25, 137, 250, 0.1);
                }

                &:active {
                  background-color: rgba(25, 137, 250, 0.2);
                }
              }
            }
          }

          .sub-title {
            display: inline-flex;
            align-items: center;
            margin-left: 8px;
            min-width: 0; // 允许缩小以便省略号生效
            max-width: 40%;
            :deep(.van-popover__wrapper) {
              display: inline-flex;
              max-width: 100%;
              min-width: 0;
            }
            .card_item_subtitle {
              font-size: var(--van-font-size-md);
              color: var(--van-text-color-2);
            }
          }

          .action-buttons {
            display: flex;
            align-items: center;
            margin-left: auto; // 占据最右侧
            flex-shrink: 0; // 不被压缩，避免换行
            .action-button {
              margin-left: 6px;
              width: 32px;
              height: 32px;
              padding: 0;
              border: none;
              color: var(--van-primary-color);
              background-color: rgba(25, 137, 250, 0.1);
              border-radius: 6px;
              font-size: var(--van-font-size-lg);
              display: flex;
              align-items: center;
              justify-content: center;
              transition: all 0.2s ease;
              &:active {
                opacity: 0.7;
                background-color: rgba(25, 137, 250, 0.2);
                transform: scale(0.95);
              }
            }
          }
        }
      }

      .tag-row {
        margin-bottom: var(--van-padding-base);
      }

      .tag-container {
        width: 100%;
        .tag-wrapper {
          display: flex;
          flex-wrap: wrap;
          padding: 0 !important;
          align-items: center;
          width: 100%;
          margin: 0 -4px;

          .tag-item {
            width: auto;
            font-size: var(--van-font-size-md);
            margin: 4px 4px;
            flex: 0 0 auto;
            min-width: 0;
            max-width: 100%;
            :deep(.van-tag) {
              max-width: 100%;
              width: fit-content;
              display: inline-block;
              vertical-align: middle;
              white-space: normal;
              overflow-wrap: anywhere;
              word-break: break-word;
              padding: 2px 8px;
              border-radius: 4px;
              min-width: 0;
            }
            .tag-content {
              display: inline;
              white-space: normal;
              overflow-wrap: anywhere;
              word-break: break-word;
              max-width: 100%;
              min-width: 0;
            }
            .tag-icon {
              margin-right: 4px;
              font-size: 14px;
              display: inline-flex;
              align-items: center;
            }
            .tag-title {
              font-weight: normal;
              white-space: nowrap;
              margin-right: 4px;
            }
            .tag-title::after {
              content: '\00a0'; /* non-breaking space */
            }
          }
        }
      }

      .card_item_details {
        font-size: var(--van-font-size-md);
        color: var(--van-text-color-2);
        padding: 4px 0;

        .van-col {
          margin-bottom: 4px;
          p {
            display: flex;
            align-items: center;
            gap: 4px;

            span {
              flex: 1;
              min-width: 0;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            }

            :deep(.van-badge) {
              flex-shrink: 0;
            }
          }
        }
      }

      .card_item_footer {
        font-size: var(--van-font-size-md);
        color: var(--van-text-color-2);
        padding: 4px 0;
        .van-col:last-child {
          text-align: right;
        }
        .van-col:first-child {
          text-align: left;
        }
      }

      .card_item_bottom {
        margin-top: 8px;
        padding-top: 10px;
        border-top: 1px solid rgba(0, 0, 0, 0.06);

        .more-button {
          width: 37px;
          height: 37px;
          display: flex;
          align-items: center;
          justify-content: center;
          color: var(--van-text-color-2);
          cursor: pointer;
          font-size: var(--van-font-size-lg);
          background-color: var(--van-background);
          border-radius: 6px;
          transition: all 0.2s ease;
          border: 1px solid rgba(0, 0, 0, 0.06);
          margin: 2px 0 0 0;
          span {
            line-height: 1;
            margin-top: -2px;
          }
          &:active {
            opacity: 0.7;
            background-color: var(--van-background-2);
            transform: scale(0.95);
          }

          &.disabled {
            opacity: 0.5;
            cursor: not-allowed;
            pointer-events: none;
          }
        }

        .action-btn {
          --van-button-primary-border-color: #1890ff;
          --van-button-primary-background: #1890ff;
          min-width: 76px;
          height: 40px;
          border-radius: 10px;
          padding: 0 10px;
          // font-size: var(--van-font-size-md);
          transition: all 0.2s ease;
          &:active {
            transform: scale(0.95);
          }
        }
      }
    }
  }

  :deep(.van-search__field) {
    padding: 0 !important;
    height: 100%;
  }

  :deep(.van-popup),
  :deep(.van-popover) {
    border: none !important;
    outline: none !important;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15) !important;
    background-color: #ffffff !important;

    &::before,
    &::after {
      border: none !important;
      outline: none !important;
    }

    .van-popover__content {
      //background-color: #ffffff !important;
      border: none !important;
      outline: none !important;
      border-radius: 8px !important;
    }

    .van-popover__arrow,
    .van-popover_arrow {
      //background-color: #ffffff !important;
      border: none !important;
      outline: none !important;
    }

    .van-popover__action {
      color: #333 !important;

      //&:hover {
      //  //background-color: #f5f5f5 !important;
      //}
    }
  }

  .filter-condition {
    display: flex;
    align-items: center;
    padding: 8px 12px;
    background-color: #fff;
    gap: 1px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.02);
    position: sticky;
    top: 0;
    z-index: 100;

    .add-col {
      display: flex;
      align-items: center;
      margin: 0 4px;
      .add-action-btn {
        width: 40px;
        height: 40px;
        border-radius: 10px;
        background-color: var(--van-background);
        color: #323233;
        border: 1px solid rgba(0, 0, 0, 0.06);
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 16px;
        padding: 0;
        transition: all 0.2s;
        &:active {
          opacity: 0.85;
          background-color: rgba(25, 137, 250, 0.08);
          border-color: var(--van-primary-color);
          color: var(--van-primary-color);
        }
      }
    }
    .edit-button {
      gap: 8px;
    }
    :deep(.van-search) {
      width: 100%;
      padding: var(--van-search-padding);
      background-color: transparent;

      &.multi-select-mode {
        opacity: 0.8;
      }
    }
    :deep(.van-search__content) {
      border-radius: 8px;
      background-color: var(--van-background);
      padding: 4px 12px;
      border: 1px solid rgba(0, 0, 0, 0.01);
      height: 40px;
    }
    :deep(.van-field__left-icon) {
      color: var(--van-text-color-2);
    }
    :deep(.van-cell) {
      background-color: transparent;
    }
    :deep(.van-field__control::placeholder) {
      color: var(--van-text-color-2);
      font-size: 14px;
    }
    .van-col {
      display: flex;
      align-items: center;
      &.search-col {
        flex: 1;
        min-width: 0;
      }
      &.search-icon {
        flex-shrink: 0;
        padding: 0;
      }
    }
    .filter-icon-box {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 36px;
      height: 36px;
      border-radius: 8px;
      background-color: var(--van-background);
      cursor: pointer;
      position: relative;
      z-index: 1;
      border: 1px solid rgba(0, 0, 0, 0.06);
      transition: all 0.2s ease;
      &:active {
        opacity: 0.7;
        transform: scale(0.95);
      }
    }
  }
  .filter-condition.dark {
    background-color: #222222;
  }

  .multi-select-hint {
    display: flex;
    align-items: center;
    padding: 8px 12px;
    background-color: rgba(0, 0, 0, 0.04);
    border: 1px solid rgba(0, 0, 0, 0.08);
    border-radius: 6px;
    margin: 8px 12px;
    font-size: var(--van-font-size-sm);
    color: var(--van-text-color-2);

    .van-icon {
      margin-right: 6px;
      color: var(--van-text-color-3);
    }

    span {
      flex: 1;
    }
  }

  .multi-select-tip {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 8px 12px;
    background-color: rgba(25, 137, 250, 0.1);
    border: 1px solid rgba(25, 137, 250, 0.2);
    border-radius: 6px;
    margin: 8px 12px;
    font-size: var(--van-font-size-sm);
    color: var(--van-primary-color);

    .van-icon {
      margin-right: 6px;
    }

    span {
      flex: 1;
      margin-right: 8px;
    }
  }
}
</style>
