<template>
  <splitpanes class="default-theme" :horizontal="false" @resized="storePaneSize">
    <pane :size="treeSize" :min-size="15" :max-size="40" v-if="xTreeConfigName">
      <x-tree-pro
        :config-name="xTreeConfigName"
        :env="env"
        @action="action"
        @btnFuncClick="treeBtnFuncClick"
        @treeOnChecked="treeOnChecked"
        ref="xtree"
      ></x-tree-pro>
    </pane>
    <pane :size="100 - treeSize">
      <a-skeleton :loading="loading" :paragraph="{ rows: 4 }" />
      <a-row style="height: 12px" v-if="xTreeConfigName"></a-row>
      <div v-show="!loading">
        <template v-if="!loadError">
          <x-add-form
            ref="xAddForm"
            @onLocalSubmit="onLocalSubmit"
            @x-form-item-emit-func="emitFunc"
            @afterSubmit="onAddOrEditSubmitAfterSubmit"
            @onSubmit="$listeners.addFormSubmit"
          >
            <template slot="groupFormItems" slot-scope="{ form, model, rules, modifyModelData }">
              <slot
                name="groupFormItems"
                :form="form"
                :model="model"
                :rules="rules"
                :modifyModelData="modifyModelData"
              ></slot>
            </template>
          </x-add-form>
          <x-add-report v-if="moveType" ref="xAddReport"></x-add-report>
          <div v-if="crudTitle" class="crud_title">
            {{ crudTitle }}
          </div>
          <a-spin :spinning="tableShowMode === 'popup' && formQueryLoading" tip="正在查询...">
            <x-form
              ref="xForm"
              @x-form-item-emit-func="emitFunc"
              @toggleAdvanced="toggleAdvanced"
              @onSubmit="onSearchSubmit"
            >
              <slot name="formBtnExpand"></slot>
            </x-form>
          </a-spin>
          <!-- 默认模式：直接展示表格 -->
          <x-table
            v-if="tableShowMode === 'default'"
            ref="xTable"
            :fixedQueryForm="fixedQueryForm"
            :queryParamsName="queryParamsName"
            :query-params-json="queryParamsJson"
            :show-pagination="showPagination"
            :customDelete="customDelete"
            :autoSave="autoSave"
            :extraHeight="extraHeight"
            :serviceName="serviceName"
            :defaultPageSize="defaultPageSize"
            :pageSizeArray="currentPageSizeArray || pageSizeArray"
            :pageMaxSize="realQueryConfig.queryPagesSize"
            :externalSelectedRowKeys="externalSelectedRowKeys"
            :customPagination="customPagination"
            :hiddenFunctionalArea="hiddenFunctionalArea"
            @x-form-item-emit-func="emitFunc"
            @add="add"
            @move="move"
            @edit="edit"
            @del="del"
            @rowChoose="rowChoose"
            @customEvent="customEvent"
            @afterDelete="afterDelete"
            @action="action"
            @selectRow="selectRow"
            @afterQuery="afterQuery"
            @columnClick="columnClick"
            @gotoUserDetail="gotoUserDetail"
            @editButtonStateDataClick="editButtonStateDataClick"
            @importExcelOk="importExcelOk"
            @rowClick="handleRowClick"
            @rowDblClick="handleRowDblClick"
            @beforeDataChange="beforeDataChange"
            @expand="onExpand"
            @progressUpdated="handleProgressUpdated"
          >
            <template slot="leftButton" slot-scope="{ selectedRowKeys, selectedRows }">
              <slot name="leftButton" :selectedRowKeys="selectedRowKeys" :selectedRows="selectedRows"></slot>
            </template>
            <template slot="button" slot-scope="{ selectedRowKeys, selectedRows }">
              <slot name="button" :selectedRowKeys="selectedRowKeys" :selectedRows="selectedRows"></slot>
            </template>
            <template slot="rightBtnExpand" slot-scope="{ selectedRowKeys, selectedRows }">
              <slot name="rightBtnExpand" :selectedRowKeys="selectedRowKeys" :selectedRows="selectedRows"></slot>
              <a-tooltip title="收起查询条件" placement="bottom">
                <a-button @click="toggleIsFormShow">
                  <a-icon :style="iconStyle" :type="toggleIsFormIcon" />
                </a-button>
              </a-tooltip>
            </template>
            <!-- 底部插槽 -->
            <template slot="footer" slot-scope="{ selectedRowKeys, selectedRows }">
              <slot name="footer" :selectedRowKeys="selectedRowKeys" :selectedRows="selectedRows"></slot>
            </template>
            <!--      excel导入说明插槽      -->
            <template #importExcelSlot>
              <slot name="importExcelSlot"></slot>
            </template>
          </x-table>
          <!-- 弹框模式：在 Modal 中展示表格 -->
          <a-modal
            v-if="tableShowMode === 'popup'"
            :visible="tableModalVisible"
            @cancel="closeTableModal"
            :title="realQueryConfig.popupTitle || null"
            :closable="false"
            width="80%"
            :bodyStyle="{ padding: '12px', minHeight: '50vh' }"
            :footer="null"
            :destroyOnClose="false"
            :forceRender="true"
            :z-index="1005"
          >
            <x-table
              ref="xTable"
              :fixedQueryForm="fixedQueryForm"
              :queryParamsName="queryParamsName"
              :query-params-json="queryParamsJson"
              :show-pagination="showPagination"
              :customDelete="customDelete"
              :autoSave="autoSave"
              :extraHeight="extraHeight"
              :serviceName="serviceName"
              :defaultPageSize="defaultPageSize"
              :pageSizeArray="currentPageSizeArray || pageSizeArray"
              :pageMaxSize="realQueryConfig.queryPagesSize"
              :externalSelectedRowKeys="externalSelectedRowKeys"
              :customPagination="customPagination"
              :hiddenFunctionalArea="hiddenFunctionalArea"
              @x-form-item-emit-func="emitFunc"
              @add="add"
              @move="move"
              @edit="edit"
              @del="del"
              @rowChoose="rowChoose"
              @customEvent="customEvent"
              @afterDelete="afterDelete"
              @action="action"
              @selectRow="selectRow"
              @afterQuery="afterQuery"
              @columnClick="columnClick"
              @gotoUserDetail="gotoUserDetail"
              @editButtonStateDataClick="editButtonStateDataClick"
              @importExcelOk="importExcelOk"
              @rowClick="handleRowClick"
              @rowDblClick="handleRowDblClick"
              @beforeDataChange="beforeDataChange"
              @expand="onExpand"
              @progressUpdated="handleProgressUpdated"
            >
              <template slot="leftButton" slot-scope="{ selectedRowKeys, selectedRows }">
                <slot name="leftButton" :selectedRowKeys="selectedRowKeys" :selectedRows="selectedRows"></slot>
              </template>
              <template slot="button" slot-scope="{ selectedRowKeys, selectedRows }">
                <slot name="button" :selectedRowKeys="selectedRowKeys" :selectedRows="selectedRows"></slot>
              </template>
              <template slot="rightBtnExpand" slot-scope="{ selectedRowKeys, selectedRows }">
                <slot name="rightBtnExpand" :selectedRowKeys="selectedRowKeys" :selectedRows="selectedRows"></slot>
                <a-tooltip title="关闭弹窗" placement="bottom">
                  <a-button @click="closeTableModal">
                    <a-icon :style="iconStyle" type="close" />
                  </a-button>
                </a-tooltip>
              </template>
              <!-- 底部插槽 -->
              <template slot="footer" slot-scope="{ selectedRowKeys, selectedRows }">
                <slot name="footer" :selectedRowKeys="selectedRowKeys" :selectedRows="selectedRows"></slot>
              </template>
              <!--      excel导入说明插槽      -->
              <template #importExcelSlot>
                <slot name="importExcelSlot"></slot>
              </template>
              <!-- 固定底部提示（与分页在同一行） -->
              <template slot="fixedfooter">
                <span v-if="realQueryConfig.popupFooterTip" class="popup-footer-tip">
                  {{ realQueryConfig.popupFooterTip }}
                </span>
              </template>
            </x-table>
          </a-modal>
        </template>
        <template v-else>
          <a-empty>
            <span slot="description">页面配置不存在，请联系系统管理员</span>
          </a-empty>
        </template>
      </div>
    </pane>
    <UserInfoDetailManage ref="userInfo" @close="refresh(false)" />
  </splitpanes>
</template>
<script>
import XForm from '@vue2-client/base-client/components/common/XForm'
import XAddForm from '@vue2-client/base-client/components/common/XAddForm'
import XAddReport from '@vue2-client/base-client/components/common/XAddReport'
import XTable from '@vue2-client/base-client/components/common/XTable'
import XTree from '@vue2-client/base-client/components/common/XTree'
import XImportExcel from '@vue2-client/base-client/components/common/XImportExcel'
import { Splitpanes, Pane } from 'splitpanes'
import 'splitpanes/dist/splitpanes.css'
import {
  getConfigByName,
  getConfigByLogic,
  parseConfig,
  runLogic,
  getConfigByNameAsync
} from '@vue2-client/services/api/common'
import { mapState } from 'vuex'
import XTreePro from '@vue2-client/base-client/components/common/XTree/XTreePro.vue'
import { executeStrFunctionByContext } from '@vue2-client/utils/runEvalFunction'
import { getRealKeyData } from '@vue2-client/utils/util'
import * as util from '@vue2-client/utils/util'
import UserInfoDetailManage from '@vue2-client/pages/userInfoDetailManage/index.vue'

export default {
  name: 'XFormTable',
  components: {
    UserInfoDetailManage,
    XTreePro,
    XTable,
    XForm,
    XTree,
    XAddForm,
    XAddReport,
    XImportExcel,
    Splitpanes,
    Pane
  },
  provide () {
    return {
      getSelf: () => this,
      emitEvent: this.emitEvent.bind(this)
    }
  },
  inject: {
    getSelectedId: {
      default: () => () => {
        console.warn('getSelectedId is not provided.')
        return null
      }
    },
    setGlobalData: {
      default: () => () => {
        console.warn('setGlobalData is not provided.')
        return null
      }
    },
    getGlobalData: {
      default: () => () => {
        console.warn('getGlobalData is not provided.')
        return null
      }
    },
    getSelectedData: {
      default: () => () => {
        console.warn('getSelectedData is not provided.')
        return null
      }
    },
    getMixinData: {
      default: () => () => {
        console.warn('getMixinData is not provided.')
        return {}
      }
    },
    getOutEnv: {
      default: () => () => {
        console.warn('getOutEnv is not provided.')
        return {}
      }
    },
    currUser: {
      default: () => {
        console.warn('currUser is not provided.')
        return { id: null, name: 'Guest' }
      }
    },

    /**
     * 祖先组件注入的自定义函数对象
     * 此对象包含祖先组件通过provide/inject机制注入的各种自定义函数
     * 子组件可以通过this.generalFunction来访问这些函数
     * 使用示例：
     * - this.generalFunction.handleCustomEvent(data)
     * - this.generalFunction.submitForm(formData)
     * - this.generalFunction.validateData(data)
     */
    generalFunction: {
      default: () => {
        console.warn('generalFunction is not provided.')
        return null
      }
    }
  },
  data () {
    return {
      // 加载状态
      loading: false,
      // 图标样式
      iconStyle: {
        position: 'relative',
        top: '1px'
      },
      loadError: false,
      moveType: false,
      // 添加按钮对应的配置名
      moveconfig: '',
      // 实际查询配置内容
      realQueryConfig: {},
      toggleIsFormIcon: 'vertical-align-top',
      table_selectedRowKeys: [],
      table_selectedRows: [],
      // 数据只有一页时是否展示分页，true：展示，auto：隐藏
      showPagination: true,
      isMounted: false,
      treeSize: localStorage.getItem('CURD::' + this.xTreeConfigName + '::TreeSize') ?? 25,
      // 表格展示模式：default 或 popup
      tableShowMode: 'default',
      // Modal 弹框显示状态
      tableModalVisible: false,
      // 弹框模式下表单查询中的加载状态
      formQueryLoading: false,
      currentPageSizeArray: null
    }
  },
  computed: {
    ...mapState('setting', ['isMobile'])
  },
  props: {
    // 业务名称
    title: {
      type: String,
      default: ''
    },
    // 外部传入的选中行keys
    externalSelectedRowKeys: {
      type: Array,
      default: () => []
    },
    // 卡片标题
    crudTitle: {
      type: String,
      default: null
    },
    // 查询配置文件名
    queryParamsName: {
      type: String,
      default: null
    },
    // 配置所属命名空间
    serviceName: {
      type: String,
      default: process.env.VUE_APP_SYSTEM_NAME
    },
    // 查询配置文件Json，用于查询配置生成器的预览
    queryParamsJson: {
      type: Object,
      default: null
    },
    // xTree 配置
    xTreeConfigName: {
      type: String,
      default: null
    },
    // 业务逻辑名称, 通过logic获取表单表格配置
    logicName: {
      type: String,
      default: null
    },
    // 执行logic传递的参数
    logicParam: {
      type: Object,
      default: () => {}
    },
    // 固定新增表单
    fixedAddForm: {
      type: Object,
      default: () => {
        return {}
      }
    },
    // 固定查询表单（隐藏条件，不显示在表单上）
    fixedQueryForm: {
      type: Object,
      default: () => {
        return {}
      }
    },
    // 默认查询表单（显示在表单上的默认值，用户可修改）
    defaultQueryForm: {
      type: Object,
      default: () => {
        return {}
      }
    },
    // 预览模式
    viewMode: {
      type: Boolean,
      default: () => {
        return false
      }
    },
    // 本地编辑模式
    localEditMode: {
      type: Boolean,
      default: () => {
        return false
      }
    },
    // 行编辑模式自动数据切换自动保存
    autoSave: {
      type: Boolean,
      default: () => {
        return false
      }
    },
    // 行选择模式
    rowSelectMode: {
      type: Boolean,
      default: () => {
        return false
      }
    },
    // 行选择模式-允许选中行数量，0：任意数量行，大于0：指定值数量的行
    allowSelectRowNum: {
      type: Number,
      default: () => {
        return 0
      }
    },
    // 弹框模式下，最少多少行数据才自动弹框展示
    minShowRows: {
      type: Number,
      default: 1
    },
    // 环境
    env: {
      type: String,
      default: () => {
        return 'prod'
      }
    },
    // 调用logic获取数据源的追加参数
    getDataParams: {
      type: Object,
      default: undefined
    },
    // 可以控制组件中导出等按钮的隐藏
    buttonState: {
      type: Object,
      default: undefined
    },
    // 是否自定义新增按钮的功能
    customAdd: {
      type: Boolean,
      default: false
    },
    reportQueryName: {
      type: String,
      default: undefined
    },
    // 是否自定义删除按钮的功能
    customDelete: {
      type: Boolean,
      default: false
    },
    // 是否自定义修改按钮的功能
    customEdit: {
      type: Boolean,
      default: false
    },
    // 是否自定义增加按钮
    customMove: {
      type: Boolean,
      default: false
    },
    // 自适应底部边距
    extraHeight: {
      type: Number,
      default: 80
    },
    // 是否禁用右侧操作行为
    disableAction: {
      type: Boolean,
      default: false
    },
    // 额外参数，用于控制组件行为
    extraParams: {
      type: Object,
      default: () => {
        return {}
      }
    },
    /**
     * 额外数据对象
     * 类型：Object
     * 默认值：返回一个空对象
     * 用途：用于传递组件需要的额外数据参数，此参数在点击导入时会将对象传入到自定义前后置插槽业务中
     */
    extraData: {
      type: Object,
      default: () => {
        return {}
      }
    },
    // 是否使用自定义分页样式
    customPagination: {
      type: Boolean,
      default: false
    },
    // 是否隐藏顶部功能区域
    hiddenFunctionalArea: {
      type: Boolean,
      default: false
    },
    // 默认查询的当页行数
    defaultPageSize: {
      type: Number,
      default: 10
    },
    // 分页配置
    pageSizeArray: {
      type: Array,
      default: () => ['10', '20', '30', '40']
    },
    // 是否为扩展按钮预留空间（减少 1 个可见表单项，避免 formBtnExpand 导致折行）
    reserveSpaceForButtons: {
      type: Boolean,
      default: false
    }
  },
  watch: {
    logicParam: {
      handler () {
        this.initConfig()
      },
      deep: true
    },
    queryParamsJson: {
      handler () {
        this.initConfig()
      },
      deep: true
    },
    queryParamsName: {
      handler () {
        this.initConfig()
      }
    },
    serviceName: {
      handler () {
        this.initConfig()
      }
    },
    extraData: {
      handler (newVal) {
        if (this.$refs.xTable) {
          this.$refs.xTable.updateExtraData(newVal)
        }
      },
      deep: true
    }
  },
  methods: {
    runLogic,
    getRealKeyData,
    getConfigByNameAsync,
    getConfigByName,
    storePaneSize (treeSize) {
      localStorage.setItem('CURD::' + this.xTreeConfigName + '::TreeSize', treeSize[0].size)
    },
    customEvent (func, data) {
      this.$emit(func, data)
    },
    columnClick (key, value, record) {
      this.$emit('columnClick', key, value, record)
    },
    gotoUserDetail (key, value, record) {
      this.$refs.userInfo.init(getRealKeyData(record))
    },
    // 获取主表的数据内容，去掉主表别名
    getPrimaryData (rows) {
      const alias = this.realQueryConfig.tableAliasName // 获取主表的别名
      const prefix = `${alias}_` // 构建前缀
      const result = []

      // 遍历 rows 的每一项，提取符合条件的数据
      rows.forEach(row => {
        const itemResult = {}
        Object.keys(row).forEach(key => {
          if (key.startsWith(prefix)) {
            const newKey = key.slice(prefix.length) // 去掉前缀
            itemResult[newKey] = row[key] // 添加到结果对象中
          }
        })
        result.push(itemResult) // 将处理后的项添加到结果数组中
      })

      return result // 返回去掉前缀后的对象数组
    },

    // 给数据区域添加主表数据，给的数据没有主表别名，放着时添加主表别名
    pushPrimaryData (rows) {
      const alias = this.realQueryConfig.tableAliasName // 获取主表的别名
      const prefix = `${alias}_` // 构建前缀
      const result = rows.map(row => {
        const itemResult = {}
        Object.keys(row).forEach(key => {
          itemResult[prefix + key] = row[key] // 复制原始数据
        })
        return itemResult // 返回添加了主表别名的数据
      })
      // 把结果添加到数据区
      this.getTableData().push(...result)
    },

    // 设置固定查询条件，主表别名自动带
    setFixedQueryForm (data) {
      const alias = this.realQueryConfig.tableAliasName // 获取主表的别名
      const prefixedData = {}

      // 为每个键添加主表别名
      Object.keys(data).forEach(key => {
        prefixedData[`${alias}_${key}`] = data[key]
      })

      Object.assign(this.fixedQueryForm, prefixedData)
    },

    // 固定条件（key 已包含表别名，不再处理）
    setFixedQueryFormWithAlias (data) {
      Object.assign(this.fixedQueryForm, data)
    },

    importExcelOk (data) {
      this.$emit('importExcelOk', data)
    },
    initConfig () {
      this._configEndEmitted = false
      this._configEndPromise = new Promise(resolve => { this._configEndResolve = resolve })
      this.loading = true
      this.loadError = false
      if (this.queryParamsName) {
        this.getConfig()
      } else if (this.queryParamsJson) {
        this.getConfigBySource()
      } else if (this.logicName && this.logicParam) {
        this.getColumnJsonByLogic()
      } else {
        this.loading = false
        this.loadError = true
        this._emitConfigEnd()
      }
    },

    getConfig () {
      getConfigByName(
        this.queryParamsName,
        this.serviceName,
        res => {
          if (!res) {
            this.loading = false
            this.loadError = true
            this._emitConfigEnd()
            return
          }
          this.updateComponents(res)
        },
        this.env === 'dev'
      )
    },
    getConfigBySource () {
      parseConfig(this.queryParamsJson, 'CRUD_FORM', this.serviceName, this.env === 'dev').then(res => {
        if (!res) {
          this.loading = false
          this.loadError = true
          this._emitConfigEnd()
          return
        }
        this.updateComponents(res, true)
      })
    },
    getColumnJsonByLogic () {
      getConfigByLogic(
        this.logicName,
        this.logicParam,
        this.serviceName,
        res => {
          if (!res) {
            this.loading = false
            this.loadError = true
            this._emitConfigEnd()
            return
          }
          this.updateComponents(res, true)
        },
        this.env === 'dev'
      )
    },

    /**
     * 更新子组件
     * @param res  参数
     * @param setQueryParams 是否设置queryParams参数
     */
    updateComponents (res, setQueryParams) {
      this.realQueryConfig = res
      // 读取表格展示模式配置
      this.tableShowMode = res.tableShowMode || 'default'
      if (this.realQueryConfig.expandPageSize) {
        const baseArray = this.pageSizeArray.slice()
        const extraSizes = ['100', '500', '1000']
        extraSizes.forEach(size => {
          if (!baseArray.includes(size)) {
            baseArray.push(size)
          }
        })
        baseArray.sort((a,b) => Number(a) - Number(b))
        this.currentPageSizeArray = baseArray
      } else {
        this.currentPageSizeArray = null
      }
      // 弹框模式下，xTable 可能还未渲染，需要特殊处理
      const hasRequiredRefs =
        this.tableShowMode === 'popup'
          ? this.$refs.xForm && this.$refs.xAddForm
          : this.$refs.xTable && this.$refs.xForm && this.$refs.xAddForm

      if (hasRequiredRefs) {
        // 设置添加按钮对应的配置名
        this.moveconfig = res.moveconfig
        this.showPagination = res.showPagination === null ? true : res.showPagination
        // 是否展示排序按钮控制
        if (res.showSortIcon !== null && !res.showSortIcon) {
          res.columnJson.forEach(item => {
            item.sorter = false
          })
        }
        const localEditMode = !this.localEditMode ? res.localEditMode : this.localEditMode
        const initTable = () => {
          // 初始化 xTable 子组件（弹框模式下由于 forceRender，xTable 已经渲染）
          if (this.$refs.xTable) {
            this.$refs.xTable.init({
              formItems: res.formJson,
              queryParams: setQueryParams ? res : null,
              realQueryParams: res,
              tableColumns: res.columnJson,
              buttonState: Object.assign(res.buttonState, this.buttonState),
              title: this.title || res.title,
              viewMode: this.viewMode,
              autoSave: this.autoSave,
              localEditMode: localEditMode,
              rowSelectMode: this.rowSelectMode,
              allowSelectRowNum: this.allowSelectRowNum,
              tableSummaryMap: res.tableSummaryMap,
              serviceName: this.serviceName,
              env: this.env,
              form: this.$refs.xForm.form,
              summaryUpdate: true,
              disableAction: this.disableAction,
              extraData: this.extraData,
              rowStyleFunction: res.rowStyleFunction,
              ...res
            })
            if (this.realQueryConfig?.funcData?.pageMounted) {
              executeStrFunctionByContext(this, this.realQueryConfig.funcData.pageMounted, [
                util,
                runLogic,
                getConfigByNameAsync
              ])
            }
            this.$emit('afterTableInit')
          }
        }
        // 初始化 xForm 子组件
        if (!localEditMode && !this.rowSelectMode) {
          this.$refs.xForm.init({
            queryParamsName: this.queryParamsName || 'localConfig',
            formItems: res.formJson,
            serviceName: this.serviceName,
            getDataParams: this.getDataParams,
            simpleMode: res.simpleMode,
            funcData: res.funcData,
            env: this.env,
            defaultQueryForm: this.defaultQueryForm,
            reserveSpaceForButtons: this.reserveSpaceForButtons
          })
        } else {
          // TODO 此处应删除
          initTable()
        }
        // 初始化 xTable 子组件
        // 等待 x-from-item 的 mounted 完成
        this.$refs.xForm.$on('itemsMounted', initTable)
      }
      this.loading = false
      this._emitConfigEnd()
    },
    /** 配置加载结束后发出，供 XReport 判断「所有 slot 配置结束」；仅发出一次 */
    _emitConfigEnd () {
      if (this._configEndEmitted) return
      this._configEndEmitted = true
      if (this._configEndResolve) {
        this._configEndResolve()
        this._configEndResolve = null
      }
      this.$emit('configEnd')
    },
    /**
     * 等待配置结束的异步方法。配置已结束则立即 resolve，否则在 configEnd 时 resolve。
     * @returns {Promise<void>}
     */
    waitConfigEnd () {
      if (this._configEndEmitted) return Promise.resolve()
      return this._configEndPromise || Promise.resolve()
    },
    // 自定义按钮
    editButtonStateDataClick (functionName, rows) {
      console.log('functionName', functionName)
      console.log('rows', rows)
      this.$emit(functionName, rows)
    },

    /**
     * 提交查询表单事件
     * @param res  参数
     */
    onSearchSubmit (res) {
      if (res.valid) {
        // 如果是弹框模式，显示表单加载动画，不立即打开弹框
        if (this.tableShowMode === 'popup') {
          // 开启表单查询加载状态
          this.formQueryLoading = true
        }
        // 默认模式：直接设置查询表单
        this.$refs.xTable.setQueryForm(res.form)
        this.$refs.xTable.summaryUpdate = true
        // commit
        this.$emit('afterSearchSubmit', res)
      } else {
        return false
      }
    },

    /**
     * 关闭表格弹框
     */
    closeTableModal () {
      this.tableModalVisible = false
    },

    active (props) {
      let num = false
      for (const key in props) {
        // eslint-disable-next-line no-prototype-builtins
        if (this.$props.hasOwnProperty(key)) {
          if (this.$props[key] instanceof Object) {
            this.$props[key] = JSON.parse(props[key])
          } else {
            this.$props[key] = props[key]
          }
          num = true
        }
      }
      if (num) {
        this.initConfig()
      }
    },
    /**
     * 提交新增/修改表单后事件
     */
    onAddOrEditSubmitAfterSubmit (res) {
      this.refreshTable(res.businessType === '新增')
      // commit
      this.$emit('afterSubmit', res)
    },
    /**
     * 表格查询后事件
     * @param res  参数（可能是 Promise）
     * @param conditionParams 查询条件
     */
    async afterQuery (res, conditionParams) {
      // 如果是弹框模式且正在查询中
      if (this.tableShowMode === 'popup' && this.formQueryLoading) {
        // 兼容 Promise
        const realRes = await res
        // 结束表单加载状态
        this.formQueryLoading = false
        // 兼容 data / records 两种结构
        const rows = realRes && (realRes.data || realRes.records || [])
        // 判断是否有数据（行数 >= minShowRows）
        const hasData = Array.isArray(rows) && rows.length >= this.minShowRows

        if (hasData) {
          // 有数据：打开弹框展示
          this.tableModalVisible = true
        }
      }

      // 继续触发父组件的 afterQuery 事件（保持原有行为）
      this.$emit('afterQuery', res, conditionParams)
    },
    /**
     * 详情按钮事件
     * @param record 本条数据
     * @param id 数据标识
     * @param actionType 操作类型
     * @param fun 向上级传递的事件
     */
    action (record, id, actionType, fun = 'action', index) {
      this.$emit('innerXFormTableEmit', fun, record, id, actionType, index, this)
      this.$emit(fun, record, id, actionType, index, this)
    },
    treeOnChecked (checkedKeys, deepNodes, deepKeys) {
      this.$emit('treeOnChecked', checkedKeys, deepNodes, deepKeys)
    },
    treeBtnFuncClick (index, func) {
      this.$emit('treeBtnFuncClick', index, func)
    },
    /**
     * 新增按钮事件
     */
    add () {
      if (this.customAdd) {
        this.$emit('add')
      } else {
        if (this.$listeners.curdAddBefore) {
          this.$emit('curdAddBefore', this.addFormInit)
        } else {
          this.addFormInit()
        }
      }
    },
    addFormInit () {
      const res = this.realQueryConfig
      const localEditMode = !this.localEditMode ? res.localEditMode : this.localEditMode
      this.$refs.xAddForm.init({
        businessType: '新增',
        title: this.title || res.title,
        isShow: !res.buttonState || res.buttonState.add || res.buttonState.edit,
        configName: this.queryParamsName,
        configContent: this.queryParamsJson,
        formItems: res.formJson,
        viewMode: this.viewMode,
        localEditMode: localEditMode,
        isKeyHandle: !Boolean(localEditMode),
        serviceName: this.serviceName,
        fixedAddForm: this.fixedAddForm,
        getDataParams: this.getDataParams,
        layout: res.xAddFormLayout || 'horizontal',
        xAddFormLayoutWidth: res.xAddFormLayoutWidth,
        formItemLayout: res.formItemLayout || {},
        env: this.env
      })
    },
    /**
     * 添加按钮事件
     */
    move () {
      this.moveType = true
      this.$nextTick(() => {
        this.$refs.xAddReport.init({
          configName: this.moveconfig,
          selectedId: this.fixedAddForm.selected_id
        })
      })
    },
    async crudEditBefore (modifyModelData) {
      return await new Promise((resolve) => {
        this.$emit('crudEditBefore', modifyModelData, resolve)
      })
    },
    /**
     * 修改按钮事件
     * @param modifyModelData 修改表单数据
     */
    async edit (modifyModelData) {
      if (this.customEdit) {
        this.$emit('edit')
      } else {
        if (this.$listeners.crudEditBefore) {
          const res = await this.crudEditBefore(modifyModelData)
          if (res === false) return
        }
        const res = this.realQueryConfig
        const localEditMode = !this.localEditMode ? res.localEditMode : this.localEditMode
        this.$refs.xAddForm.init({
          businessType: '修改',
          title: this.title || res.title,
          isShow: !res.buttonState || res.buttonState.add || res.buttonState.edit,
          configName: this.queryParamsName,
          configContent: this.queryParamsJson,
          formItems: res.formJson,
          viewMode: this.viewMode,
          localEditMode: localEditMode,
          isKeyHandle: !Boolean(localEditMode),
          serviceName: this.serviceName,
          fixedAddForm: this.fixedAddForm,
          getDataParams: this.getDataParams,
          modifyModelData: modifyModelData,
          layout: res.xAddFormLayout || 'horizontal',
          xAddFormLayoutWidth: res.xAddFormLayoutWidth,
          formItemLayout: res.formItemLayout || {},
          env: this.env
        })
      }
    },
    /**
     * 删除按钮事件
     */
    del (keys, callback) {
      if (this.customDelete) {
        this.$emit('del', keys, callback)
      }
    },
    /**
     * 删除后事件
     * @param res
     */
    afterDelete (res) {
      this.$emit('afterDelete', res)
    },
    /**
     * 行选择事件
     * @param row 选中行
     */
    rowChoose (row) {
      this.$emit('rowChoose', row)
    },
    /**
     * 本地编辑模式下校验表格并同步本地数据
     * @param currRow 当前行
     * @param defaultAppendRowData 默认追加的行数据
     */
    validateTableAndSyncData (currRow, defaultAppendRowData) {
      this.$refs.xTable.validateTableAndSyncData(currRow, defaultAppendRowData)
    },
    /**
     * 更多条件是否展示
     */
    toggleAdvanced () {
      // 只有在非弹出模式下才需要调整表格滚动高度
      if (this.tableShowMode !== 'popup') {
        this.$refs.xTable.setScrollYHeight({})
      }
    },
    /**
     * 查询表单部分显示/隐藏切换
     */
    toggleIsFormShow () {
      this.toggleIsFormIcon =
        this.toggleIsFormIcon === 'vertical-align-top' ? 'vertical-align-bottom' : 'vertical-align-top'
      this.$refs.xForm.toggleVisible()
      // 只有在非弹出模式下才需要调整表格滚动高度
      if (this.tableShowMode !== 'popup') {
        this.$refs.xTable.setScrollYHeight({})
      }
    },
    /**
     * 选择列事件
     * @param selectedRowKeys 选中列Key集合
     * @param selectedRows 选中列
     */
    selectRow (selectedRowKeys, selectedRows) {
      this.table_selectedRowKeys = selectedRowKeys
      this.table_selectedRows = selectedRows
      this.$emit('selectRow', selectedRowKeys, selectedRows)
    },
    /**
     * 清除勾选数据
     */
    clearRowKeys () {
      this.$refs.xTable.clearRowKeys()
    },
    /**
     * 刷新表格
     * @param toFirstPage 是否到第一页
     */
    refreshTable (toFirstPage = true) {
      if (this.tableShowMode === 'popup') {
        this.formQueryLoading = true
      }
      this.$refs.xTable.refresh(toFirstPage)
    },
    /**
     * 刷新表格
     * @param toFirstPage 是否到第一页
     */
    refresh (toFirstPage = true) {
      if (this.tableShowMode === 'popup') {
        this.formQueryLoading = true
      }
      this.$refs.xTable.refresh(toFirstPage)
    },
    /**
     * 主动传递条件查询表格
     */
    queryTable (conditionParams) {
      if (this.tableShowMode === 'popup') {
        this.formQueryLoading = true
      }
      // 调用 XForm 的 submitForm 方法
      // 这会触发 emit 'onSubmit'，然后走现有的 onSearchSubmit 逻辑
      // 最终通过 setQueryForm → refresh → loadData 进行数据处理
      this.$refs.xForm.submitForm(conditionParams)
    },
    /**
     * 向外暴露 resetForm 函数
     */
    resetForm () {
      this.$refs.xForm.resetForm()
    },
    /**
     * 获取表单字段的 labelData（用于导出/打印等场景）
     * @returns {Object} labelData 对象
     */
    getFormLabelData () {
      return this.$refs.xForm ? this.$refs.xForm.getFormLabelData() : {}
    },
    /**
     * 获取表格数据
     */
    getTableData () {
      return this.$refs.xTable.getTableData()
    },
    // 在行编辑等情况下，让界面生效
    update () {
      this.getTableData().push(...[])
    },

    /**
     * 设置表格数据
     */
    setTableData (data) {
      this.$refs.xTable.setTableData(data)
    },
    /**
     * 表单本地提交
     */
    onLocalSubmit (res, callback) {
      const form = res.realForm
      if (res.businessType === '新增') {
        this.$refs.xTable.appendLocalData(form)
      } else {
        this.$refs.xTable.modifyLocalData(form['序号'], form)
      }
      this.$message.success(res.businessType + '成功！')
      this.onAddOrEditSubmitAfterSubmit(res, callback)
      if (callback) {
        callback()
      }
    },
    emitFunc (func, ...args) {
      this.$emit(func, ...args)
      this.$emit('getEmitFuncData', func, ...args)
    },
    // 直接转发事件的函数
    emitEvent (event, ...args) {
      this.$emit(event, ...args)
    },
    // 添加处理 rowClick 的方法
    handleRowClick (record) {
      this.$emit('rowClick', record)
    },
    handleRowDblClick (record) {
      this.$emit('rowDblClick', record)
    },
    beforeDataChange (record) {
      this.$emit('beforeDataChange', record)
    },
    onExpand (expanded, record) {
      this.$emit('expand', expanded, record)
    },
    /**
     * 处理进度更新事件
     * @param {Object} data 进度数据
     * @param {Object} record 行数据
     * @param {String} dataIndex 列字段名
     */
    handleProgressUpdated (data, record, dataIndex) {
      this.$emit('progressUpdated', data, record, dataIndex)
    },
    async beforeExportSetHeaders() {
      const hasListener = !!this.$listeners?.beforeExportSetHeaders

      if (!hasListener) return []

      const result = await new Promise(resolve => {
        this.$emit('beforeExportSetHeaders', resolve)
      })

      // 字符串 → 包装成数组
      if (typeof result === 'string') {
        return [result]
      }

      // 数组 → 原样返回
      if (Array.isArray(result)) {
        return result
      }

      // 其他情况 → 兜底为空数组
      return []
    }
  },
  action: {
    /**
     * 实现doAction方法
     */
    doAction (actionType, args, data) {
      switch (actionType) {
        case 'refreshTable':
          for (const item in args) {
            console.log('item', item)
          }
          break
        default:
          break
      }
    }
  },
  mounted () {
    if (!this.isMounted) {
      // 防止多次调用
      // 不知道为啥他会执行两次 mounted 暂时处理方式
      this.initConfig()
      this.isMounted = true
    }
    if (this.getSelectedData && typeof this.getSelectedData === 'function') {
      const selectedId = this.getSelectedData()
      if (!selectedId) {
        return
      }
      if (typeof selectedId === 'object') {
        const data = JSON.parse(JSON.stringify(selectedId))
        if (data.selectedId) {
          data.selected_id = data.selectedId
          delete data.selectedId
        }
        Object.assign(this.fixedAddForm, data)
        Object.assign(this.fixedQueryForm, data)
      } else {
        Object.assign(this.fixedAddForm, { selected_id: selectedId })
        Object.assign(this.fixedQueryForm, { selected_id: selectedId })
      }
    }
  }
}
</script>
<style lang="less" scoped>
.crud_title {
  height: 32px;
  font-size: 16px;
  font-weight: 500;
  color: #000000d9;
  line-height: 32px;
  margin-bottom: 12px;
}

// 表格行样式类型
.ant-table-tbody {
  // 成功样式 - 绿色 (#52c41a)
  .ant-table-row-success {
    background-color: rgba(82, 196, 26, 0.2);

    &:hover {
      background-color: rgba(82, 196, 26, 0.3) !important;

      td {
        background-color: transparent;
      }
    }

    // 选中状态
    &.ant-table-row-selected {
      background-color: rgba(82, 196, 26, 0.4);

      td {
        background-color: transparent;
      }
    }

    td {
      background-color: transparent;
    }
  }

  // 警告样式 - 黄色 (#faad14)
  .ant-table-row-warning {
    background-color: rgba(250, 173, 20, 0.1);

    &:hover {
      background-color: rgba(250, 173, 20, 0.15);

      td {
        background-color: transparent;
      }
    }

    // 选中状态
    &.ant-table-row-selected {
      background-color: rgba(250, 173, 20, 0.2);

      td {
        background-color: transparent;
      }
    }

    td {
      background-color: transparent;
    }
  }

  // 错误样式 - 红色 (#f5222f)
  .ant-table-row-error {
    background-color: rgba(245, 34, 47, 0.1);

    &:hover {
      background-color: rgba(245, 34, 47, 0.15);

      td {
        background-color: transparent;
      }
    }

    // 选中状态
    &.ant-table-row-selected {
      background-color: rgba(245, 34, 47, 0.2);

      td {
        background-color: transparent;
      }
    }

    td {
      background-color: transparent;
    }
  }

  // 魔法样式 - 紫色
  .ant-table-row-magic {
    background-color: rgba(114, 46, 209, 0.1);

    &:hover {
      background-color: rgba(114, 46, 209, 0.15);

      td {
        background-color: transparent;
      }
    }

    // 选中状态
    &.ant-table-row-selected {
      background-color: rgba(114, 46, 209, 0.2);

      td {
        background-color: transparent;
      }
    }

    td {
      background-color: transparent;
    }
  }

  // 默认选中状态（没有特殊行样式时）
  .ant-table-row-selected:not(.ant-table-row-success):not(.ant-table-row-warning):not(.ant-table-row-error):not(
      .ant-table-row-magic
    ) {
    background-color: rgba(24, 144, 255, 0.1);
  }
}
</style>
<style lang="less">
.splitpanes.default-theme .splitpanes__splitter {
  border: 0;
  width: 1rem;
  position: relative;

  &:before {
    content: '';
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    width: 2px;
    height: 30px;
    border-radius: 1px;
  }
}

.splitpanes.default-theme .splitpanes__pane {
  overflow: visible;
  background-color: transparent;
}

/* 弹框底部提示样式（与分页在同一行） */
.popup-footer-tip {
  color: rgba(0, 0, 0, 0.45);
  font-size: 12px;
  line-height: 1.5;
}
</style>
