<template>
  <view :class="`w-full`">
    <view
      :class="`table-cell`"
      v-for="(row, index) in column"
      :key="index"
      @click="handleRowClick(index)"
      :style="cellStyle"
    >
      {{ $slots.value }}
      <slot name="value" v-if="$slots.value" :row="getScope(index)" :index="index"></slot>
      <text :class="`table-value`" v-else>{{ row }}</text>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { useParent } from './useParent'
import { TABLE_KEY } from './types'
import { isDef, isFunction } from './utils'
const props = defineProps<{
  prop?: string
  label?: string
  width?: string
  align?: string
}>()

const { parent: table, index: columnIndex } = useParent(TABLE_KEY)

const column = computed(() => {
  if (!isDef(table)) {
    return []
  }

  const column: any[] = table.props.data.map((item) => {
    return item[props.prop]
  })
  return column
})

/**
 * 行点击事件
 * @param index 行下标
 */
function handleRowClick(index: number) {
  if (!isDef(table)) {
    return
  }
  isFunction(table.rowClick) && table.rowClick(index)
}

// 行数据
function getScope(index: number) {
  if (!isDef(table)) {
    return {}
  }

  return table.props.data[index] || {}
}

const cellStyle = computed(() => {
  let style: {
    width: string
    textAlign: 'left' | 'center' | 'right'
  } = { width: '', textAlign: 'center' }
  let _currentStyle = table.internalChildren[columnIndex.value].props
  if (_currentStyle.width) {
    style.width = _currentStyle.width
  }
  if (_currentStyle.align) {
    style.textAlign = _currentStyle.align
  }

  return style
})
</script>

<style scoped>
.table-cell {
  display: flex;
  align-items: center;
  justify-content: center;
  /* padding: 16rpx; */
  font-size: 20rpx;
  color: #333333;
  border-right: 1px solid #ddd;
}

.table-cell:last-child {
  border-right: none;
}

.text-left {
  justify-content: flex-start;
}

.text-center {
  justify-content: center;
}

.text-right {
  justify-content: flex-end;
}
</style>
