<template>
  <div class="survey-dialog-container">
    <CostAuditDialog
      :title="dialogTitle"
      :visible="dialogVisible"
      :width="dialogWidth"
      :close-on-click-modal="false"
      :show-confirm-btn="false"
      cancel-text="关闭"
      append-to-body
      @cancel="handleCancel"
    >
      <div class="content-edit-container">
        <div class="table-header-info mb20">
          <div class="table-name">
            表名：{{ contentEditForm.surveyTemplateName }}
          </div>
          <div class="table-style">
            表单样式：
            <el-radio-group v-model="contentEditForm.templateType" disabled>
              <el-radio label="1">单记录</el-radio>
              <el-radio label="2">固定表</el-radio>
              <el-radio label="3">动态表</el-radio>
            </el-radio-group>
          </div>
        </div>

        <!-- 单记录列表 -->
        <div v-if="contentEditForm.templateType == '1'">
          <div class="table-edit-container">
            <el-table
              :data="contentEditForm.fixedTable.fixedTables"
              border
              style="width: 100%"
            >
              <!-- <el-table-column
                label="序号"
                width="100"
                align="center"
                prop="orderNum"
              ></el-table-column> -->
              <el-table-column
                v-for="(item, index) in contentEditForm.fixedTable
                  .fixedTablesTitle"
                :key="index"
                :label="item.rkey"
                align="center"
              >
                <!-- <template slot-scope="scope">
                  {{
                    scope.row.fixedValues
                      ? scope.row.fixedValues[item.rkey]
                      : ''
                  }}
                </template> -->
              </el-table-column>
            </el-table>
          </div>
        </div>
        <!-- 固定表时显示 -->
        <div v-if="contentEditForm.templateType == '2'">
          <div class="table-edit-container">
            <el-table
              :data="fixedTableDisplayData"
              border
              style="width: 100%"
              :row-class-name="getFixedPreviewRowClass"
            >
              <el-table-column label="序号" width="80" align="center">
                <template slot-scope="scope">
                  {{ scope.row._displaySeq || '-' }}
                </template>
              </el-table-column>
              <el-table-column label="项目" min-width="200" align="left">
                <template slot-scope="scope">
                  <span
                    :class="[
                      'table-item-text',
                      scope.row._isCategory ? 'category-name' : '',
                    ]"
                    :style="{ paddingLeft: `${scope.row._indentLevel * 20}px` }"
                  >
                    {{ scope.row._displayName || '-' }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column label="单位" width="100" align="center">
                <template slot-scope="scope">
                  <span v-if="!scope.row._isCategory">
                    {{ scope.row._displayUnit || '-' }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column
                v-for="column in fixedTableValueColumns"
                :key="column.key"
                :label="column.label"
                min-width="120"
                align="center"
              >
                <template slot-scope="scope">
                  <el-input
                    v-if="!scope.row._isCategory"
                    :value="scope.row._displayValues[column.key] || ''"
                    :placeholder="column.placeholder"
                    disabled
                  />
                </template>
              </el-table-column>
              <el-table-column label="备注" min-width="160" align="left">
                <template slot-scope="scope">
                  <!-- <span v-if="!scope.row._isCategory">
                    {{ scope.row._displayRemark || '-' }}
                  </span> -->
                  <el-input
                    v-if="!scope.row._isCategory"
                    :value="scope.row._displayRemark || ''"
                    placeholder="请输入备注"
                    disabled
                  />
                </template>
              </el-table-column>
              <!-- <el-table-column label="指标编号" width="120" align="center">
                <template slot-scope="scope">
                  <span v-if="!scope.row._isCategory">
                    {{ scope.row.cellCode || '-' }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column label="计算公式" min-width="150" align="left">
                <template slot-scope="scope">
                  <span v-if="!scope.row._isCategory">
                    {{ scope.row.calculationFormula || '-' }}
                  </span>
                </template>
              </el-table-column> -->
            </el-table>
          </div>
        </div>
        <!-- 动态表时显示 -->
        <div v-if="contentEditForm.templateType == '3'">
          <div class="table-edit-container">
            <el-table
              :data="contentEditForm.dynamicTable.dynamicTables"
              border
              style="width: 100%"
            >
              <el-table-column
                label="序号"
                width="100"
                align="center"
                prop="orderNum"
              >
                <template slot-scope="scope">
                  {{
                    scope.row.dynamicValues
                      ? scope.row.dynamicValues['序号']
                      : ''
                  }}
                </template>
              </el-table-column>
              <el-table-column
                v-for="(item, index) in contentEditForm.dynamicTable
                  .dynamicTableHeaders"
                :key="index"
                :label="item.rkey"
                align="center"
              >
                <template slot-scope="scope">
                  {{
                    scope.row.dynamicValues
                      ? scope.row.dynamicValues[item.rkey]
                      : ''
                  }}
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>
    </CostAuditDialog>
  </div>
</template>

<script>
  import CostAuditDialog from '@/components/costAudit/CostAuditDialog'
  import { listByCurrentTemplateId } from '@/api/catalogManage.js'
  export default {
    name: 'SurveyDialog',
    components: {
      CostAuditDialog,
    },
    props: {
      // 弹窗可见状态
      dialogVisible: {
        type: Boolean,
        default: false,
      },
      // 父组件传入的监审期间（字符串、数组或范围）
      auditPeriodFromParent: {
        type: [String, Array],
        default: '',
      },
      // 弹窗标题
      dialogTitle: {
        type: String,
        default: '查看',
      },
      // 弹窗宽度
      dialogWidth: {
        type: String,
        default: '70%',
      },
      // 表单数据
      formData: {
        type: Object,
        default: () => ({
          surveyTemplateName: '',
          templateType: '1',
          versionId: '',
          // 单记录列表
          tableHeaders: [],
          // 固定表列表
          fixedTable: {
            tableHeaders: [],
            fixedTables: [],
            fixedTablesTitle: [],
            fixedTableHeaders: [],
          },
          // 动态表列表
          dynamicTable: {
            tableHeaders: [],
            dynamicTables: [],
            dynamicTablesTitle: [],
            dynamicTableHeaders: [],
          },
          isDynamicTables: false,
          isFixedTables: false,
        }),
      },
      // 是否禁用编辑
      disabled: {
        type: Boolean,
        default: true,
      },
    },
    data() {
      return {
        contentEditForm: {
          surveyTemplateName: '',
          templateType: '1',
          versionId: '',
          // 单记录列表
          tableHeaders: [],
          // 固定表列表
          fixedTable: {
            tableHeaders: [],
            fixedTables: [],
            fixedTablesTitle: [],
            fixedTableHeaders: [],
          },
          // 动态表列表
          dynamicTable: {
            tableHeaders: [],
            dynamicTables: [],
            dynamicTablesTitle: [],
            dynamicTableHeaders: [],
          },
          isDynamicTables: false,
          isFixedTables: false,
        },
      }
    },
    computed: {
      auditPeriodYears() {
        const collectedYears = []
        const pushYear = (year) => {
          if (!year) return
          const str = String(year).trim()
          if (!str) return
          const matchList = str.match(/(19|20)\d{2}/g)
          if (matchList && matchList.length > 0) {
            matchList.forEach((match) => {
              if (!collectedYears.includes(match)) {
                collectedYears.push(match)
              }
            })
            return
          }
          if (/^\d{4}$/.test(str)) {
            if (!collectedYears.includes(str)) {
              collectedYears.push(str)
            }
          }
        }
        const parseMaybeString = (value) => {
          if (!value) return
          if (Array.isArray(value)) {
            value.forEach((item) => parseMaybeString(item))
            return
          }
          if (typeof value === 'object') {
            if (value.value !== undefined) {
              parseMaybeString(value.value)
            }
            if (value.label !== undefined) {
              parseMaybeString(value.label)
            }
            return
          }
          if (typeof value === 'number') {
            pushYear(value)
            return
          }
          if (typeof value === 'string') {
            if (value.includes(',')) {
              value
                .split(',')
                .map((item) => item.trim())
                .forEach((item) => parseMaybeString(item))
              return
            }
            if (value.includes('-')) {
              const parts = value.split('-')
              if (parts.length === 2) {
                const start = parseInt(parts[0].trim(), 10)
                const end = parseInt(parts[1].trim(), 10)
                if (!isNaN(start) && !isNaN(end) && start <= end) {
                  for (let year = start; year <= end; year++) {
                    pushYear(year)
                  }
                  return
                }
              }
            }
          }
          pushYear(value)
        }

        const form = this.contentEditForm || {}
        const data = form.data || {}
        const candidateSources = [
          this.auditPeriodFromParent,
          form.auditPeriod,
          form.auditPeriods,
          form.auditPeriodList,
          form.auditPeriodArray,
          form.auditPeriodStr,
          data.auditPeriod,
          data.auditPeriods,
          data.auditPeriodList,
          data.auditPeriodArray,
          data.auditPeriodStr,
          data.basicInfo && data.basicInfo.auditPeriod,
          data.basicInfo && data.basicInfo.auditPeriodArray,
          data.projectInfo && data.projectInfo.auditPeriod,
          data.project && data.project.auditPeriod,
        ]
        candidateSources.forEach((source) => parseMaybeString(source))

        if (collectedYears.length === 0) {
          const candidateLabels = this.fixedTableColumnCandidates
          candidateLabels
            .map((label) => {
              const match = String(label).match(/(19|20)\d{2}/)
              return match ? match[0] : null
            })
            .filter(Boolean)
            .forEach((year) => {
              if (!collectedYears.includes(year)) {
                collectedYears.push(year)
              }
            })
        }
        return collectedYears
      },
      fixedTableColumnCandidates() {
        const labels = new Set()
        const addLabel = (value) => {
          if (value === undefined || value === null) return
          const str = String(value).trim()
          if (!str) return
          labels.add(str)
        }
        const fixedTable =
          (this.contentEditForm && this.contentEditForm.fixedTable) || {}
        const potentialSources = [
          fixedTable.fixedTablesTitle,
          fixedTable.fixedTableHeaders,
          fixedTable.tableHeaders,
        ]
        potentialSources.forEach((source) => {
          if (!Array.isArray(source)) return
          source.forEach((item) => {
            if (item && typeof item === 'object') {
              addLabel(item.rkey || item.label || item.fieldName || item.name)
            } else {
              addLabel(item)
            }
          })
        })
        const rows = fixedTable.fixedTables
        if (Array.isArray(rows)) {
          rows.forEach((row) => {
            if (row && typeof row === 'object' && row.fixedValues) {
              Object.keys(row.fixedValues).forEach((key) => addLabel(key))
            }
          })
        }
        return Array.from(labels)
      },
      fixedTableValueColumns() {
        const auditYears = this.auditPeriodYears
        const candidateLabels = this.fixedTableColumnCandidates
        const usedLabels = new Set()
        const resultColumns = []
        const extractYear = (label) => {
          if (!label) return ''
          const match = String(label).match(/(19|20)\d{2}/)
          return match ? match[0] : ''
        }
        const buildColumn = ({ key, label, placeholder, candidates }) => ({
          key,
          label,
          placeholder,
          candidates,
        })

        auditYears.forEach((year) => {
          const matchLabel =
            candidateLabels.find((label) => {
              const normalized = extractYear(label)
              return normalized && normalized === String(year)
            }) || ''
          const displayLabel = matchLabel || `${year}年`
          const columnKey = `year-${year}`
          usedLabels.add(matchLabel)
          resultColumns.push(
            buildColumn({
              key: columnKey,
              label: displayLabel,
              placeholder: `请输入${displayLabel}数据`,
              candidates: [
                matchLabel,
                displayLabel,
                `${year}年`,
                `${year}年度`,
                `${year}`,
                `year_${year}`,
              ].filter(Boolean),
            })
          )
        })

        candidateLabels.forEach((label) => {
          if (!label || usedLabels.has(label)) {
            return
          }
          if (
            ['序号', '项目', '指标编号', '计算公式', '单位', '备注'].includes(
              label
            )
          ) {
            return
          }
          resultColumns.push(
            buildColumn({
              key: `col-${label}`,
              label,
              placeholder: `请输入${label}`,
              candidates: [label],
            })
          )
          usedLabels.add(label)
        })

        return resultColumns
      },
      fixedTableDisplayData() {
        const rows =
          (this.contentEditForm &&
            this.contentEditForm.fixedTable &&
            this.contentEditForm.fixedTable.fixedTables) ||
          []
        if (!Array.isArray(rows) || rows.length === 0) {
          return []
        }

        const normalizeId = (val) => {
          if (val === undefined || val === null) return ''
          return String(val)
        }

        const parentMap = {}
        rows.forEach((row, index) => {
          const rowId = normalizeId(row.rowid || row.itemId || index)
          const parentId = row.parentid
          if (
            parentId !== undefined &&
            parentId !== null &&
            parentId !== '' &&
            parentId !== '-1' &&
            parentId !== -1
          ) {
            parentMap[rowId] = normalizeId(parentId)
          } else {
            parentMap[rowId] = ''
          }
        })

        const childMap = {}
        Object.keys(parentMap).forEach((rowId) => {
          const parentId = parentMap[rowId]
          if (parentId) {
            if (!childMap[parentId]) {
              childMap[parentId] = []
            }
            childMap[parentId].push(rowId)
          }
        })

        const computedLevels = {}
        const getLevel = (rowId, depth = 0) => {
          if (!rowId) return 0
          if (computedLevels[rowId] !== undefined) {
            return computedLevels[rowId]
          }
          if (depth > rows.length) {
            return 0
          }
          const parentId = parentMap[rowId]
          if (!parentId) {
            computedLevels[rowId] = 0
            return 0
          }
          const level = 1 + getLevel(parentId, depth + 1)
          computedLevels[rowId] = level
          return level
        }

        const columnDefs = this.fixedTableValueColumns || []

        return rows.map((row, index) => {
          const rowId = normalizeId(row.rowid || row.itemId || index)
          const fixedValues = row.fixedValues || {}
          const displaySeq =
            fixedValues['序号'] ||
            row.orderText ||
            row.orderNum ||
            row.seq ||
            ''
          const displayName =
            fixedValues['项目'] ||
            fixedValues['项目名称'] ||
            row.itemName ||
            row.projectName ||
            ''
          const displayUnit = fixedValues['单位'] || row.unit || ''
          const displayRemark = fixedValues['备注'] || row.remark || ''
          const hasChildren = !!childMap[rowId]
          const isChild =
            row.isChild ||
            row.isSubItem ||
            (row.parentid !== undefined &&
              row.parentid !== null &&
              row.parentid !== '' &&
              row.parentid !== '-1' &&
              row.parentid !== -1)
          const isCategory =
            row.isCategory === true || (!isChild && hasChildren)

          const displayValues = {}
          columnDefs.forEach((column) => {
            let value = ''
            const candidates = column.candidates || []
            for (let i = 0; i < candidates.length; i += 1) {
              const candidate = candidates[i]
              if (!candidate) continue
              if (
                fixedValues[candidate] !== undefined &&
                fixedValues[candidate] !== null &&
                fixedValues[candidate] !== ''
              ) {
                value = fixedValues[candidate]
                break
              }
              if (
                row[candidate] !== undefined &&
                row[candidate] !== null &&
                row[candidate] !== ''
              ) {
                value = row[candidate]
                break
              }
              const altKey = String(candidate).replace(/年|年度/g, '')
              if (
                altKey &&
                fixedValues[altKey] !== undefined &&
                fixedValues[altKey] !== null &&
                fixedValues[altKey] !== ''
              ) {
                value = fixedValues[altKey]
                break
              }
            }
            displayValues[column.key] = value
          })

          const remarkValue =
            fixedValues['备注'] !== undefined && fixedValues['备注'] !== null
              ? fixedValues['备注']
              : displayRemark

          return {
            ...row,
            _rowId: rowId,
            _displaySeq: displaySeq,
            _displayName: displayName,
            _displayUnit: displayUnit,
            _displayRemark: remarkValue,
            _hasChildren: hasChildren,
            _isCategory: isCategory,
            _indentLevel: getLevel(rowId),
            _displayValues: displayValues,
          }
        })
      },
    },
    watch: {
      // 监听弹窗可见状态变化
      dialogVisible: {
        handler(newVal) {
          if (newVal) {
            this.initForm()
          }
        },
        immediate: true,
      },
      // 监听表单数据变化
      formData: {
        handler(newVal) {
          // 只有在弹窗未打开时预初始化一次数据，避免弹窗打开后多次重复请求
          if (Object.keys(newVal).length > 0 && !this.dialogVisible) {
            this.initForm()
          }
        },
        deep: true,
      },
    },
    methods: {
      // 初始化表单
      initForm() {
        if (Object.keys(this.formData).length > 0) {
          this.contentEditForm = { ...this.contentEditForm, ...this.formData }
          this.getData()
        }
      },
      getData() {
        listByCurrentTemplateId({
          surveyTemplateId: this.contentEditForm.data.surveyId,
        }).then((res) => {
          // 根据模板类型解析并显示数据
          // if (this.contentEditForm.templateType === '1') {
          //   if (res.value.fixedFields) {
          //     console.log(this.contentEditForm)
          //     this.contentEditForm.fixedTable.fixedTablesTitle =
          //       this.stringToObjects(res.value.fixedFields || '')
          //     this.contentEditForm.fixedTable.fixedTables = []
          //     console.log(this.contentEditForm.fixedTable.fixedTablesTitle)
          //   }
          // }
          if (
            this.contentEditForm.templateType === '1' ||
            this.contentEditForm.templateType === '2'
          ) {
            // 解析并显示固定表项目数据
            this.parseAndDisplayFixedTableData(res)
          } else if (this.contentEditForm.templateType === '3') {
            // 解析并显示动态表项目数据
            this.parseAndDisplayDynamicTableData(res)
          }
        })
      },
      /**
       * 解析并回显固定表、单记录项目数据
       * @param {Object} responseData - listByCurrentTemplateId接口返回的数据
       */
      parseAndDisplayFixedTableData(responseData) {
        if (responseData.value.fixedFields) {
          this.contentEditForm.fixedTable.fixedTablesTitle =
            this.stringToObjects(responseData.value.fixedFields || '')
        } else {
          let fixedFields = this.contentEditForm.fixedTable.tableHeaders
            .map((item) => item.fieldName)
            .join(',')
          this.contentEditForm.fixedTable.fixedTablesTitle =
            this.stringToObjects(fixedFields || '')
        }
        const fixedTitles = this.contentEditForm.fixedTable.fixedTablesTitle
        this.contentEditForm.fixedTable.fixedTableHeaders = fixedTitles.filter(
          (title) => title.rkey !== '序号'
        )
        if (
          !responseData ||
          !responseData.value ||
          !responseData.value.itemlist
        ) {
          return
        }

        const itemList = responseData.value.itemlist
        const allRows = []

        // 清空现有数据
        this.contentEditForm.fixedTable.fixedTables = []

        // 遍历itemList，为每个项目创建一行数据
        itemList.forEach((item, index) => {
          // 判断是否为子项（parentid不为-1且不为"-1"）
          const isSubItem =
            item.parentid && item.parentid !== -1 && item.parentid !== '-1'

          const newRow = {
            orderText: item.orderNum || '', // 显示用序号
            orderNum: item.orderNum || '', // 保留原始序号用于发送后端
            surveyTemplateId: item.surveyTemplateId,
            versionId: item.versionId,
            cellCode: item.cellCode || '',
            calculationFormula: item.calculationFormula || '',
            unit: item.unit || '',
            fixedValues: {},
            itemId: item.id || null,
            parentid: item.parentid || -1,
            isChild: isSubItem,
            isSubItem: isSubItem,
            rowid: item.rowid || this.generateUUID(),
            jsonstr: item.jsonstr || null,
          }

          // 确保orderNum是数字类型
          if (item.orderNum) {
            newRow.orderNum = parseInt(item.orderNum, 10) || 0
          }

          // 初始化fixedValues并填充实际值
          fixedTitles.forEach((title) => {
            newRow.fixedValues[title.rkey] = item[title.rkey] || ''
          })

          allRows.push(newRow)
        })

        // 按父子关系排序：父项在前，子项在对应的父项后面
        allRows.sort((a, b) => {
          // 先按orderNum排序父项
          if (a.isChild && !b.isChild) {
            // 如果a是子项，b是父项，需要检查a的父项是否在b之后
            const parentOfA = allRows.find(
              (item) => item.rowid === a.parentid || item.itemId === a.parentid
            )
            if (parentOfA && parentOfA.orderNum > b.orderNum) {
              return 1
            }
            return -1
          }
          if (!a.isChild && b.isChild) {
            // 如果a是父项，b是子项，需要检查b的父项是否在a之前
            const parentOfB = allRows.find(
              (item) => item.rowid === b.parentid || item.itemId === b.parentid
            )
            if (parentOfB && parentOfB.orderNum < a.orderNum) {
              return -1
            }
            return 1
          }

          // 如果都是父项或都是子项，按orderNum排序
          return (a.orderNum || 0) - (b.orderNum || 0)
        })

        // 重新排序，确保子项紧跟在其对应的父项后面
        const sortedArray = []
        const parentItems = allRows.filter((item) => !item.isChild)
        const childItems = allRows.filter((item) => item.isChild)

        parentItems.forEach((parent) => {
          sortedArray.push(parent)
          // 找到并添加该父项的所有子项
          const relatedChildren = childItems.filter(
            (child) =>
              child.parentid === parent.rowid ||
              child.parentid === parent.itemId
          )
          // 子项按orderNum排序
          relatedChildren.sort((a, b) => (a.orderNum || 0) - (b.orderNum || 0))
          sortedArray.push(...relatedChildren)
        })

        this.contentEditForm.fixedTable.fixedTables = sortedArray
      },
      getFixedPreviewRowClass({ row }) {
        if (!row) return ''
        return row._isCategory ? 'category-row' : ''
      },
      /**
       * 解析并回显动态表项目数据
       * @param {Object} responseData - listByCurrentTemplateId接口返回的数据
       */
      parseAndDisplayDynamicTableData(responseData) {
        // 确保数据初始化
        if (!this.contentEditForm.dynamicTable) {
          this.contentEditForm.dynamicTable = {
            tableHeaders: [],
            dynamicTables: [],
            dynamicTablesTitle: [],
            dynamicTableHeaders: [],
          }
        }

        // 使用API返回的字段配置（如果有）
        if (responseData.value.fixedFields) {
          this.contentEditForm.dynamicTable.dynamicTablesTitle =
            this.stringToObjects(responseData.value.fixedFields || '')
        } else if (
          this.contentEditForm.dynamicTable.tableHeaders &&
          this.contentEditForm.dynamicTable.tableHeaders.length > 0
        ) {
          let fixedFields = this.contentEditForm.dynamicTable.tableHeaders
            .map((item) => item.fieldName || '')
            .filter(Boolean)
            .join(',')
          if (fixedFields) {
            this.contentEditForm.dynamicTable.dynamicTablesTitle =
              this.stringToObjects(fixedFields || '')
          }
        }

        const dynamicTitles =
          this.contentEditForm.dynamicTable.dynamicTablesTitle
        this.contentEditForm.dynamicTable.dynamicTableHeaders =
          dynamicTitles.filter((title) => title.rkey !== '序号')
        if (
          !responseData ||
          !responseData.value ||
          !responseData.value.itemlist
        ) {
          return
        }

        const itemList = responseData.value.itemlist

        const allRows = []

        // 清空现有数据
        this.contentEditForm.dynamicTable.dynamicTables = []

        // 遍历itemList，为每个项目创建一行数据
        itemList.forEach((item, index) => {
          // 判断是否为子项（parentid不为-1且不为"-1"）
          const isSubItem =
            item.parentid && item.parentid !== -1 && item.parentid !== '-1'

          const newRow = {
            orderText: item.orderNum || '', // 显示用序号
            orderNum: item.orderNum || '', // 保留原始序号用于发送后端
            surveyTemplateId: item.surveyTemplateId,
            dynamicValues: {},
            itemId: item.id || null,
            parentid: item.parentid || -1,
            isChild: isSubItem,
            isSubItem: isSubItem,
            rowid: item.rowid || this.generateUUID(),
            jsonstr: item.jsonstr || null,
          }

          // 确保orderNum是数字类型
          if (item.orderNum) {
            newRow.orderNum = parseInt(item.orderNum, 10) || 0
          }

          // 初始化dynamicValues
          newRow.dynamicValues = {}
          dynamicTitles.forEach((title) => {
            // 特殊处理序号字段
            if (title.rkey === '序号') {
              // 优先使用item中的序号值，如果没有则使用orderNum或index+1
              newRow.dynamicValues[title.rkey] =
                item[title.rkey] || item.orderNum || index + 1
            }
            // 排除其他序号相关字段，避免重复显示
            else if (title.rkey !== 'ordernum' && title.rkey !== 'orderText') {
              newRow.dynamicValues[title.rkey] = item[title.rkey] || ''
            }
          })

          allRows.push(newRow)
        })

        // 按父子关系排序：父项在前，子项在对应的父项后面
        // 1. 先创建一个映射表，方便通过ID查找父项
        const rowMap = new Map()
        const sortedArray = []
        const addedItems = new Set()

        // 深拷贝原始数据并过滤掉重复项
        const uniqueRows = allRows.reduce((acc, current) => {
          const isDuplicate = acc.some(
            (row) =>
              (row.rowid && current.rowid && row.rowid === current.rowid) ||
              (row.itemId && current.itemId && row.itemId === current.itemId)
          )
          if (!isDuplicate) {
            acc.push(JSON.parse(JSON.stringify(current)))
          }
          return acc
        }, [])

        // 填充映射表
        uniqueRows.forEach((row) => {
          if (row.rowid) rowMap.set(String(row.rowid), row)
          if (row.itemId) rowMap.set(String(row.itemId), row)
        })

        // 先按orderNum排序所有父项
        const parentItems = uniqueRows.filter((item) => !item.isChild)
        parentItems.sort(
          (a, b) => (Number(a.orderNum) || 0) - (Number(b.orderNum) || 0)
        )

        // 递归添加父项及其子项的函数
        const addItemWithChildren = (item) => {
          // 确保项目ID唯一
          const itemIdKey = String(
            item.rowid || item.itemId || `temp_${Math.random()}`
          )

          // 如果已经添加过，则跳过
          if (addedItems.has(itemIdKey)) return

          // 添加当前项目
          sortedArray.push(item)
          addedItems.add(itemIdKey)

          // 找到并添加所有子项
          const children = uniqueRows.filter((child) => {
            if (child.isChild) {
              const childParentId = String(child.parentid)
              return (
                childParentId === String(item.rowid) ||
                childParentId === String(item.itemId)
              )
            }
            return false
          })

          // 子项按orderNum排序
          children.sort(
            (a, b) => (Number(a.orderNum) || 0) - (Number(b.orderNum) || 0)
          )

          // 添加所有子项
          children.forEach((child) => addItemWithChildren(child))
        }

        // 遍历所有父项，添加父项及其子项
        parentItems.forEach((parent) => addItemWithChildren(parent))

        // 添加剩余的没有被添加的项目（应该很少，但作为兜底）
        uniqueRows.forEach((row) => {
          const itemIdKey = String(
            row.rowid || row.itemId || `temp_${Math.random()}`
          )
          if (!addedItems.has(itemIdKey)) {
            sortedArray.push(row)
            addedItems.add(itemIdKey)
          }
        })

        // 最后，重新计算显示序号，确保序号连续且正确
        sortedArray.forEach((item, index) => {
          item.orderText = String(index + 1)
        })

        this.contentEditForm.dynamicTable.dynamicTables = sortedArray
      },
      // 字符串转对象数组
      stringToObjects(str) {
        if (!str || typeof str !== 'string') return []

        const result = str
          .split(',')
          .map((item) => {
            const trimmed = item.trim()
            return {
              rkey: trimmed,
              rvalue: trimmed,
            }
          })
          .filter((item) => item.rkey)

        return result
      },

      // 生成UUID用于临时行ID
      generateUUID() {
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(
          /[xy]/g,
          function (c) {
            const r = (Math.random() * 16) | 0
            const v = c === 'x' ? r : (r & 0x3) | 0x8
            return v.toString(16)
          }
        )
      },
      // 处理选择变化
      handleSelectionChange(val) {
        this.$emit('selection-change', val)
      },
      // 获取格式占位符
      getFormatPlaceholder(fieldType) {
        switch (fieldType) {
          case '布尔值':
            return '请选择布尔值'
          case '下拉选择':
            return '请选择选项'
          default:
            return '请输入格式'
        }
      },
      // 处理取消
      handleCancel() {
        this.$emit('cancel')
      },
    },
  }
</script>

<style scoped lang="scss">
  @import '@/styles/costAudit.scss';
  .survey-dialog-container {
    .content-edit-container {
      .table-header-info {
        display: flex;
        justify-content: space-between;
        margin-bottom: 20px;
        padding: 10px;
        background-color: #f5f7fa;
        border-radius: 4px;
        .table-name {
          font-weight: bold;
          color: #303133;
        }
        .table-style {
          .el-radio-group {
            margin-left: 10px;
          }
        }
      }
      .table-edit-container {
        margin-top: 20px;
        .format-input {
          display: flex;
          align-items: center;
          .format-prefix {
            margin-right: 5px;
            color: #606266;
          }
        }
        .bind-dict-column {
          display: flex;
          flex-direction: column;
          .dict-select {
            margin-left: 0 !important;
          }
        }
      }
      ::v-deep .category-row {
        background-color: #f5f7fa !important;
        td {
          background-color: #f5f7fa !important;
          font-weight: 600;
        }
        .category-name {
          color: #409eff;
          font-weight: 600;
        }
      }
      .table-item-text {
        display: inline-block;
        width: 100%;
        color: #303133;
      }
    }
  }
</style>
