<template>
  <tr>
    <!--  预览页展示  -->
    <template v-if="display">
      <template v-if="!inputColumns">
        <td
          v-for="(cell, cellIndex) in columns"
          v-if="!cell.dontShowRow"
          :key="cellIndex"
          :class=" calcTDBorder(cell.noBoarder) "
          :style="determineCellStyle(cell)"
          :colspan="cell.colSpan ? cell.colSpan : undefined">
          <template v-if="cell.type === 'column'">
            <template v-if="cell.customFunction">
              {{ deserializeFunctionAndRun(cell.customFunction, configData[cell.dataIndex], config) }}
            </template>
            <template v-else>
              {{ cell.text }}
            </template>
          </template>
          <!--       占位             -->
          <template v-else-if="cell.type === 'placeHolderColumn'">
          </template>
          <template v-else-if="cell.type === 'value'">
            <template v-if="cell.customFunction === undefined">
              {{ cell.value }}
            </template>
            <template v-else>
              {{ deserializeFunctionAndRun(cell.customFunction, cell.value, config) }}
            </template>
          </template>
          <template v-else-if="cell.type === 'input'">
            <template v-if="cell.customFunction === undefined">
              {{ getDeepObject(configData, cell.dataIndex) }}
            </template>
            <template v-else>
              {{ deserializeFunctionAndRun(cell.customFunction, configData[cell.dataIndex], config) }}
            </template>
          </template>
          <template v-else-if="cell.type === 'datePicker'">
            <template v-if="cell.customFunction === undefined">
              {{ getDeepObject(configData, cell.dataIndex) }}
            </template>
            <template v-else>
              {{ deserializeFunctionAndRun(cell.customFunction, configData[cell.dataIndex], config) }}
            </template>
          </template>
          <template v-else-if="cell.type === 'timePicker'">
            <template v-if="cell.customFunction === undefined">
              {{ getDeepObject(configData, cell.dataIndex) }}
            </template>
            <template v-else>
              {{ deserializeFunctionAndRun(cell.customFunction, configData[cell.dataIndex], config) }}
            </template>
          </template>
          <template v-else-if="cell.type === 'inputs'">
            <template v-if="cell.customFunction === undefined">
              {{ showSubRowValue(cell) }}
            </template>
            <template v-else>
              {{ deserializeFunctionAndRun(cell.customFunction, showSubRowValue(cell), config) }}
            </template>
          </template>
          <template v-else-if="cell.type === 'list'">
            <template v-if="listIndex === 0">
              <span style="font-weight: bold">{{ cell.listHead }}</span>
            </template>
            <template v-else-if="cell.listType === 'input'">
              {{ getDeepObject(configData, cell.dataIndex)[listIndex] }}
            </template>
            <template v-else-if="cell.listType === 'value'">
              {{ cell.content[listIndex] }}
            </template>
            <template v-else-if="cell.listType === 'variable'">
              {{ configData[cell.dataIndex][listIndex - 1][cell.listDataIndex] }}
            </template>
          </template>
          <template v-else-if="cell.type === 'images'">
            <template v-if="getDeepObject(configData.images, cell.dataIndex) === undefined || getDeepObject(configData.images, cell.dataIndex).length === 0">
              <template v-if="getDeepObject(configData, cell.dataIndex) === undefined || getDeepObject(configData, cell.dataIndex).length === 0">
                <span>无</span>
              </template>
              <template v-else>
                <template v-if="typeof getDeepObject(configData, cell.dataIndex) === 'object'">
                  <div style="display: flex; align-items: end; justify-content: space-evenly; flex-wrap: wrap">
                    <template v-for="(img,imgIndex) in getDeepObject(configData, cell.dataIndex)">
                      <template v-if="showImgInCell">
                        <div :key="imgIndex">
                          <img :src="img.url" alt="图片"/>
                          <p>{{ img.name }}</p>
                        </div>
                      </template>
                      <template v-else>
                        <span :key="imgIndex" style="margin-right: 5%">{{ img.name }}</span>
                      </template>
                    </template>
                  </div>
                </template>
                <template v-else>
                  <img :src="getDeepObject(configData, cell.dataIndex)" alt="图片"/>
                  <p style="margin-right: 5%">{{ formatImgStr(getDeepObject(configData, cell.dataIndex))[0].name }}</p>
                </template>
              </template>
            </template>
            <template v-else v-for="(img,imgIndex) in getDeepObject(configData.images, cell.dataIndex)">
              <span :key="imgIndex" style="margin-right: 5%">{{ img.name }}</span>
            </template>
          </template>
        </td>
      </template>
      <template v-else>
        <td
          v-for="(cell, cellIndex) in columns"
          :key="cellIndex"
          :class=" calcTDBorder(cell.noBoarder) "
          :colspan="cell.colSpan ? cell.colSpan : undefined"
          :style="determineCellStyle(cell)"
          :rowspan="cell.rowSpan ? cell.rowSpan : undefined">
          <template v-if="cell.type === 'column'">
            {{ cell.text }}
          </template>
          <template v-else-if="cell.type === 'value'">
            <template v-if="cell.customFunction === undefined">
              {{ cell.value }}
            </template>
            <template v-else>
              {{ deserializeFunctionAndRun(cell.customFunction, cell.value, config) }}
            </template>
          </template>
          <template v-else-if="cell.type === 'increment'">
            <template v-if="cell.customFunction === undefined">
              {{ getDeepObject(configData.arr[inputColumnsDefinitionIndex], cell.dataIndex) }}
            </template>
            <template v-else>
              {{
                deserializeFunctionAndRun(cell.customFunction, configData.arr[inputColumnsDefinitionIndex][cell.dataIndex], config)
              }}
            </template>
          </template>
          <template v-else-if="cell.type === 'input'">
            <template v-if="cell.customFunction === undefined">
              {{ getDeepObject(configData.arr[inputColumnsDefinitionIndex], cell.dataIndex) }}
            </template>
            <template v-else>
              {{
                deserializeFunctionAndRun(cell.customFunction, configData.arr[inputColumnsDefinitionIndex][cell.dataIndex], config)
              }}
            </template>
          </template>
          <template v-else-if="cell.type === 'datePicker'">
            <template v-if="cell.customFunction === undefined">
              {{ getDeepObject(configData.arr[inputColumnsDefinitionIndex], cell.dataIndex) }}
            </template>
            <template v-else>
              {{
                deserializeFunctionAndRun(cell.customFunction, configData.arr[inputColumnsDefinitionIndex][cell.dataIndex], config)
              }}
            </template>
          </template>
          <template v-else-if="cell.type === 'timePicker'">
            <template v-if="cell.customFunction === undefined">
              {{ getDeepObject(configData.arr[inputColumnsDefinitionIndex], cell.dataIndex) }}
            </template>
            <template v-else>
              {{
                deserializeFunctionAndRun(cell.customFunction, configData.arr[inputColumnsDefinitionIndex][cell.dataIndex], config)
              }}
            </template>
          </template>
          <template v-else-if="cell.type === 'inputs'">
            <template v-if="cell.customFunction === undefined">
              {{ getDeepObject(configData.arr[inputColumnsDefinitionIndex], cell.dataIndex) }}
            </template>
            <template v-else>
              {{
                deserializeFunctionAndRun(cell.customFunction, configData.arr[inputColumnsDefinitionIndex][cell.dataIndex], config)
              }}
            </template>
          </template>
        </td>
      </template>
    </template>
    <!--  不是动态行  -->
    <template v-else-if="!inputColumns">
      <td
        v-for="(cell, cellIndex) in columns"
        :key="cellIndex"
        :class=" calcTDBorder(cell.noBoarder) "
        :colspan="cell.colSpan ? cell.colSpan : undefined"
        :style="determineCellStyle(cell)"
        :rowspan="cell.rowSpan ? cell.rowSpan : undefined">
        <template v-if="cell.type === 'column'">
          <template v-if="cell.customFunction">
            {{ deserializeFunctionAndRun(cell.customFunction, configData[cell.dataIndex], config) }}
          </template>
          <template v-else>
            {{ cell.text }}
          </template>
        </template>
        <template v-else-if="cell.type === 'placeHolderColumn'">
          <!--       占位             -->
        </template>
        <template v-else-if="cell.type === 'value'">
          {{ cell.value }}
        </template>
        <template v-else-if="cell.type === 'curDateInput'">
          <a-button type="dashed" v-if="configData[cell.dataIndex]">
            {{ configData[cell.dataIndex] }}
          </a-button>
          <a-button
            v-if="!configData[cell.dataIndex]"
            type="primary"
            @click="getNowDate(cell.dataIndex)"
          >{{ cell.text || '确认' }}
          </a-button>
        </template>
        <template v-else-if="cell.type === 'datePicker'">
          <div>
            <a-date-picker
              @change="handleDatePickerChange($event, cell.dataIndex, cell)"
              :value="formatDateValue(configData[cell.dataIndex])"
              format="YYYY-MM-DD"
              :style="'width:' + (cell.inputWidth ? cell.inputWidth : '100') + '%'"
              :disabled="cell.inputReadOnly===true"
              :class="{'required-field-error': isFieldRequired(cell) && !configData[cell.dataIndex]}"/>
            <div v-if="isFieldRequired(cell) && !configData[cell.dataIndex]" class="required-message">
              {{ getRequiredMessage(cell, 'datePicker') }}
            </div>
          </div>
        </template>
        <template v-else-if="cell.type === 'timePicker'">
          <div>
            <a-date-picker
              @change="handleTimePickerChange($event, cell.dataIndex, cell)"
              :value="formatDateValue(configData[cell.dataIndex])"
              format="YYYY-MM-DD HH:mm:ss"
              show-time
              :style="'width:' + (cell.inputWidth ? cell.inputWidth : '100') + '%'"
              :disabled="cell.inputReadOnly===true"
              :class="{'required-field-error': isFieldRequired(cell) && !configData[cell.dataIndex]}"/>
            <div v-if="isFieldRequired(cell) && !configData[cell.dataIndex]" class="required-message">
              {{ getRequiredMessage(cell, 'timePicker') }}
            </div>
          </div>
        </template>
        <template v-else-if="cell.type === 'signature'">
          <img :src="configData[cell.dataIndex]" alt="签名加载失败" style="max-height: 2rem">
          <a-button v-if="!configData[cell.dataIndex]" type="dashed" >需要在手机端签名 </a-button>
        </template>
        <template v-else-if="cell.type === 'input'">
          <div>
            <template v-if="cell.dataIndex.indexOf('@@@') !== -1">
              <a-input
                @change="handleInputDeepChange($event, cell.dataIndex, cell)"
                v-model="config.tempData[cell.dataIndex]"
                :style="'width:' + (cell.inputWidth ? cell.inputWidth : '100') + '%'"
                :disabled="cell.inputReadOnly === true"
                :class="{'required-field-error': isFieldRequired(cell) && !config.tempData[cell.dataIndex]}"/>
            </template>
            <template v-else>
              <a-input
                @change="handleInputChange($event, cell.dataIndex, cell)"
                v-model="configData[cell.dataIndex]"
                :style="'width:' + (cell.inputWidth ? cell.inputWidth : '100') + '%'"
                :disabled="cell.inputReadOnly === true"
                :class="{'required-field-error': isFieldRequired(cell) && !configData[cell.dataIndex]}"/>
            </template>
            <div v-if="isFieldRequired(cell) && !getInputValue(cell)" class="required-message">
              {{ getRequiredMessage(cell, 'input') }}
            </div>
          </div>
        </template>
        <template v-else-if="cell.type === 'inputs'">
          <template v-if="cell.inputReadOnly === true">
            <div class="inputsDiv">
              <div class="inputsDivItem" v-for="(num, index) of calcFormatInputNum(cell.format)" :key="index">
                <span class="inputsDivItemLabel">{{ displayFormatStartText(cell.format) }}</span>
                <template v-if="cell.dataIndex.indexOf('@@@') !== -1">
                  <a-input
                    @change="handleInputDeepChange($event, cell.dataIndex, cell)"
                    v-model="config.tempData[cell.dataIndex][index]"
                    :style="'width:' + (cell.inputWidth ? cell.inputWidth : '100') + '%'"
                    :disabled="true"/>
                </template>
                <template v-else>
                  <a-input
                    v-model="configData[cell.dataIndex][index]"
                    :style="'width:' + (cell.inputWidth ? cell.inputWidth : '100') + '%'"
                    :disabled="true"/>
                </template>
                <span class="inputsDivItemLabel">{{ displayFormatText(cell.format, index) }}</span>
              </div>
            </div>
          </template>
          <template v-else>
            <div class="inputsDiv">
              <div class="inputsDivItem" v-for="(num, index) of calcFormatInputNum(cell.format)" :key="index">
                <span class="inputsDivItemLabel">{{ displayFormatStartText(cell.format) }}</span>
                <template v-if="cell.dataIndex.indexOf('@@@') !== -1">
                  <a-input
                    @change="handleInputDeepChange($event, cell.dataIndex, cell)"
                    v-model="config.tempData[cell.dataIndex][index]"
                    :style="'width:' + (cell.inputWidth ? cell.inputWidth : '100') + '%'"/>
                </template>
                <template v-else>
                  <a-input
                    v-model="configData[cell.dataIndex][index]"
                    :style="'width:' + (cell.inputWidth ? cell.inputWidth : '100') + '%'"/>
                </template>
                <span class="inputsDivItemLabel">{{ displayFormatText(cell.format, index) }}</span>
              </div>
            </div>
          </template>
        </template>
        <template v-else-if="cell.type === 'list'">
          <template v-if="listIndex === 0">
            <span style="font-weight: bold">{{ cell.listHead }}</span>
          </template>
          <template v-else-if="cell.listType === 'input'">
            <a-input
              v-model="configData[cell.dataIndex][listIndex]"
              :style="'width:' + (cell.inputWidth ? cell.inputWidth : '100') + '%'"/>
          </template>
          <template v-else-if="cell.listType === 'value'">
            {{ cell.content[listIndex] }}
          </template>
          <template v-else-if="cell.listType === 'variable'">
            {{ configData[cell.dataIndex][listIndex - 1][cell.listDataIndex] }}
          </template>
        </template>
        <template v-else-if="cell.type === 'images'">
          <div>
            <template v-if="configData.images[cell.dataIndex]?.length > 0">
              <upload
                :model="uploadParams"
                :img-prefix="imgPrefix"
                :service-name="serverName"
                :images="checkImg(cell.dataIndex, 'configData')"
                :outer-container-index="cell.dataIndex"
                @setFiles="(...args) => {setImages(args, 'configData')}"
                :upload-style="'simple'"
              />
            </template>
            <template v-else>
              <upload
                :model="uploadParams"
                :img-prefix="imgPrefix"
                :service-name="serverName"
                :images="checkImg(cell.dataIndex, 'config')"
                :outer-container-index="cell.dataIndex"
                @setFiles="(...args) => {setImages(args, 'config', cell.dataIndex)}"
                :upload-style="'simple'"
              />
            </template>
          </div>
        </template>
      </td>
    </template>
    <!--  动态行插入按钮  -->
    <template v-else-if="inputColumnsButton">
      <td :colspan="maxColSpan" :class="calcTDBorder()">
        <a-button-group>
          <a-button @click="addData(columns[0].dataIndex, columns)">
            <a-icon type="plus"/>
          </a-button>
          <a-button @click="removeData(columns[0].dataIndex)">
            <a-icon type="minus"/>
          </a-button>
        </a-button-group>
      </td>
    </template>
    <!--  其他行  -->
    <template v-else>
      <td
        v-for="(cell, cellIndex) in columns"
        :key="cellIndex"
        :class=" calcTDBorder(cell.noBoarder) "
        :colspan="cell.colSpan ? cell.colSpan : undefined"
        :style="determineCellStyle(cell)"
        :rowspan="cell.rowSpan ? cell.rowSpan : undefined">
        <template v-if="cell.type === 'column'">
          {{ cell.text }}
        </template>
        <template v-else-if="cell.type === 'value'">
          {{ cell.value }}
        </template>
        <template v-else-if="cell.type === 'curDateInput'">
          <a-button type="dashed" v-if="configData.arr[inputColumnsDefinitionIndex][cell.dataIndex]">
            {{ configData.arr[inputColumnsDefinitionIndex][cell.dataIndex] }}
          </a-button>
          <a-button
            v-if="!configData.arr[inputColumnsDefinitionIndex][cell.dataIndex]"
            type="primary"
            @click="getNowDate(inputColumnsDefinitionIndex,cell.dataIndex)"
          >{{ cell.text || '确认' }}
          </a-button>
        </template>
        <template v-else-if="cell.type === 'datePicker'">
          <div>
            <a-date-picker
              @change="handleArrayDatePickerChange($event, inputColumnsDefinitionIndex, cell.dataIndex, cell)"
              :value="formatDateValue(configData.arr[inputColumnsDefinitionIndex][cell.dataIndex])"
              format="YYYY-MM-DD"
              :style="'width:' + (cell.inputWidth ? cell.inputWidth : '100') + '%'"
              :disabled="cell.inputReadOnly === true"
              :class="{'required-field-error': isFieldRequired(cell) && !configData.arr[inputColumnsDefinitionIndex][cell.dataIndex]}"/>
            <div v-if="isFieldRequired(cell) && !configData.arr[inputColumnsDefinitionIndex][cell.dataIndex]" class="required-message">
              {{ getRequiredMessage(cell, 'datePicker') }}
            </div>
          </div>
        </template>
        <template v-else-if="cell.type === 'timePicker'">
          <div>
            <a-date-picker
              @change="handleArrayTimePickerChange($event, inputColumnsDefinitionIndex, cell.dataIndex, cell)"
              :value="formatDateValue(configData.arr[inputColumnsDefinitionIndex][cell.dataIndex])"
              format="YYYY-MM-DD HH:mm:ss"
              show-time
              :style="'width:' + (cell.inputWidth ? cell.inputWidth : '100') + '%'"
              :disabled="cell.inputReadOnly === true"
              :class="{'required-field-error': isFieldRequired(cell) && !configData.arr[inputColumnsDefinitionIndex][cell.dataIndex]}"/>
            <div v-if="isFieldRequired(cell) && !configData.arr[inputColumnsDefinitionIndex][cell.dataIndex]" class="required-message">
              {{ getRequiredMessage(cell, 'timePicker') }}
            </div>
          </div>
        </template>
        <template v-else-if="cell.type === 'signature'">
          <img :src="configData[cell.dataIndex]" alt="签名加载失败" style="max-height: 2rem">
          <a-button v-if="!configData[cell.dataIndex]" type="dashed" >需要在手机端签名</a-button>
        </template>
        <template v-else-if="cell.type === 'increment'">
          {{ configData.arr[inputColumnsDefinitionIndex][cell.dataIndex] }}
        </template>
        <template v-else-if="cell.type === 'input'">
          <div>
            <a-input
              @change="handleArrayInputChange($event, inputColumnsDefinitionIndex, cell.dataIndex, cell)"
              v-model="configData.arr[inputColumnsDefinitionIndex][cell.dataIndex]"
              :style="'width:' + (cell.inputWidth ? cell.inputWidth : '100') + '%'"
              :disabled="cell.inputReadOnly === true"
              :class="{'required-field-error': isFieldRequired(cell) && !configData.arr[inputColumnsDefinitionIndex][cell.dataIndex]}"/>
            <div v-if="isFieldRequired(cell) && !configData.arr[inputColumnsDefinitionIndex][cell.dataIndex]" class="required-message">
              {{ getRequiredMessage(cell, 'input') }}
            </div>
          </div>
        </template>
        <template v-else-if="cell.type === 'inputs'">
          <template v-if="cell.inputReadOnly === true">
            <a-input
              v-model="configData.arr[inputColumnsDefinitionIndex][cell.dataIndex]"
              :style="'width:' + (cell.inputWidth ? cell.inputWidth : '100') + '%'"
              :disabled="true"/>
          </template>
          <template v-else>
            <a-input
              v-model="configData.arr[inputColumnsDefinitionIndex][cell.dataIndex]"
              :style="'width:' + (cell.inputWidth ? cell.inputWidth : '100') + '%'"/>
          </template>
        </template>
      </td>
    </template>
  </tr>
</template>

<script>
import Upload from '@vue2-client/base-client/components/common/Upload'
import { formatDate } from '@vue2-client/utils/util'
import { nanoid } from 'nanoid'
import moment from 'moment'

export default {
  name: 'XReportTrGroup',
  components: {
    Upload
  },
  props: {
    // 每一行的配置
    columns: {
      type: Array,
      required: true
    },
    showImgInCell: {
      type: Boolean,
      default: false
    },
    config: {
      type: Object,
      default: function () {
        return {}
      }
    },
    // 命名空间
    serverName: {
      type: String,
      default: process.env.VUE_APP_SYSTEM_NAME
    },
    // 原始配置
    configData: {
      type: Object,
      required: true
    },
    // 是否为动态行
    inputColumns: {
      type: Boolean,
      default: false
    },
    // 是否为动态行按钮
    inputColumnsButton: {
      type: Boolean,
      default: false
    },
    // 动态行的Index
    inputColumnsDefinitionIndex: {
      type: Number,
      default: undefined
    },
    // 是否为展示行
    display: {
      type: Boolean,
      default: false
    },
    // list类型的下标，用于遍历列表时，获取对应的数据
    listIndex: {
      type: Number,
      default: undefined
    },
    // 表格没有上边框
    noTopBorder: {
      type: Boolean,
      default: false
    },
    // 图片是否使用OSS来保存
    useOssForImg: {
      type: Boolean,
      default: true
    },
    // 图片上传后添加前缀
    imgPrefix: {
      type: String,
      default: undefined
    }
  },
  data () {
    return {
      maxColSpan: 12,
      uploadParams: {
        type: 'image',
        accept: ['*'],
        resUploadStock: 1,
        pathKey: 'cs'
      }
      // tableConfig: {}
    }
  },
  methods: {
    updateImg (data) {
      this.$emit('updateImg', data)
    },
    formatImgStr (str) {
      const result = []
      if (str !== '') {
        const arr = str.split('/')
        result.push({
          uid: nanoid(6),
          url: str,
          name: arr[arr.length - 1],
          status: 'done'
        })
      }
      this.uploadParams.acceptCount = 1
      return result
    },
    checkImg (index, type) {
      let target
      if (type === 'configData') {
        target = this.configData.images[index]
      } else {
        target = this.config.tempData[index]
      }
      if (typeof target !== 'object') {
        return this.formatImgStr(target)
      }
      target.forEach(obj => {
        if (obj.uid === undefined) {
          obj.uid = obj.id.toString()
        }
        if (obj.url === undefined) {
          if (obj.path) {
            obj.url = obj.path
          }
        }
        if (obj.name === undefined) {
          const withOutEndFix = obj.url.split('.')[0]
          const temp = withOutEndFix.split('/')
          obj.name = temp[temp.length - 1]
        }
        if (obj.status === undefined) {
          obj.status = 'done'
        }
      })
      return target
    },
    // 判断单元格样式
    determineCellStyle (cell, color = '#000', borderWidth = '1px') {
      // 如果声明了borderColor
      if (this.config.style.borderColor) {
        color = this.config.style.borderColor
      }
      // 如果声明了borderWidth
      if (this.config.style.borderWidth) {
        borderWidth = this.config.style.borderWidth
      }
      // 普通带边框单元格
      const withBorder = {
        border: borderWidth + ' solid ' + color,
        padding: '8px'
      }
      // 只有左右边框的单元格
      const noBorder = {
        borderLeft: borderWidth + ' solid ' + color,
        borderRight: borderWidth + ' solid ' + color,
        padding: '8px'
      }
      // 只没有上边框的单元格
      const NoTopBorder = {
        borderTopStyle: 'none',
        borderLeft: borderWidth + ' solid ' + color,
        borderRight: borderWidth + ' solid ' + color,
        borderBottom: borderWidth + ' solid ' + color,
        padding: '8px'
      }
      let result = {}
      // 如果表格也声明了样式，用表格样式将样式覆盖
      if (cell.style) {
        if (cell.noBorder) {
          result = { ...noBorder, ...cell.style }
        } else {
          if (this.noTopBorder) {
            result = { ...NoTopBorder, ...cell.style }
          } else {
            result = { ...withBorder, ...cell.style }
          }
        }
        return result
      }
      // 如果表头声明了样式，则用其将基础样式覆盖
      if (cell.type === 'column') {
        if (this.config.labelStyle !== undefined) {
          if (cell.noBorder) {
            result = { ...noBorder, ...this.config.labelStyle }
          } else {
            if (this.noTopBorder) {
              result = { ...NoTopBorder, ...this.config.labelStyle }
            } else {
              result = { ...withBorder, ...this.config.labelStyle }
            }
          }
          return result
        }
      }
      if (cell.noBorder) {
        result = { ...noBorder }
      } else {
        if (this.noTopBorder) {
          result = { ...NoTopBorder }
        } else {
          result = { ...withBorder }
        }
      }
      return result
    },
    // 表格中数据key含有@@@，需要手动触发更新
    handleInputDeepChange (event, dataIndex, cell = null) {
      // 如果字段必填且有值，触发重新渲染以移除错误样式
      if (cell && this.isFieldRequired(cell) && event.target.value) {
        this.$forceUpdate()
      }
      this.$forceUpdate()
    },
    // 处理普通input变化
    handleInputChange (event, dataIndex, cell = null) {
      // 如果字段必填且有值，触发重新渲染以移除错误样式
      if (cell && this.isFieldRequired(cell) && event.target.value) {
        this.$forceUpdate()
      }
    },
    // 处理动态行中input变化
    handleArrayInputChange (event, arrayIndex, dataIndex, cell = null) {
      // 如果字段必填且有值，触发重新渲染以移除错误样式
      if (cell && this.isFieldRequired(cell) && event.target.value) {
        this.$forceUpdate()
      }
    },
    // 获取input的值，用于必填校验
    getInputValue (cell) {
      if (cell.dataIndex.indexOf('@@@') !== -1) {
        return this.config.tempData[cell.dataIndex]
      } else {
        return this.configData[cell.dataIndex]
      }
    },
    // 路径中含有@@@的key，将其解析，并返回其数据
    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 (e) {
        result = undefined
      }
      return result
    },
    // 获取当前日期
    getNowDate (index1, index2) {
      if (index2) {
        // @click="getNowDate(configData.arr[inputColumnsDefinitionIndex][cell.dataIndex])"
        this.configData.arr[index1][index2] = formatDate('now')
      } else {
        this.configData[index1] = formatDate('now')
      }
      this.configData = Object.assign({}, this.configData)
    },
    // 通用的日期时间选择器变化处理方法
    handleDateTimePickerChange (date, dataIndex, format, arrayIndex = null, cell = null) {
      const dateStr = date ? moment(date).format(format) : ''

      if (arrayIndex !== null) {
        // 处理动态行中的日期时间选择器
        this.configData.arr[arrayIndex][dataIndex] = dateStr
      } else if (dataIndex.indexOf('@@@') !== -1) {
        // 处理深层嵌套的数据
        this.handleInputDeepChange({ target: { value: dateStr } }, dataIndex, cell)
      } else {
        // 处理普通的数据
        this.configData[dataIndex] = dateStr
      }

      // 如果字段必填且有值，触发重新渲染以移除错误样式
      if (cell && this.isFieldRequired(cell) && dateStr) {
        this.$forceUpdate()
      }

      this.configData = Object.assign({}, this.configData)
    },
    // 日期选择器变化处理（YYYY-MM-DD格式）
    handleDatePickerChange (date, dataIndex, cell = null) {
      this.handleDateTimePickerChange(date, dataIndex, 'YYYY-MM-DD', null, cell)
    },
    // 时间选择器变化处理（YYYY-MM-DD HH:mm:ss格式）
    handleTimePickerChange (date, dataIndex, cell = null) {
      this.handleDateTimePickerChange(date, dataIndex, 'YYYY-MM-DD HH:mm:ss', null, cell)
    },
    // 动态行中日期选择器变化处理
    handleArrayDatePickerChange (date, arrayIndex, dataIndex, cell = null) {
      this.handleDateTimePickerChange(date, dataIndex, 'YYYY-MM-DD', arrayIndex, cell)
    },
    // 动态行中时间选择器变化处理
    handleArrayTimePickerChange (date, arrayIndex, dataIndex, cell = null) {
      this.handleDateTimePickerChange(date, dataIndex, 'YYYY-MM-DD HH:mm:ss', arrayIndex, cell)
    },
    // 判断字段是否必填
    isFieldRequired (cell) {
      return cell && cell.required === true
    },
    // 获取必填字段的提示信息
    getRequiredMessage (cell, fieldType) {
      if (cell.requiredMessage) {
        return cell.requiredMessage
      }

      // 默认提示信息
      const defaultMessages = {
        datePicker: '请选择日期',
        timePicker: '请选择日期时间',
        input: '请填写此字段'
      }

      return defaultMessages[fieldType] || '此字段为必填项'
    },
    // 格式化日期值，用于日期选择器的value
    formatDateValue (dateStr) {
      if (!dateStr) return null
      const date = moment(dateStr)
      return date.isValid() ? date : null
    },
    // 反序列化函数并执行
    deserializeFunctionAndRun (functionStr, value) {
      // eslint-disable-next-line no-eval
      const fun = eval('(' + functionStr + ')')
      return fun(value, this.config)
    },
    // 基础上传组件，图片改动后触发
    setImages (args, type, index = undefined) {
      // 如果基础上传组件在初始化完成后，就调用emit了setImage，此时图片并没有变化，直接返回
      if (args[2] === 'created') {
        return
      }
      if (type === 'configData') {
        this.configData.images[args[1]] = args[0]
      } else {
        this.config.tempData[args[1]] = args[0]
        if (index) {
          this.$emit('updateImg', this.config.tempData[index])
        }
      }
    },
    // 动态行删除
    removeData (index) {
      if (this.configData[index].length === 0) {
        this.$message.warn('已经没有更多了')
        return
      }
      this.configData[index].pop()
    },
    // 添加一行
    addData (index, row) {
      // 获取定义
      const defs = row[0].definition

      // 获取外层对象名
      const dataName = row[0].dataIndex
      const temp = {}

      defs.forEach(def => {
        // 找到数组中最后一个数据的值
        let lastDataNo = 0
        if (this.configData[dataName][this.configData[dataName].length - 1]) {
          lastDataNo = this.configData[dataName][this.configData[dataName].length - 1][def.dataIndex]
        }

        // 如果没有值，检查是否声明了初始值
        if (lastDataNo === 0 && def.initialValue) {
          lastDataNo = def.initialValue
        }

        // 检查是否有步长
        let step = 1
        if (def.step) {
          step = def.step
        }

        // 如果单元格类型为increment，则进行自增
        if (def.type === 'increment') {
          temp[def.dataIndex] = lastDataNo + step
        }
      })
      this.configData[index].push(temp)
    },
    // 根据format计算需要多少个输入框
    calcFormatInputNum (formatStr) {
      let count = 0
      for (let i = 0; i < formatStr.length; i++) {
        if (formatStr[i] === '{') {
          count++
        }
      }
      return count
    },
    // 根据format计算输入框之后的文字显示
    displayFormatText (formatStr, num) {
      let start = 0
      let count = 0
      num++
      for (let i = 0; i < formatStr.length; i++) {
        if (formatStr[i] === '}') {
          start = i
          count++
        }
        if (count === num) {
          for (let j = start + 1; j < formatStr.length; j++) {
            if (formatStr[j] === '{') {
              return formatStr.slice(start + 1, j)
            }
            if (j === formatStr.length - 1 && formatStr[j] !== '}') {
              return formatStr[j]
            }
          }
        }
      }
    },
    calcTDBorder (cellNoBorder = false) {
      if (cellNoBorder) {
        return 'tdNoBorder'
      } else {
        if (this.noTopBorder) {
          return 'tdWithNoTopBorder'
        } else {
          return 'tdWithBorder'
        }
      }
    },
    // 根据format计算输入框之前的文字显示
    displayFormatStartText (formatStr) {
      let count = 0
      for (let i = 0; i < formatStr.length; i++) {
        if (formatStr[i] === '{') {
          break
        } else {
          count++
        }
      }
      return formatStr.slice(0, count)
    },
    // 拼接被自动拆分的单元格内容
    showSubRowValue (cell) {
      const dataName = cell.dataIndex
      const formatArr = []
      const dataArr = []

      // 从config中取出所有数据，根据dataIndex的开头内容进行拼接
      this.config.columns.forEach(row => row.forEach(cell => {
        if (cell.dataIndex && cell.dataIndex.startsWith(dataName)) {
          formatArr.push(cell.format)
          dataArr.push(this.configData[cell.dataIndex])
        }
      }))

      const text = []
      const data = []

      formatArr.forEach(word => {
        const temp = word.split('{}')
        temp.forEach(char => {
          if (char !== '') {
            text.push(char)
          }
        })
      })

      dataArr.forEach(item => {
        item.forEach(num => {
          data.push(num)
        })
      })

      let result = ''
      for (let i = 0; i < data.length; i++) {
        result += data[i]
        result += text[i]
      }

      return result
    },
  },
  beforeMount () {
    if (this.useOssForImg) {
      this.uploadParams.resUploadMode = 'oss'
    }
  }
}

</script>

<style scoped lang="less">
.inputsDiv {
  display: flex;
  justify-content: space-between;

  .inputsDivItem {
    display: flex;
    align-items: center;
    padding: 0 4px;
    white-space: nowrap;

    .inputsDivItemLabel {
      padding: 0 4px;
    }
  }
}

.tdNoBorder {
  border-left: 1px solid #000;
  border-right: 1px solid #000;
  padding: 8px;
}

.tdWithBorder {
  border: 1px solid #000;
  padding: 8px;
}

.tdWithNoTopBorder {
  border-top-style: none;
  border-left: 1px solid #000;
  border-right: 1px solid #000;
  border-bottom: 1px solid #000;
  padding: 8px;
}

.required-field-error {
  border-color: #ff4d4f !important;
  box-shadow: 0 0 0 2px rgba(255, 77, 79, 0.2) !important;
}

.required-message {
  color: #ff4d4f;
  font-size: 12px;
  margin-top: 4px;
  line-height: 1.2;
}
</style>
