<script setup lang="ts">
import Uploader from '@af-mobile-client-vue3/components/core/Uploader/index.vue'
import DateTimeSecondsPicker from '@af-mobile-client-vue3/components/data/XReportForm/DateTimeSecondsPicker.vue'
import XReportFormJsonRender from '@af-mobile-client-vue3/components/data/XReportForm/XReportFormJsonRender.vue'
import XSignature from '@af-mobile-client-vue3/components/data/XSignature/index.vue'
import { getConfigByNameWithoutIndexedDB } from '@af-mobile-client-vue3/services/api/common'
import {
  showFailToast,
  Button as vanButton,
  Cell as vanCell,
  CellGroup as vanCellGroup,
  Collapse as vanCollapse,
  CollapseItem as vanCollapseItem,
  Field as vanField,
  Form as vanForm,
  NavBar as vanNavBar,
  Skeleton as vanSkeleton,
} from 'vant'
import { nextTick, reactive, ref, watch } from 'vue'
// 移除 VueHashCalendar，使用自定义的 DateTimeSecondsPicker

// -------------------------  类型定义  -------------------------
interface configDefine {
  data?: any
  designMode?: string
  title?: string | undefined
  subTitle?: Array<cell> | undefined
  columns?: Array<any>
  slotsDeclare?: Array<string> | undefined
  tempData?: any
}

interface getConfigLock {
  status: boolean
}

interface cell {
  type: string
  dataIndex: string
  format: string | undefined
}

// -------------------------  数据  -------------------------
const props = defineProps({
  // 配置名
  configName: String,
  // 是否将动态行的label显示在标题上
  showInputColumnsLabelOnTitle: { default: false },
  slotName: String,
  showNav: { default: true },
  localConfig: { default: undefined },
  configData: { default: undefined },
})
const emit = defineEmits(['saveConfig'])
// 原始配置
const activatedConfig: configDefine = reactive({})
// 激活的配置名
const activatedConfigName = ref('')
// 下载的配置
const configFromWeb = reactive({})
// 定时器
let timer: NodeJS.Timeout
// 控制组件渲染
const scanFinish = ref(false)
// 折叠面板当前激活的值
const activeCollapseName = ref('副标题')

watch(() => props.configName, () => {
  // 这里是你的处理逻辑
  initComponent()
})

// -------------------------  方法  -------------------------
// 为inputs类型的数据，整理格式，供form展示用
function formatInputs(cell: cell): string[] {
  const format = cell.format
  const arr = format.split('{}')
  const result = []
  const reg = /[\u4E00-\u9FA5a-z]/gi
  arr.forEach((str) => {
    if (str.length >= 1 && str.match(reg)) {
      const strs = str.match(reg)
      result.push(strs.join(''))
    }
  })
  if (!activatedConfig.data[cell.dataIndex][result.length - 1]) {
    let dataKeySet = Object.keys(activatedConfig.data)
    dataKeySet = dataKeySet.filter((key) => {
      return key.startsWith(cell.dataIndex)
    })
    dataKeySet.sort()
    const target = dataKeySet[0]
    dataKeySet.shift()
    dataKeySet.forEach((key) => {
      activatedConfig.data[key].forEach((item) => {
        activatedConfig.data[target].push(item)
      })
    })

    for (let i = 0; i < result.length; i++) {
      if (!activatedConfig.data[cell.dataIndex][i])
        activatedConfig.data[cell.dataIndex][i] = undefined
    }
  }
  return result
}

// 左上角返回按钮
function onClickLeft(): void {
  history.back()
}

function generateDefaultRequiredMessage(field: any): string {
  const label = field.label || field.text || field.valueText || ''

  switch (field.type) {
    case 'input':
      return `请填写${label || '此项'}`
    case 'datePicker':
      return `请选择${label || '日期'}`
    case 'timePicker':
      return `请选择${label || '时间'}`
    case 'dateTimeSecondsPicker':
      return `请选择${label || '完整时间'}`
    case 'curDateInput':
      return `请设置${label || '时间'}`
    case 'signature':
      return `请完成${label || '签名'}`
    case 'images':
      return `请上传${label || '图片'}`
    case 'inputs':
      return `请完成${label || '此项'}的填写`
    default:
      return `请完成${label || '此项'}的填写`
  }
}

// 检查字段值是否为空
function isFieldEmpty(value: any): boolean {
  if (value === null || value === undefined || value === '') {
    return true
  }
  if (Array.isArray(value) && value.length === 0) {
    return true
  }
  return typeof value === 'object' && Object.keys(value).length === 0
}

// 表单校验
function validateForm(): boolean {
  const errors: string[] = []

  // 校验主表单字段
  activatedConfig.columns.forEach((row: any) => {
    if (row.required === true) {
      const dataIndex = row.dataIndex
      let value

      if (dataIndex.includes('@@@')) {
        value = activatedConfig.tempData?.[dataIndex]
      }
      else {
        if (row.type === 'images') {
          value = activatedConfig.data.images?.[dataIndex]
        }
        else {
          value = activatedConfig.data[dataIndex]
        }
      }

      if (isFieldEmpty(value)) {
        const message = row.requiredMessage || generateDefaultRequiredMessage(row)
        errors.push(message)
      }
    }

    // 校验动态行中的字段
    if (row.type === 'inputColumns' && row.definition) {
      const dynamicData = activatedConfig.data[row.dataIndex]
      if (Array.isArray(dynamicData)) {
        dynamicData.forEach((item: any, index: number) => {
          row.definition.forEach((def: any) => {
            if (def.required === true) {
              const value = item[def.dataIndex]
              if (isFieldEmpty(value)) {
                const message = def.requiredMessage || generateDefaultRequiredMessage(def)
                errors.push(`第${index + 1}行：${message}`)
              }
            }
          })
        })
      }
    }
  })

  // 校验副标题字段（如果有的话）
  if (activatedConfig.subTitle) {
    activatedConfig.subTitle.forEach((subCell: any) => {
      if (subCell.required === true) {
        const value = activatedConfig.data[subCell.dataIndex]
        if (isFieldEmpty(value)) {
          const message = subCell.requiredMessage || generateDefaultRequiredMessage(subCell)
          errors.push(message)
        }
      }
    })
  }

  if (errors.length > 0) {
    // 显示第一个错误信息
    showFailToast(errors[0])

    return false
  }

  return true
}

// 提交按钮
function onSubmit(): void {
  // 调试：打印所有字段的required状态
  console.log('所有字段配置:', activatedConfig.columns.map(row => ({
    type: row.type,
    label: row.label,
    required: row.required,
    dataIndex: row.dataIndex,
  })))

  // 先进行表单校验
  if (!validateForm()) {
    return
  }

  if (activatedConfig.tempData) {
    const keys = Object.keys(activatedConfig.tempData)
    keys.forEach((key) => {
      changeDeepObject(activatedConfig.data, key, activatedConfig.tempData[key])
    })
  }
  console.warn('保存', activatedConfig)
  emit('saveConfig', activatedConfig)
}

// // 动态行新增
// function addInputColumns(dataIndex: string, define: Array<any>): void {
//   const temp = {}
//   define.forEach((def) => {
//     let begin = def.initialValue
//     if (def.type === 'increment') {
//       if (activatedConfig.data[dataIndex].length > 0) {
//         begin = activatedConfig.data[dataIndex][activatedConfig.data[dataIndex].length - 1][def.dataIndex]
//         begin = Number.parseInt(begin)
//       }
//       temp[def.dataIndex] = begin + def.step
//     }
//     else {
//       temp[def.dataIndex] = ''
//     }
//   })
//   activatedConfig.data[dataIndex].push(temp)
// }
//
// // 动态行删除
// function removeInputColumns(dataIndex: string) {
//   activatedConfig.data[dataIndex].pop()
// }

// 扫描所有插槽名
function scanConfigName(config: configDefine, resut: Array<string>): void {
  if (config.slotsDeclare) {
    config.slotsDeclare.forEach((name) => {
      resut.push(name)
    })
  }
}

// 检查slot是否在配置文件中包含，如果没有包含，则视为非法获取
function checkSlotDefine(config: configDefine): boolean {
  const slotsDeclare = config.slotsDeclare
  const total = slotsDeclare.length
  let count = 0
  slotsDeclare.forEach((declare) => {
    config.columns.forEach((row: Array<any>) => {
      row.forEach((cell) => {
        if (cell.slotConfig === declare)
          count++
      })
    })
  })

  return count === total
}

// 扫描配置，如果有插槽则拼接插槽
function scanConfigSlot(config: configDefine): void {
  const columnsArr: Array<any> = config.columns
  for (let i = 0; i < columnsArr.length; i++) {
    for (let j = 0; j < columnsArr[i].length; j++) {
      // 如果发现type为slot，开始匹配对应的slot配置文件
      if (columnsArr[i][j].type === 'slot') {
        const targetName = columnsArr[i][j].slotConfig
        // 找不到目标插槽配置
        if (!configFromWeb[targetName] || !configFromWeb[targetName].columns)
          return

        // 替换columns，合并data
        config.columns[i] = []
        const before = config.columns.slice(0, i)
        let after = config.columns.slice(i + 1, config.columns.length)

        const addArr = []

        if (configFromWeb[targetName].cardMode === true) {
          const temp = [{
            type: 'card',
            content: [],
            label: configFromWeb[targetName].title,
          }]
          for (let k = 0; k < configFromWeb[targetName].columns.length; k++) {
            configFromWeb[targetName].columns[k].forEach((cell) => {
              temp[0].content.push(cell)
            })
          }
          addArr.push(temp)
        }
        else {
          for (let k = 0; k < configFromWeb[targetName].columns.length; k++) {
            const temp = []
            configFromWeb[targetName].columns[k].forEach((cell) => {
              temp.push(cell)
            })
            addArr.push(temp)
          }
        }

        const newArr = []
        // 拼接之前的数组
        if (before.length > 0) {
          if (before.length >= 1) {
            before.forEach((item) => {
              newArr.push(item)
            })
          }
          else {
            newArr.push(before)
          }
        }

        addArr.forEach((arr) => {
          newArr.push(arr)
        })

        // 拼接之后的数组
        if (after.length === 1) {
          if (after[0].type === 'slot' || after[0][0].type === 'slot')
            after = []
        }
        if (after.length > 0) {
          if (after.length >= 1) {
            after.forEach((item) => {
              newArr.push(item)
            })
          }
          else {
            newArr.push(after)
          }
        }

        config.columns = newArr
        if (configFromWeb[targetName].slotsDeclare)
          config.slotsDeclare = configFromWeb[targetName].slotsDeclare

        else
          config.slotsDeclare = []

        if (config.data.images && configFromWeb[targetName].data.images) {
          config.data.images = { ...config.data.images, ...configFromWeb[targetName].data.images }
          delete configFromWeb[targetName].data.images
        }
        config.data = { ...config.data, ...configFromWeb[targetName].data }
      }
    }
  }
  Object.assign(activatedConfig, config)
}

// 获取并拼装插槽
function getConfigAndJoin(config: configDefine, outerLock: getConfigLock): void {
  // 检查主配置插槽声明是否合法
  const check = checkSlotDefine(config)
  const waitForDownloadSlotName = []
  if (check) {
    // 扫描主配置中声明的插槽名
    scanConfigName(config, waitForDownloadSlotName)

    const total = waitForDownloadSlotName.length
    let count = 0

    // 挨个获取插槽
    waitForDownloadSlotName.forEach((configName) => {
      getConfigByNameWithoutIndexedDB(configName).then((res) => {
        configFromWeb[configName] = res
        count++
      })
    })

    const timer = setInterval(() => {
      if (count >= total) {
        clearInterval(timer)
        scanConfigSlot(config)
        if (config.slotsDeclare.length > 0) {
          const lock: getConfigLock = { status: true }
          getConfigAndJoin(config, lock)
          const innerTimer = setInterval(() => {
            if (!lock.status) {
              clearInterval(innerTimer)
              outerLock.status = false
            }
          }, 100)
        }
        else {
          outerLock.status = false
        }
      }
    }, 100)
  }
  else {
    outerLock.status = false
  }
}

function deserializeFunctionAndRun(functionStr: string, value: any) {
  try {
    // eslint-disable-next-line no-new-func
    const fun = new Function('value', 'activatedConfig', `return (${functionStr})(value, activatedConfig)`)
    return fun(value, activatedConfig)
  }
  catch (err) {
    console.error('Failed to deserialize and run function:', err)
    return null
  }
}

function deserializeFunctionAndRunWithConfig(functionStr: string) {
  try {
    // eslint-disable-next-line no-new-func
    const fun = new Function('activatedConfig', `return (${functionStr})(activatedConfig)`)
    return fun(activatedConfig)
  }
  catch (err) {
    console.error('Failed to deserialize and run function with config:', err)
    return null
  }
}

// 将table配置的表格转换为适合Form展示的格式
function formatConfigToForm(config: configDefine): void {
  const formColumns: Array<object> = []
  const labels: Array<string> = []
  for (let i = 0; i < config.columns.length; i++) {
    let tempObj: {
      customFunction?: any
      inputColumns?: boolean
      dataIndex: string
      label: string
      listType?: string
      listLength?: number
      valueText?: string
      type: string | undefined
      format?: string
      definition?: Array<any>
      editable?: boolean
      inputReadOnly?: boolean
      content?: Array<any>
      text?: string
      required?: boolean
      requiredMessage?: string
    } = {
      label: '',
      type: undefined,
      dataIndex: '',
    }

    const row: Array<any> = config.columns[i]
    let listArr = []
    for (let j = 0; j < row.length; j++) {
      switch (row[j].type) {
        case 'column' :
          if (row[j].customFunctionForDynamicDataIndex)
            row[j].dataIndex = deserializeFunctionAndRunWithConfig(row[j].customFunctionForDynamicDataIndex)
          if (j === row.length - 1) {
            if (row[j].customFunction) {
              tempObj.customFunction = row[j].customFunction
              tempObj.label = deserializeFunctionAndRun(row[j].customFunction, row[j].dataIndex)
            }
            else {
              labels.push(tempObj.label)
              labels.push(row[j].text)
              tempObj = {
                label: '',
                type: undefined,
                dataIndex: '',
              }
            }
          }
          else if (tempObj.label && tempObj.dataIndex) {
            formColumns.push(tempObj)
            tempObj = {
              label: '',
              type: undefined,
              dataIndex: '',
            }
          }
          else if (tempObj.customFunction) {
            formColumns.push(tempObj)
            tempObj = {
              label: '',
              type: undefined,
              dataIndex: '',
            }
          }
          else if (tempObj.label && !tempObj.dataIndex) {
            labels.push(tempObj.label)
            tempObj = {
              label: '',
              type: undefined,
              dataIndex: '',
            }
          }
          if (row[j].customFunction) {
            tempObj.customFunction = row[j].customFunction
            tempObj.label = deserializeFunctionAndRun(row[j].customFunction, row[j].dataIndex)
          }
          else {
            tempObj.label = row[j].text
          }
          break
        case 'value' :
          tempObj.valueText = row[j].value
          tempObj.editable = false
          tempObj.type = 'showValue'
          break
        case 'input' :
          if (row[j].customFunctionForDynamicDataIndex)
            row[j].dataIndex = deserializeFunctionAndRunWithConfig(row[j].customFunctionForDynamicDataIndex)
          tempObj.dataIndex = row[j].dataIndex
          tempObj.type = 'input'
          if (row[j].inputReadOnly)
            tempObj.inputReadOnly = true
          tempObj.required = row[j].required
          break
        case 'curDateInput' :
          tempObj.dataIndex = row[j].dataIndex
          tempObj.text = row[j].text
          tempObj.type = 'curDateInput'
          tempObj.required = row[j].required
          break
        case 'datePicker' :
          tempObj.dataIndex = row[j].dataIndex
          tempObj.text = row[j].text
          tempObj.type = 'datePicker'
          tempObj.required = row[j].required
          break
        case 'timePicker' :
          tempObj.dataIndex = row[j].dataIndex
          tempObj.text = row[j].text
          tempObj.type = 'timePicker'
          tempObj.required = row[j].required
          break
        case 'dateTimeSecondsPicker' :
          tempObj.dataIndex = row[j].dataIndex
          tempObj.text = row[j].text
          tempObj.type = 'dateTimeSecondsPicker'
          tempObj.required = row[j].required
          break
        case 'signature' :
          tempObj.dataIndex = row[j].dataIndex
          tempObj.text = row[j].text
          tempObj.type = 'signature'
          tempObj.required = row[j].required
          break
        case 'inputs' :
          if (!tempObj.format)
            tempObj.format = ''
          if (!tempObj.dataIndex)
            tempObj.dataIndex = row[j].dataIndex
          tempObj.format += row[j].format
          tempObj.type = 'inputs'
          if (row[j].inputReadOnly)
            tempObj.inputReadOnly = true
          break
        case 'images' :
          tempObj.dataIndex = row[j].dataIndex
          tempObj.type = 'images'
          break
        case 'inputColumns' :
          tempObj.label = ''
          tempObj.dataIndex = row[j].dataIndex
          tempObj.definition = row[j].definition
          if (labels.length > 0) {
            for (let k = 0; k < tempObj.definition.length; k++) {
              if (labels[k].length > 1) {
                tempObj.definition[k].label = labels[k]
                if (props.showInputColumnsLabelOnTitle) { // 动态行label展示在标题
                  if (k === tempObj.definition.length - 1)
                    tempObj.label = `${tempObj.label} ${labels[k].replace(/\s*/g, '')}`
                  else
                    tempObj.label = `${tempObj.label} ${labels[k].replace(/\s*/g, '')} :`
                }
                else { // 动态行仅展示为’动态行‘
                  tempObj.label = '动态行'
                }
              }
              else {
                tempObj.definition[k].label = ''
              }
            }
          }
          tempObj.type = 'inputColumns'
          break
        case 'list' :
          tempObj.valueText = row[j].listHead
          tempObj.type = 'list'
          tempObj.listType = row[j].listType
          tempObj.dataIndex = row[j].dataIndex
          if (row[j].content)
            tempObj.content = row[j].content
          tempObj.listLength = row[j].listLength
          listArr.push(tempObj)
          tempObj = {
            label: '',
            type: undefined,
            dataIndex: '',
          }
      }
    }
    if (listArr.length > 0)
      formColumns.push({ type: 'list', content: listArr })
    else if (tempObj.type || tempObj.label)
      formColumns.push(tempObj)
    listArr = []
    tempObj = {
      label: '',
      type: undefined,
      dataIndex: '',
    }
  }
  activatedConfig.columns = formColumns
}

// 获取子组件更新的file列表
function updateFile(files, index) {
  files.forEach((file) => {
    if (file.content)
      delete file.content
    if (file.file)
      delete file.file
    if (file.objectUrl)
      delete file.objectUrl
  })
  if (index.includes('@@@'))
    changeDeepObjectDeepCopy(activatedConfig.data.images, index, files)
  else
    activatedConfig.data.images[index] = files
}

// function handleInputDeepChange(event, dataIndex) {
//   this.$forceUpdate()
// }
function getDeepObject(obj, strPath) {
  const arr = strPath.split('@@@')
  let result = obj[arr[0]]
  arr.shift()
  try {
    while (arr.length > 0) {
      result = result[arr[0]]
      arr.shift()
    }
  }
  catch {
    result = undefined
  }
  return result
}

function changeDeepObject(obj, strPath, newVal) {
  const arr = strPath.split('@@@')
  if (arr.length === 1) {
    obj[arr[0]] = newVal
  }
  else {
    let result = obj[arr[0]]
    arr.shift()
    while (arr.length > 1) {
      result = result[arr[0]]
      arr.shift()
    }
    result[arr[0]] = newVal
  }
}

function changeDeepObjectDeepCopy(obj, strPath, newVal) {
  const arr = strPath.split('@@@')
  if (arr.length === 1) {
    obj[arr[0]] = newVal
  }
  else {
    let result = obj[arr[0]]
    arr.shift()
    while (arr.length > 1) {
      result = result[arr[0]]
      arr.shift()
    }
    Object.assign(result[arr[0]], newVal)
  }
}

// -------------------------  初始化  -------------------------
initComponent()

function initComponent() {
  if (props.localConfig !== undefined && Object.keys(props.localConfig).length > 0) {
    Object.assign(activatedConfig, props.localConfig)

    if (activatedConfig.designMode === 'json') {
      activatedConfig.data = {}
      Object.assign(activatedConfig.data, props.configData)
      nextTick(() => {
        scanFinish.value = true
      })
      return
    }
    else {
      const lock = { status: true }
      if (activatedConfig.slotsDeclare) {
        getConfigAndJoin(activatedConfig, lock)
        timer = setInterval(() => {
          if (!lock.status) {
            clearInterval(timer)
            // 将配置文件格式更改为更利于Form的组织形式
            formatConfigToForm(activatedConfig)
            nextTick(() => {
              scanFinish.value = true
            })
          }
        }, 100)
      }
      else {
        formatConfigToForm(activatedConfig)
        nextTick(() => {
          scanFinish.value = true
        })
      }
      if (props.configData !== undefined)
        Object.assign(activatedConfig.data, props.configData)

      activatedConfig.columns.forEach((row) => {
        if (row.dataIndex && row.dataIndex.includes('@@@')) {
          if (!activatedConfig.tempData) {
            activatedConfig.tempData = {}
          }
          if (row.type === 'images') {
            activatedConfig.tempData[row.dataIndex] = getDeepObject(activatedConfig.data.images, row.dataIndex)
          }
          else {
            activatedConfig.tempData[row.dataIndex] = getDeepObject(activatedConfig.data, row.dataIndex)
          }
        }
        // 为了兼容旧的结构，保留原有的逻辑
        if (row.forEach) {
          row.forEach((item) => {
            if (item.dataIndex && item.dataIndex.includes('@@@')) {
              if (!activatedConfig.tempData) {
                activatedConfig.tempData = {}
              }
              if (item.type === 'images') {
                activatedConfig.tempData[item.dataIndex] = getDeepObject(activatedConfig.data.images, item.dataIndex)
              }
              else {
                activatedConfig.tempData[item.dataIndex] = getDeepObject(activatedConfig.data, item.dataIndex)
              }
            }
          })
        }
      })
      console.warn('初始化完成，配置：', activatedConfig)
    }
  }

  if (props.slotName)
    activatedConfigName.value = props.slotName

  else
    activatedConfigName.value = props.configName

  getConfigByNameWithoutIndexedDB(activatedConfigName.value).then((result) => {
    Object.assign(activatedConfig, result)
    if (activatedConfig.designMode === 'json') {
      if (props.configData === undefined) {
        console.error('无法找到json配置的数据')
      }
      else {
        activatedConfig.data = {}
        Object.assign(activatedConfig.data, props.configData)
        nextTick(() => {
          scanFinish.value = true
        })
      }
    }
    else {
      const lock = { status: true }
      if (activatedConfig.slotsDeclare) {
        getConfigAndJoin(activatedConfig, lock)
        timer = setInterval(() => {
          if (!lock.status) {
            clearInterval(timer)
            // 将配置文件格式更改为更利于Form的组织形式
            formatConfigToForm(activatedConfig)
            nextTick(() => {
              scanFinish.value = true
            })
          }
        }, 100)
      }
      else {
        formatConfigToForm(activatedConfig)
        nextTick(() => {
          scanFinish.value = true
        })
      }
      if (props.configData !== undefined)
        Object.assign(activatedConfig.data, props.configData)
    }

    activatedConfig.columns.forEach((row) => {
      row.forEach((item) => {
        if (item.dataIndex && item.dataIndex.includes('@@@')) {
          if (!activatedConfig.tempData) {
            activatedConfig.tempData = {}
            activatedConfig.tempData[item.dataIndex] = getDeepObject(activatedConfig.data, item.dataIndex)
            if (item.type === 'images')
              activatedConfig.tempData[item.dataIndex] = getDeepObject(activatedConfig.data.images, item.dataIndex)
          }
          else {
            activatedConfig.tempData[item.dataIndex] = getDeepObject(activatedConfig.data, item.dataIndex)
            if (item.type === 'images')
              activatedConfig.tempData[item.dataIndex] = getDeepObject(activatedConfig.data.images, item.dataIndex)
          }
        }
      })
    })
  }).catch((e) => {
    console.error(e)
  })
}
function getNow() {
  const date = new Date()
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

// 移除了旧的日期时间选择器相关方法，现在使用 DateTimeSecondsPicker 组件
</script>

<template>
  <!-- 标题栏 -->
  <van-nav-bar
    v-if="showNav"
    title="动态报表表单"
    left-text="返回"
    left-arrow
    @click-left="onClickLeft"
  />
  <div v-if="scanFinish" class="main">
    <template v-if="activatedConfig.designMode === 'json'">
      <XReportFormJsonRender :json-config="activatedConfig" />
    </template>
    <template v-else>
      <!--  标题  -->
      <h2 v-if="activatedConfig.title" class="title" v-html="activatedConfig.title" />
      <!--  副标题  -->
      <!--      <div v-if="activatedConfig.subTitle && activatedConfig.subTitle.length > 0" class="form_item"> -->
      <!--        <van-collapse v-model="activeCollapseName" accordion> -->
      <!--          <van-collapse-item title="副标题" name="副标题"> -->
      <!--            <van-form> -->
      <!--              <van-cell-group inset> -->
      <!--                <template v-for="(subCell, cellIndex) in activatedConfig.subTitle" :key="cellIndex"> -->
      <!--                  <template v-if="subCell.type === 'inputs'"> -->
      <!--                    <template v-for="(item, itemIndex) in formatInputs(subCell)" :key="itemIndex"> -->
      <!--                      <van-field -->
      <!--                        v-model="activatedConfig.data[subCell.dataIndex][itemIndex]" -->
      <!--                        :label="`${item}:`" -->
      <!--                        clearable -->
      <!--                        type="textarea" -->
      <!--                        rows="1" -->
      <!--                        autosize -->
      <!--                        :placeholder="`请输入${item}`" -->
      <!--                      /> -->
      <!--                    </template> -->
      <!--                  </template> -->
      <!--                  <template v-else> -->
      <!--                    <van-field -->
      <!--                      v-model="activatedConfig.data[subCell.dataIndex]" -->
      <!--                      :label="`${subCell.format}:`" -->
      <!--                      clearable -->
      <!--                      type="textarea" -->
      <!--                      rows="1" -->
      <!--                      autosize -->
      <!--                      :placeholder="`请输入${subCell.format}`" -->
      <!--                    /> -->
      <!--                  </template> -->
      <!--                </template> -->
      <!--              </van-cell-group> -->
      <!--            </van-form> -->
      <!--          </van-collapse-item> -->
      <!--        </van-collapse> -->
      <!--      </div> -->
      <!--  表单项  -->
      <div class="form_item">
        <van-collapse v-model="activeCollapseName" accordion>
          <van-collapse-item title="操作卡内容" name="操作卡内容">
            <van-form>
              <template v-for="(row, index) in activatedConfig.columns" :key="index">
                <!--     value属性      -->
                <van-cell-group v-if="row.type === 'showValue'" inset class="cell_group">
                  <van-cell center :title="row.label" :value="row.valueText" />
                </van-cell-group>
                <!--     input      -->
                <van-cell-group v-else-if="row.type === 'input'" inset class="cell_group" :title="row.label" :class="{ 'required-field': row.required }">
                  <template v-if="row.inputReadOnly === true">
                    <template v-if="row.dataIndex.includes('@@@')">
                      <van-field
                        v-model="activatedConfig.tempData[row.dataIndex]"
                        :label="`${row.label}:`"
                        :placeholder="`请输入${row.label}`"
                        clearable
                        type="textarea"
                        rows="1"
                        :disabled="true"
                        autosize
                      />
                    </template>
                    <template v-else>
                      <van-field
                        v-model="activatedConfig.data[row.dataIndex]"
                        :label="`${row.label}:`"
                        :placeholder="`请输入${row.label}`"
                        clearable
                        type="textarea"
                        rows="1"
                        :disabled="true"
                        autosize
                      />
                    </template>
                  </template>
                  <template v-else>
                    <template v-if="row.dataIndex.includes('@@@')">
                      <van-field
                        v-model="activatedConfig.tempData[row.dataIndex]"
                        :label="`${row.label}:`"
                        :placeholder="`请输入${row.label}`"
                        clearable
                        type="textarea"
                        rows="1"
                        autosize
                      />
                    </template>
                    <template v-else>
                      <van-field
                        v-model="activatedConfig.data[row.dataIndex]"
                        :label="`${row.label}:`"
                        :placeholder="`请输入${row.label}`"
                        clearable
                        type="textarea"
                        rows="1"
                        autosize
                      />
                    </template>
                  </template>
                </van-cell-group>
                <!--     curDateInput      -->
                <van-cell-group v-else-if="row.type === 'curDateInput'" inset style="margin-top: 4vh">
                  <div class="cur-date-input-container">
                    <div class="cur-date-input-content">
                      <div class="cur-date-input-label">
                        {{ row.valueText || '当前时间' }}
                      </div>
                      <div class="cur-date-input-value">
                        {{ activatedConfig.data[row.dataIndex] || '未操作' }}
                      </div>
                    </div>
                    <div class="cur-date-input-action">
                      <van-button
                        v-if="!activatedConfig.data[row.dataIndex]"
                        size="small"
                        type="primary"
                        @click="activatedConfig.data[row.dataIndex] = getNow()"
                      >
                        {{ row.text || '设置时间' }}
                      </van-button>
                      <van-button
                        v-else
                        size="small"
                        type="default"
                        @click="activatedConfig.data[row.dataIndex] = getNow()"
                      >
                        {{ row.text || '重新设置' }}
                      </van-button>
                    </div>
                  </div>
                </van-cell-group>
                <!--     signature      -->
                <van-cell-group v-else-if="row.type === 'signature'" inset style="margin-top: 4vh">
                  <van-field
                    :label="row.valueText ? `${row.valueText}:` : ''"

                    rows="1"
                    autosize readonly
                  >
                    <template #button>
                      <XSignature v-model="activatedConfig.data[row.dataIndex]" />
                    </template>
                  </van-field>
                </van-cell-group>
                <!--     datePicker      -->
                <van-cell-group v-else-if="row.type === 'datePicker'" inset :title="row.label" :class="{ 'required-field': row.required }">
                  <DateTimeSecondsPicker
                    v-model="activatedConfig.data[row.dataIndex]"
                    :label="`${row.label || '日期'}:`"
                    placeholder="请选择日期"
                    title="选择日期"
                    format="YYYY-MM-DD"
                  />
                </van-cell-group>
                <!--     timePicker      -->
                <van-cell-group v-else-if="row.type === 'timePicker'" inset :title="row.label" :class="{ 'required-field': row.required }">
                  <DateTimeSecondsPicker
                    v-model="activatedConfig.data[row.dataIndex]"
                    :label="`${row.label || '时间'}:`"
                    placeholder="请选择时间"
                    title="选择时间"
                    format="YYYY-MM-DD HH:mm:ss"
                  />
                </van-cell-group>
                <!--     dateTimeSecondsPicker      -->
                <van-cell-group v-else-if="row.type === 'dateTimeSecondsPicker'" inset :title="row.label" :class="{ 'required-field': row.required }">
                  <DateTimeSecondsPicker
                    v-model="activatedConfig.data[row.dataIndex]"
                    :label="`${row.label || '完整时间'}:`"
                    placeholder="请选择完整时间"
                    title="选择完整时间"
                    format="YYYY-MM-DD HH:mm:ss"
                  />
                </van-cell-group>
                <!--     inputs      -->
                <van-cell-group v-else-if="row.type === 'inputs'" inset :title="row.label || ''" :class="{ 'required-field': row.required }">
                  <template v-if="row.inputReadOnly === true">
                    <template v-for="(item, _index) in formatInputs(row)" :key="_index">
                      <van-field
                        v-model="activatedConfig.data[row.dataIndex][_index]"
                        :label="`${item}:`"
                        :placeholder="`请输入${item}`"
                        clearable
                        type="textarea"
                        rows="1"
                        :disabled="true"
                        autosize
                      />
                    </template>
                  </template>
                  <template v-else>
                    <template v-for="(item, _index) in formatInputs(row)" :key="_index">
                      <van-field
                        v-model="activatedConfig.data[row.dataIndex][_index]"
                        :label="`${item}:`"
                        :placeholder="`请输入${item}`"
                        clearable
                        type="textarea"
                        rows="1"
                        autosize
                      />
                    </template>
                  </template>
                </van-cell-group>
                <!--     images      -->
                <van-cell-group v-else-if="row.type === 'images'" inset :title="row.label">
                  <template v-if="row.dataIndex.includes('@@@')">
                    <Uploader
                      upload-mode="oss"
                      :image-list="activatedConfig.tempData[row.dataIndex]"
                      :outer-index="row.dataIndex"
                      authority="admin"
                      @update-file-list="updateFile"
                    />
                  </template>
                  <template v-else>
                    <Uploader
                      upload-mode="oss"
                      :image-list="activatedConfig.data.images[row.dataIndex]"
                      :outer-index="row.dataIndex"
                      authority="admin"
                      @update-file-list="updateFile"
                    />
                  </template>
                </van-cell-group>
                <!--     动态行      -->
                <template v-else-if="row.type === 'inputColumns'">
                  <!--                <van-divider class="divider"> -->
                  <!--                  {{ row.label }} -->
                  <!--                </van-divider> -->
                  <van-cell-group inset :title="row.label" style="background-color: #eff2f5">
                    <van-cell-group v-for="(_item, _index) in activatedConfig.data[row.dataIndex]" :key="_index" inset class="my-cell-group" style="margin: 0 0 10px 0">
                      <div v-for="(def, defIndex) in row.definition" :key="defIndex">
                        <template v-if="def.type === 'curDateInput'">
                          <div class="cur-date-input-container">
                            <div class="cur-date-input-content">
                              <div class="cur-date-input-label">
                                {{ def.label }}
                              </div>
                              <div class="cur-date-input-value">
                                {{ activatedConfig.data[row.dataIndex][_index][def.dataIndex] || '未设置' }}
                              </div>
                            </div>
                            <div class="cur-date-input-action">
                              <van-button
                                v-if="!activatedConfig.data[row.dataIndex][_index][def.dataIndex]"
                                size="small"
                                type="primary"
                                @click="activatedConfig.data[row.dataIndex][_index][def.dataIndex] = getNow()"
                              >
                                {{ def.text || '设置时间' }}
                              </van-button>
                              <van-button
                                v-else
                                size="small"
                                type="default"
                                @click="activatedConfig.data[row.dataIndex][_index][def.dataIndex] = getNow()"
                              >
                                {{ def.text || '重新设置' }}
                              </van-button>
                            </div>
                          </div>
                        </template>
                        <van-field
                          v-else
                          v-model="activatedConfig.data[row.dataIndex][_index][def.dataIndex]"
                          :label="`${def.label}:`"
                          type="textarea"
                          rows="1"
                          autosize
                          :placeholder="`请输入${def.label}`"
                          clearable
                          :class="{ 'required-field': def.required }"
                        />
                      </div>
                    </van-cell-group>
                  </van-cell-group>

                  <!--                <div class="button_group"> -->
                  <!--                  <van-button class="input_columns_button" plain type="primary" @click="addInputColumns(row.dataIndex, row.definition)"> -->
                  <!--                    <van-icon name="plus" /> -->
                  <!--                  </van-button> -->
                  <!--                  <van-button class="input_columns_button" plain type="primary" @click="removeInputColumns(row.dataIndex)"> -->
                  <!--                    <van-icon name="minus" /> -->
                  <!--                  </van-button> -->
                  <!--                </div> -->
                </template>
                <!--        list        -->
                <template v-else-if="row.type === 'list'">
                  <template v-for="(listIndex) in row.content[0].listLength" :key="listIndex">
                    <div style="margin-top: 3vh; margin-bottom: 3vh">
                      <van-cell-group inset :title="row.label" style="background-color: #eff2f5">
                        <template v-for="(_cell, cellIndex) in row.content" :key="listIndex + cellIndex">
                          <template v-if="_cell.listType === 'input'">
                            <van-field
                              v-model="activatedConfig.data[_cell.dataIndex][listIndex]"
                              :label="_cell.valueText"
                              type="textarea"
                              autosize
                            />
                          </template>
                          <template v-else-if="_cell.listType === 'value'">
                            <van-field
                              :disabled="true"
                              :label="_cell.valueText"
                              type="textarea"
                              :placeholder="_cell.content[listIndex - 1]"
                              autosize
                            />
                          </template>
                        </template>
                      </van-cell-group>
                    </div>
                  </template>
                </template>
              </template>
            </van-form>
          </van-collapse-item>
        </van-collapse>
      </div>
      <!--  提交按钮  -->
      <div class="submit_button">
        <van-button round block type="primary" native-type="submit" @click="onSubmit">
          提交
        </van-button>
      </div>
    </template>
  </div>
  <!-- 骨架屏 -->
  <div v-else class="skeleton">
    <van-skeleton title :row="5" />
  </div>

  <!-- 已移除 VueHashCalendar，现在使用内置的 DateTimeSecondsPicker 组件 -->
</template>

<style scoped lang="less">
.main {
  padding-top: 4vh;
  width: 100vw;
  height: 100vh;
  background-color: #eff2f5;

  .title {
    padding-bottom: 2vh;
    color: rgb(50, 50, 51);
    text-align: center;
    margin: 0 0 3vh;
  }

  .text_box {
    margin-top: 2vh;
    margin-bottom: 2vh;
  }

  .main_text {
    padding-left: 16px;
    font-weight: 400;
    line-height: 1.6;
    margin: 0 0 40px;
    color: #969799;
    font-size: 14px;
  }

  .show_value_item {
    text-align: center;
    font-size: 1.2em;
  }

  .cell_group {
    //margin-top: 2vh;
    //margin-bottom: 2vh;
  }

  .form_item {
    margin-top: 2vh;
  }

  .button_group {
    text-align: center;
    margin-top: 3vh;
    margin-bottom: 3vh;
  }

  .button_group > :first-child {
    margin-right: 3vw;
  }

  .divider {
    color: #1989fa;
    border-color: #1989fa;
    padding: 0 16px;
  }

  .submit_button {
    background-color: #eff2f5;
    padding: 5vh;
  }
}

.skeleton {
  margin-top: 5vh;
}
.my-cell-group {
  margin: 0 0 10px 0;
}
:deep(.van-collapse-item__content) {
  background-color: #eff2f5;
  padding: 10px 0;
}
:deep(.van-cell-group__title) {
  padding-top: 10px;
  padding-bottom: 10px;
}
:deep(.van-field__label) {
  font-weight: 600;
}

// 必填字段星号样式 - 只对星号生效
:deep(.van-field__label) {
  // 将包含星号的文本进行特殊处理
  &[style*='color'] {
    color: #323233 !important;
  }
}

// 使用自定义类名来处理必填字段
.required-field :deep(.van-field__label) {
  color: #323233;

  &::before {
    content: '*';
    color: #ee0a24;
    margin-right: 2px;
  }
}
:deep(.van-uploader__wrapper) {
  padding: 10px;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between; /* 水平方向上左右分散对齐 */
  align-items: center; /* 垂直方向上上下中心对齐 */
}

// 自定义的当前日期输入框样式
.cur-date-input-container {
  padding: 16px;
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  background: white;
  border-radius: 8px;

  .cur-date-input-content {
    flex: 1;
    margin-right: 12px;
    min-width: 0; // 防止flex子元素撑破容器

    .cur-date-input-label {
      font-size: 14px;
      font-weight: 600;
      color: #323233;
      line-height: 1.4;
      margin-bottom: 4px;
      word-wrap: break-word;
      white-space: normal;
      display: -webkit-box;
      -webkit-line-clamp: 4; // 最多显示2行
      -webkit-box-orient: vertical;
      overflow: hidden;
    }

    .cur-date-input-value {
      font-size: 15px;
      font-weight: 600;
      color: #666;
      line-height: 1.3;
      word-wrap: break-word;
      white-space: normal;
    }
  }

  .cur-date-input-action {
    flex-shrink: 0;
    display: flex;
    align-items: center;
  }
}

// 动态行中的当前日期输入框样式调整
.my-cell-group .cur-date-input-container {
  padding: 12px;
  margin: 8px 0;

  .cur-date-input-content {
    margin-right: 8px;

    .cur-date-input-label {
      font-size: 13px;
      margin-bottom: 2px;
    }

    .cur-date-input-value {
      font-size: 12px;
    }
  }
}
</style>
