<template>
  <div>
    <!-- 标题区域 -->
    <div v-if="showTitle" class="table-title-container" :class="{ 'table-report-mode': isReportMode }">
      <div class="table-title-content">
        <span class="title-text">{{ titleData.text }}</span>
        <span class="title-unit-text">共</span>
        <span class="title-value" v-if="titleData.value !== null">
          {{ titleData.value }}
        </span>
        <span class="title-unit-text">条</span>
      </div>
      <div v-if="titleData.line" class="title-line"></div>
    </div>

    <!-- 表格区域 -->
    <div class="table-container" :class="{ 'table-report-mode': isReportMode }" :style="{ height: tableHeight }">
      <a-table
        :loading="loading"
        :columns="processedColumns"
        :dataSource="tableData"
        :pagination="false"
        :bordered="false"
        :rowKey="rowKey"
        :scroll="{ y: scrollY }"
        :customRow="customRow"
      />
    </div>
  </div>
</template>

<script>
import { getConfigByName, runLogic } from '@vue2-client/services/api/common'

export default {
  props: {
    queryParamsName: {
      required: true,
      type: String
    },
    rowKey: {
      type: String,
      default: 'id'
    },
    parameter: {
      type: Object,
      default: () => ({})
    }
  },
  data () {
    return {
      columns: [],
      tableData: [],
      tableHeight: 'auto',
      scrollY: undefined,
      rowStyleConfig: {},
      isReportMode: false,
      // 标题数据
      titleData: {
        show: false,
        text: '',
        value: null,
        line: false
      },
      dataMode: 'normal',
      loading: false // 新增加载状态
    }
  },
  watch: {
    queryParamsName: {
      immediate: true,
      handler (val) {
        val && this.init(val, this.parameter)
      }
    }
  },
  computed: {
    showTitle () {
      return this.titleData.show === true && (this.titleData.text || this.titleData.value !== null)
    },

    processedColumns () {
      return this.columns.map(column => {
        const processedColumn = {
          ...column,
          customHeaderCell: column.headerStyle
            ? () => ({ style: column.headerStyle })
            : undefined,
          customCell: (record, rowIndex) => {
            let cellStyle = {}

            if (column.contentStyle && typeof column.contentStyle === 'object') {
              cellStyle = { ...column.contentStyle }
            }

            if (this.isReportMode && column.displayType === 'progress') {
              Object.assign(cellStyle, {
                padding: '8px 4px'
              })
            }

            return { style: cellStyle }
          }
        }

        if (column.displayType === 'progress') {
          processedColumn.customRender = (text, record, index) => {
            if (text === undefined || text === null || text === '') {
              return text
            }

            const num = parseFloat(text)
            if (!isNaN(num)) {
              const percentage = Math.min(Math.max(num, 0), 100)

              if (this.isReportMode) {
                return this.$createElement('div', {
                  style: {
                    display: 'flex',
                    alignItems: 'center',
                    gap: '8px',
                    width: '100%'
                  }
                }, [
                  this.$createElement('div', {
                    style: {
                      position: 'relative',
                      width: '100px',
                      height: '6px',
                      backgroundColor: '#f5f5f5',
                      borderRadius: '6px',
                      overflow: 'hidden',
                      flexShrink: 0
                    }
                  }, [
                    this.$createElement('div', {
                      style: {
                        position: 'absolute',
                        top: 0,
                        left: 0,
                        width: `${percentage}%`,
                        height: '100%',
                        backgroundColor: '#377CFF',
                        borderRadius: '6px',
                        opacity: 1,
                        transition: 'width 0.3s ease'
                      }
                    })
                  ]),
                  this.$createElement('span', {
                    style: {
                      fontFamily: 'Source Han Sans',
                      fontWeight: 700,
                      fontSize: '16px',
                      color: '#0057FE',
                      whiteSpace: 'nowrap'
                    }
                  }, `${text}${column.unit || ''}`)
                ])
              } else {
                return this.$createElement('div', {
                  style: {
                    position: 'relative',
                    width: '100%',
                    height: '20px',
                    backgroundColor: '#f5f5f5',
                    borderRadius: '10px',
                    overflow: 'hidden'
                  }
                }, [
                  this.$createElement('div', {
                    style: {
                      position: 'absolute',
                      top: 0,
                      left: 0,
                      height: '100%',
                      width: `${percentage}%`,
                      backgroundColor: this.getProgressColor(percentage),
                      borderRadius: '10px',
                      transition: 'width 0.3s ease'
                    }
                  }),
                  this.$createElement('div', {
                    style: {
                      position: 'absolute',
                      top: 0,
                      left: 0,
                      width: '100%',
                      height: '100%',
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                      fontSize: '12px',
                      fontWeight: 'bold',
                      color: percentage > 50 ? '#fff' : '#333',
                      zIndex: 1
                    }
                  }, `${text}${column.unit || ''}`)
                ])
              }
            }

            return text
          }
        } else if (column.unit && !processedColumn.customRender) {
          processedColumn.customRender = (text, record, index) => {
            if (text === undefined || text === null || text === '') {
              return text
            }

            const num = parseFloat(text)
            if (!isNaN(num)) {
              return {
                children: [
                  this.$createElement('span', {
                    style: column.contentStyle || {}
                  }, text),
                  this.$createElement('span', {
                    style: {
                      fontFamily: 'Source Han Sans',
                      fontSize: '16px',
                      fontWeight: 'normal',
                      lineHeight: '37px',
                      color: '#313131',
                      marginLeft: '2px'
                    }
                  }, column.unit)
                ]
              }
            }

            return text
          }
        }

        return processedColumn
      })
    },

    customRow () {
      return (record, index) => {
        const rowStyle = { ...this.rowStyleConfig }

        if (this.isReportMode) {
          Object.assign(rowStyle, {
            borderBottom: '1px solid #E5E9F0',
            margin: 0,
            padding: 0
          })
        }

        return {
          style: rowStyle,
          on: {
            click: () => this.$emit('row-click', record, index)
          }
        }
      }
    }
  },
  methods: {
    getProgressColor (percentage) {
      if (percentage < 30) {
        return '#ff4d4f'
      } else if (percentage < 60) {
        return '#faad14'
      } else if (percentage < 80) {
        return '#1890ff'
      } else {
        return '#52c41a'
      }
    },

    // 修改 init 为返回 Promise，并添加 loading 控制
    init (config, parameterData) {
      return new Promise((resolve, reject) => {
        this.loading = true // 开始加载

        getConfigByName(config, 'af-his', res => {
          // 配置获取成功
          this.tableHeight = res.tableHeight || '400px'
          this.columns = res.columns || []
          this.rowStyleConfig = res.rowStyle || {}
          this.dataMode = res.dataMode || 'normal'

          // 报表模式判断
          this.isReportMode = this.$attrs['report-mode'] === true ||
            this.$attrs['report-mode'] === '' ||
            this.$attrs['report-mode'] === 'true'

          // 标题配置
          const titleConfig = res.titleConfig || {}
          this.titleData = {
            show: titleConfig.show || false,
            text: titleConfig.text || '',
            line: titleConfig.line || false,
            value: null
          }

          // 执行逻辑获取数据
          runLogic(res.logicName, parameterData, 'af-his')
            .then(result => {
              // 根据 dataMode 处理返回数据
              if (this.dataMode === 'title' && result && typeof result === 'object') {
                if (result.title) {
                  this.titleData.show = true
                  this.titleData = {
                    ...this.titleData,
                    ...result.title,
                    value: result.title.value !== undefined ? result.title.value : result.title.count
                  }
                }
                this.tableData = result.data || []
              } else {
                this.tableData = Array.isArray(result) ? result : []
              }

              // 标题数据补全
              if (this.titleData.show) {
                if (this.titleData.value === null || this.titleData.value === undefined) {
                  this.titleData.value = this.tableData.length
                }
              }

              // 添加 key
              this.tableData = this.tableData.map((item, index) => ({
                ...item,
                key: item[this.rowKey] || `row_${index}`
              }))

              this.$nextTick(() => {
                this.scrollY = this.tableHeight
              })

              resolve(result)
            })
            .catch(error => {
              console.error('数据加载失败', error)
              reject(error)
            })
            .finally(() => {
              this.loading = false
            })
        })
      })
    },

    // 刷新表格方法，返回 Promise 以便外部可 await
    refreshTable (parameterData) {
      const params = parameterData !== undefined ? parameterData : this.parameter
      return this.init(this.queryParamsName, params)
    }
  }
}
</script>

<style scoped lang="less">
/* 标题区域样式 - 默认 */
.table-title-container {
  margin-bottom: 16px;
  padding: 0 13px;
}

.table-title-content {
  display: flex;
  align-items: center;
  gap: 4px;
}

/* 标题文本 - 默认样式 */
.title-text {
  font-family: 'Source Han Sans', sans-serif;
  font-size: 18px;
  font-weight: 700;
  color: #313131;
  line-height: 1.5;
  white-space: nowrap;
}

/* 单位文本 - 默认样式 */
.title-unit-text {
  font-family: 'Source Han Sans', sans-serif;
  font-size: 14px;
  font-weight: 400;
  color: #5D5C5C;
  line-height: 1.5;
}

/* 值文本 - 默认样式 */
.title-value {
  font-family: 'Source Han Sans', sans-serif;
  font-size: 14px;
  font-weight: 400;
  color: #0057FE;
  line-height: 1.5;
  margin: 0 2px;
}

.title-line {
  height: 1px;
  background-color: #E5E9F0;
  width: 100%;
  margin-top: 8px;
}

/* 报表模式下的标题样式 */
.table-report-mode.table-title-container {
  .title-text {
    height: 37px;
    opacity: 1;
    font-family: 'Source Han Sans', sans-serif;
    font-size: 16px;
    font-weight: bold;
    line-height: 37px;
    letter-spacing: 0em;
    color: #313131;
    margin-right: 8px;
  }

  .title-value {
    font-family: 'Source Han Sans', sans-serif;
    font-weight: 700;
    font-size: 16px;
    color: #0057FE;
    line-height: 37px;
    margin: 0 2px;
  }

  .title-unit-text {
    font-family: 'Source Han Sans', sans-serif;
    font-weight: 400;
    font-size: 16px;
    color: #313131;
    line-height: 37px;
  }
}

/* 表格区域样式 */
.table-container {
  overflow: hidden;
  display: flex;
  flex-direction: column;
  padding-left: 13px;
}

.table-report-mode.table-container {
  padding-left: 0px !important;

  /* 修复表格整体边框 */

  :deep(.ant-table) {
    border: 1px solid #E5E9F0 !important;
    border-radius: 4px;
    overflow: hidden;
  }

  /* 修复表头容器 - 关键修复 */

  :deep(.ant-table-header) {
    margin-bottom: 0 !important;
    padding-bottom: 0 !important;
    min-width: auto !important;
    overflow: hidden !important;

    /* 修复表格元素 */

    table {
      border-spacing: 0 !important;
      border-collapse: collapse !important;
      table-layout: fixed !important;
      width: 100% !important;
    }
  }

  /* 修复表头单元格 */

  :deep(.ant-table-thead > tr > th) {
    border-bottom: 1px solid #E5E9F0 !important;
    border-right: none !important;
    border-left: none !important;
    background: white !important;

    /* 关键：强制清除内边距 */
    padding: 0 !important;
    margin: 0 !important;

    /* 关键：设置固定高度和行高 */
    height: 37px !important;
    line-height: 37px !important;
    vertical-align: middle !important;

    /* 确保内容正确显示 */

    .ant-table-header-column {
      display: block;
      height: 100%;

      & > div {
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }

    .ant-table-column-title {
      display: block;
      padding: 0 !important;
      margin: 0 !important;
      line-height: 37px !important;
    }

    .ant-table-column-sorter {
      margin: 0 !important;
    }
  }

  /* 修复表格内容区域 */

  :deep(.ant-table-tbody > tr) {
    border: none !important;
    margin: 0 !important;
    padding: 0 !important;
    height: 37px !important;

    td {
      border-bottom: 1px solid #E5E9F0 !important;
      border-right: none !important;
      border-left: none !important;
      background: white !important;
      padding: 0 !important;
      margin: 0 !important;
      height: 37px !important;
      line-height: 37px !important;
      vertical-align: middle !important;
    }

    &:last-child td {
      border-bottom: none !important;
    }
  }

  /* 确保表格滚动区域正确 */

  :deep(.ant-table-content) {
    margin: 0 !important;
    padding: 0 !important;
  }

  :deep(.ant-table-body) {
    margin: 0 !important;
    padding: 0 !important;
    border-top: none !important;
  }

  :deep(.ant-table-scroll) {
    overflow: hidden;
  }
}

/* 基础表格样式 */
:deep(.ant-table) {
  border: none !important;
  flex: 1;
  display: flex;
  flex-direction: column;
  margin: 0 !important;
}

:deep(.ant-table-content) {
  flex: 1;
  display: flex;
  flex-direction: column;
  margin: 0 !important;
}

:deep(.ant-table-body) {
  flex: 1;
  overflow-y: auto !important;
  margin: 0 !important;
  padding-top: 0 !important;
}

:deep(.ant-table-body) {
  scrollbar-width: thin;
  scrollbar-color: #E5E5E5 transparent;
}

:deep(.ant-table-body::-webkit-scrollbar) {
  width: 8px;
  height: 8px;
}

:deep(.ant-table-body::-webkit-scrollbar-track) {
  background: transparent;
}

:deep(.ant-table-body::-webkit-scrollbar-thumb) {
  background: #E5E5E5;
  border-radius: 25px;
}

:deep(.ant-table-tbody > tr > td) {
  border-bottom: none !important;
  padding: 6px !important;
  font-family: 'Source Han Sans', sans-serif;
  font-size: 14px;
  font-weight: 400;
  line-height: 18px;
  letter-spacing: 0em;
  font-optical-sizing: auto;
  font-feature-settings: 'kern' on;
  color: #5D5C5C;
  margin: 0 !important;
}

:deep(.ant-table-thead > tr > th) {
  border-bottom: none !important;
  background: none !important;
  padding: 8px 6px;
  position: sticky;
  top: 0;
  z-index: 1;
  background-color: white !important;
  height: 20px;
  opacity: 1;
  font-family: 'Source Han Sans', sans-serif;
  font-size: 14px;
  font-weight: 700;
  line-height: normal;
  letter-spacing: 0em;
  font-optical-sizing: auto;
  font-feature-settings: 'kern' on;
  color: #5D5C5C;
  margin: 0 !important;
}
</style>
