<template>
  <div style="height: 100%;">
    <teleport :to="getContainer()" :disabled="fullscreenTable == false">
      <div style="height: 100%" class="custom-table" :class="{ fullscreen: fullscreenTable == true }" ref="reftableDiv"
        :id="tableID">
        <SchemaForm v-if="searchBox" ref="queryFormRef"
          class="bg-white dark:bg-black mb-16px pt-24px pr-24px table-search-form" submit-on-reset v-bind="getFormProps"
          :is-outline="false" :table-instance="tableAction" @toggle-advanced="(e) => $emit('toggle-advanced', e)"
          @submit="handleSubmit">
          <template v-for="item in getFormSlotKeys" #[replaceFormSlotKey(item)]="data">
            <slot :name="item" v-bind="data || {}"></slot>
          </template>
        </SchemaForm>
        <div class="bg-white dark:bg-black">
          <ToolBar v-if="showToolBar" :title="headerTitle" :title-tooltip="titleTooltip"
            :show-table-setting="showTableSetting" :showOrderParama="showOrderParama" :showFullScreen="fullscreenTable"
            :showAutoForm="props.queryFilterForm" :export-file-name="exportFileName" :is-export-current="isExportCurrent"
            class="table-tool-bar" @cols-change="handleColsChange" @order-change="handleOrderChange"
            @full-screen="handleFullScreen" @complex-query="handleComplexQuery" style="height: 26px;">
            <template v-for="name of Object.keys($slots)" #[name]="data">
              <slot :name="name" v-bind="data || {}"></slot>
            </template>
          </ToolBar>
          <SchemaForm ref="editTableFormRef" no-style :initial-values="editFormModel" :show-action-button-group="false"
            :show-advanced-button="false" @validate="handleEditFormValidate">
            <Table class="base-table" ref="tableRef" :id="tableID" v-bind="getBindValues" :columns="innerColumns"
              :data-source="tableData" :scroll="unref(scroll)" :row-class-name="setRowClassName"
              @resize-column="handleResizeColumn" :customRow="handleRowClick" :customHeaderRow="headerClick"
              :customCell="cellClick" :customHeaderCell="headerCellClick" @change="handleTableChange">
              <template v-for="(_, slotName) of $slots" #[slotName]="slotData" :key="slotName">
                <slot :name="slotName" v-bind="slotData"></slot>
              </template>
              <template #bodyCell="slotData">
                <slot name="bodyCell" v-bind="slotData"></slot>
              </template>
            </Table>
          </SchemaForm>
        </div>
      </div>
      <ltAModel v-model:visible="visible" @ok="onOk" :title="$t('component.table.showInDlg')" :afterClose="handleOnClose"
        class="edit-dialog" width="800px">
        <SchemaForm ref="editFormRef" class="bg-white dark:bg-black mb-16px pt-24px pr-24px table-edit-row-form"
          submit-on-reset v-bind="getRowFormProps" :initial-values="currentRowData" :table-instance="tableAction"
          @submit="handleEditRowSubmit" @submit-error="handleError">
          <template v-for="item in getRowSlotKeys" #[replaceRowSlotKey(item)]="data">
            <slot :name="item" v-bind="data || {}"></slot>
          </template>
        </SchemaForm>
      </ltAModel>

    </teleport>
  </div>
</template>

<script lang="tsx" setup >
import { useSlots, defineProps, onMounted, ref, nextTick, watch, computed, onBeforeMount, onUnmounted, watchEffect, unref } from 'vue';
import { message, Table } from 'ant-design-vue';
import {
  useTableMethods,
  createTableContext,
  useExportData2Excel,
  useTableForm,
  useRowForm,
  useTableState,
  useEditable,
  useColumns
} from './hooks';
import { ToolBar } from './components';
import { dynamicTableProps, dynamicTableEmits } from './dynamic-table';
import { TableActionType } from './types';
import { SchemaForm } from '../../lt-a-form/src';
import { GuidID } from "./hooks/commonMethods"
import type { RowClassName } from 'ant-design-vue/lib/vc-table/interface';
import * as signalR from '@microsoft/signalr';
import ltAModel from '../../lt-a-model';
import { useScroll } from './hooks/useScroll';
import { i18n } from '../../../locales/index';

defineOptions({
  name: 'ltATable',
  inheritAttrs:false 
});
const { t } = i18n.global;


const tableID = 'table-' + GuidID() //用来识别表格实例
console.log("生成的表格ID为：" + tableID)
const queryID = GuidID()
let fullscreenTable = ref(false)  //用来控制表格是否全屏显示
const visible = ref(false);
const currentRowData = ref<Recordable>({});

// let divHeight = 0
let connection: signalR.HubConnection
let currentKey = ref(0)
let lastCurrentKey = 0
const editFormRef = ref(null)


const props = defineProps(dynamicTableProps);
const emit = defineEmits(dynamicTableEmits);
const slots = useSlots();
const tableState = useTableState({ props, slots, tableID, emit });

const { tableRef, tableData, queryFormRef, editTableFormRef, getBindValues, editFormModel } =
  tableState;
// 表格内部方法
const tableMethods = useTableMethods({ state: tableState, props, emit, lastCurrentKey, currentKey, visible, currentRowData });
const {
  setProps,
  getTableData,
  handleSubmit,
  reload,
  handleTableChange,
  handleResizeColumn,
  getParentHeight,
  getOrderParama,
  orderChangeByForm,
  getDataByMonitor,
  startConect,
  setCellTtitle,
  handleEditFormValidate,
  initColumnFilter,
  getComplexCondition,
  rowClick,
  headerClick,
  cellClick,
  headerCellClick,
  editRowDlgOnOK,
  queryGroupData,
} = tableMethods;

const editableHooks = useEditable({ props, state: tableState });
const tableAction: TableActionType = {
  setProps,
  reload,
  getTableData,
  ...editableHooks
};

// 表格列的配置描述
const { innerColumns } = useColumns({
  props,
  slots,
  state: tableState,
  methods: tableMethods,
  tableAction,
  emit,
  tableID
});

const showOrderParama = computed(() => {
  //联合排序功能，只用于后台排序，本地排序不做处理
  return props.OrderParam.length > 0 && props.dataSource?.length == 0
})

const isExportCurrent = computed(() => {
  //联合排序功能，只用于后台排序，本地排序不做处理
  return typeof props.url == "undefined"
})
// 搜索表单
const { getFormProps, replaceFormSlotKey, getFormSlotKeys } = useTableForm({
  tableState,
  tableMethods,
  slots,
});

// 查看详细信息表单
const { getRowFormProps, replaceRowSlotKey, getRowSlotKeys } = useRowForm({
  tableState,
  tableMethods,
  slots,
});

// 表单导出
const exportData2ExcelHooks = useExportData2Excel({
  props,
  state: tableState,
  methods: tableMethods,
});

const { scroll } = useScroll({ props, tableID, tableData, tableMethods });

// 当前组件所有的状态和方法
const instance = {
  ...props,
  ...tableState,
  ...tableMethods,
  ...editableHooks,
  ...exportData2ExcelHooks,
};

createTableContext(instance);
defineExpose(instance);

const getContainer = function () {
  return document.body
}
//行点击事件
const handleRowClick = function (record, index) {
  return rowClick(record, index, currentKey)
};

const handleColsChange = function (cols) {
  console.log("执行列改变事件")
  initColumnFilter(tableID, props, cols)
}

const handleOrderChange = function (value, isUnion) {
  orderChangeByForm(value, isUnion)
  const sendData = {
    value: value,
    isUnion: isUnion
  }
  //像外部推送排序详细信息
  emit("order-change", sendData)
}

const handleFullScreen = function (value) {
  fullscreenTable.value = value
}

const handleComplexQuery = function (value) {
  getComplexCondition(value)
}

const setRowClassName = function (record, index): string | RowClassName<any> {
  //是否高亮显示当前行
  if (props.highlightCurrentRow && (typeof record._tableKey != 'undefined') && record._tableKey == currentKey.value) {
    return 'curren-row'
  }
  if (props.rowClassName) {
    return props.rowClassName
  } else {
    if (props.stripe) {
      if (index % 2 === 1) {
        return 'table-striped'
      }
    } else {
      return ""
    }
  }
  return ""
}

const onOk = () => {
  if (editFormRef.value) {
    //@ts-ignore 
    //借用底层函数实现form表单数据
    editFormRef.value.submit()
  }
  // visible.value = false
}

const handleEditRowSubmit = (value) => {
  editRowDlgOnOK(value)
  visible.value = false
}

const handleError = () => {
  message.warn(t('component.table.validWarning'))
  visible.value
}

const handleOnClose = function () {
  visible.value = false
}

watch(
  () => [props.setCurrentNum, innerColumns.value],
  () => {
    if (props.setCurrentNum) {
      //设置当前行关键字
      currentKey.value = props.setCurrentNum
    }
  }
);

watchEffect(() => {
  if (props.selectTypeAfterload == 1) {
    currentKey.value = 1
  } else if (props.selectTypeAfterload == 2) {
    currentKey.value = lastCurrentKey
  }
});

if (props.ifMonitor) {
  connection = new signalR.HubConnectionBuilder() //服务器地址
    .withUrl(props.signalrUrl, {})
    .configureLogging(signalR.LogLevel.Information)
    .build();
}

onBeforeMount(() => {
  if (props.ifMonitor) {
    getDataByMonitor(connection, queryID)
  }
})

onMounted(() => {
  getParentHeight(tableID) //先获取父亲的高度
  getOrderParama()
  nextTick(() => {
    getTableData();
    if (props.ifFixed)
      setCellTtitle(tableID)
  })
  if (props.ifMonitor) {
    startConect(connection, props);
    connection.onclose(async () => {
      console.log("尝试重新连接");
      await startConect(connection, props);
    });
  }
})

onUnmounted(() => {
  if (props.ifMonitor) {
    connection.send("UnSubcribe", queryGroupData.ScruSubcribeId);
    connection.stop();
  }
})

</script>

<style lang="less" scoped>
:deep(.ant-table-wrapper) {
  padding: 0 6px 6px 6px;

  .ant-table {
    .ant-table-title {
      display: flex;
    }

    .ant-image:hover {
      cursor: zoom-in;
    }

    .ant-btn {
      margin-right: 10px;
    }
  }
}

.bg-white:deep(.ant-table-wrapper) {
  height: 100%;
}

.bg-white :deep(.ant-spin-nested-loading) {
  height: 100%;
}

.bg-white :deep(.ant-spin-container) {
  height: 100%;
}


// .lt-a-table :deep.ant-table-thead deep.ant-table-cell {
//   font-weight: bold!important;
// }
// .lt-a-table:deep(.ant-table-container table>thead>tr:first-child th:first-child) {
//   border-top-left-radius: 2px;
//   font-weight: bold !important;
// }

// //设置表头字体为粗体显示 
// //紧凑型表格
// .lt-a-table:deep(.ant-table-small .ant-table-thead > tr > th) {
//   font-weight: bold !important;
// }

// //中等型表格
// .lt-a-table:deep(.ant-table-middle .ant-table-thead > tr > th) {
//   font-weight: bold !important;
// }

// //默认大型表格
// .lt-a-table:deep(.ant-table .ant-table-thead > tr > th) {
//   font-weight: bold !important;
// }

// //设置数据显示间隔 目前只修正紧凑型
// .lt-a-table:deep(.ant-table.ant-table-small .ant-table-tbody > tr > td) {
//   padding: 1px 1px 1px 1px !important;
// }

.custom-table {
  &.fullscreen {
    top: 0 !important;
    right: 0 !important;
    bottom: 0 !important;
    left: 0 !important;
    width: 100% !important;
    height: 100% !important;
    max-width: 100vw !important;
    position: absolute;
    background-color: white;
  }

  .ant-modal {
    position: fixed;
    padding: 0;
    min-height: 200px;
    min-width: 200px;

    .ant-modal-close {
      top: 6px;
      right: 6px;

      &:hover,
      &:focus {
        color: rgba(0, 0, 0, 0.45);
      }

      .ant-space-item:hover .anticon,
      .ant-space-item:focus .anticon {
        color: rgba(0, 0, 0, 0.75);
        text-decoration: none;
      }

      .ant-modal-close-x {
        width: 50px;
        height: 50px;
        line-height: 44px;

        .ant-space {
          width: 100%;
          height: 100%;
        }
      }
    }

    .ant-modal-content {
      /* width: ~'v-bind("props.width")px'; */
      display: flex;
      flex-direction: column;
      width: 100%;
      height: 100%;
      min-height: 200px;
      min-width: 200px;
      overflow: hidden;

      .ant-modal-body {
        flex: auto;
        overflow: auto;
        height: 100%;
      }
    }
  }
}

.actions>* {
  margin-right: 10px;
}
</style>

<style scoped>
.custom-table:deep(.table-striped) td {
  background-color: #fafafa !important;
}

.custom-table:deep(.curren-row) td {
  background-color: var(--currentListColor, #00b4ed) !important;
  font-size: 14px !important;
  font-weight: bold !important;
}

.custom-table:deep() td {
  padding: 1px 4px !important;
  white-space: nowrap;
}

.custom-table:deep()tr,
td {
  white-space: nowrap;
  text-overflow: ellipsis;
  word-break: break-word;
  overflow: hidden;
}

.custom-table:deep(.ant-table-pagination.ant-pagination) {
  margin: 10px 0 !important;
}

.edit-dialog:deep(.ant-modal-body) {
  padding: 10px !important;
}

/* 调整查询form显示样式 */
.custom-table :deep(.ant-col) {
  height: 38px;
  padding: 2px;
}

.custom-table :deep(.ant-form-item) {
  margin-bottom: 0px;
}

.base-table :deep(.ant-col) {
  height: 24px;
  padding: 0px;
}

.base-table :deep(.ant-form-item) {
  margin-bottom: 0px;
}
</style>

