<script setup lang="ts">
import { type ColumnStyle } from 'element-plus';
import { showImagePreview } from 'vant';
import { h, ref, type VNode } from 'vue';
import CustomTooptip from './components/Tootips/Index.vue';

type TooltipOptions = {
  enterable: boolean;
  placement:
    | 'top'
    | 'bottom'
    | 'left'
    | 'right'
    | 'top-start'
    | 'top-end'
    | 'bottom-start'
    | 'bottom-end'
    | 'left-start'
    | 'left-end'
    | 'right-start'
    | 'right-end';
  showArrow: boolean;
  hideAfter: number;
  popperOptions: { strategy: 'fixed' | 'absolute' };
  modifiers: {
    name: string;
    options: {
      boundary: string;
      padding: number;
    };
  }[];
};

const data = defineModel<unknown[]>('data', { default: [] });
const props = defineModel<TablePropsType[]>('props');
// 是否只显示单行
const singleLine = defineModel<boolean>('singleLine', { default: false });
const rowStyle = defineModel<ColumnStyle<any>>('rowStyle', {
  default: {}
});
// 显示表格的高度, 默认的高度是 200px
const tableHeight = defineModel<string | number>('height', { default: '300px' });
// 表头样式
const headerStyle = defineModel<ColumnStyle<any>>('headerStyle');
const rounded = defineModel('rounded', { default: true });
const stripeColor = defineModel('stripeColor', { default: 'red' });
// 空数据时的提示文本
const emptyText = defineModel('emptyText', { default: '暂无数据' });

// tooltip options 内容
const tooltipOptions = ref<Partial<TooltipOptions>>({
  modifiers: [
    {
      name: 'preventOverflow',
      options: {
        boundary: 'viewport',
        padding: 8
      }
    }
  ]
});
// (data: { row: any; rowIndex: number; }) => string
function setStripeColor(rowData: { row: any; rowIndex: number }): string {
  const { rowIndex } = rowData;
  return rowIndex % 2 === 0 ? 'even-row' : 'odd-row';
}
// function parseTableText(text: string): string {
//   const imgReg = /<img.*?>/g;
//   const imgArr = text.match(imgReg);
//   if (imgArr && imgArr.length > 0) {
//     return imgArr.join('');
//   }
//   return text;
// }

function handleImageClick(e: Event) {
  if (e.target instanceof HTMLImageElement) {
    const imgSrc = e.target.src;
    showImagePreview({
      images: [imgSrc],
      closeable: true
    });
  }
}

let startX = 0;
const isHorizontal = ref(false);

function handleTouchStart(event: TouchEvent) {
  startX = event.touches[0].clientX;
  isHorizontal.value = false;
}

function handleTouchMove(event: TouchEvent) {
  const deltaX = event.touches[0].clientX - startX;

  // 如果是横向滑动，则阻止冒泡
  if (Math.abs(deltaX) > 10) {
    isHorizontal.value = true;
    event.stopPropagation(); // 阻止事件冒泡到 van-swipe
  }
}

function tooptipFormatter(data: { row: any; column: any; cellValue: any }): VNode {
  return h(CustomTooptip, {
    content: data
  });
}

// render
const RenderSlot = {
  functional: true,
  props: {
    row: Object,
    render: Function,
    index: Number,
    column: {
      type: Object,
      default: null
    }
  },
  setup(props) {
    return () => {
      const { row, index, column } = props;
      return props.render(h, { row, index, column });
    };
  }
};
</script>

<template>
  <div
    :style="{ borderRadius: rounded ? '10px' : '0', overflow: 'hidden' }"
    style="height: 100%"
    @touchstart="handleTouchStart"
    @touchmove="handleTouchMove"
  >
    <el-table
      :tooltip-options="tooltipOptions"
      :tooltip-formatter="tooptipFormatter"
      :max-height="tableHeight"
      :header-cell-style="headerStyle || { background: '#f2f8ee' }"
      :row-class-name="setStripeColor"
      :data="data"
      :empty-text="emptyText"
      style="width: 100%"
    >
      <el-table-column
        v-for="item in props"
        :key="item.prop"
        :width="item.width"
        :prop="item.prop"
        :label="item.label"
        :show-overflow-tooltip="item.tooltip ? item.tooltip : true"
        :sortable="item.sortable"
      >
        <template #default="scope">
          <slot name="column-default" :scope="scope">
            <div v-if="!item.render" @click.stop="handleImageClick">
              <span>{{ scope.row[item.prop] }}</span>
            </div>

            <RenderSlot
              v-else
              :row="scope.row"
              :render="item.render"
              :index="scope.$index"
              :column="item"
            ></RenderSlot>
          </slot>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>
<style>
.table-view-html {
  display: flex;
  //align-items: center;
  flex-direction: row;

  & img {
    width: 50px;
    height: 100%;
    margin-right: 10px;
  }
}
</style>
<style lang="scss" scoped>
:deep(.even-row) {
  background-color: #fff;
}
:deep(.odd-row) {
  background-color: #fafbfa;
}
:deep(.el-table__header-wrapper) {
  border-radius: 8px 8px 0 0;
}

.table-view-html {
  display: flex;
  justify-content: center;
  align-items: center;
  font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
  font-size: 12px;
}

.table-col {
  font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
  // font-size: 12px;
}
</style>
