<script setup lang="ts">
import { ref, watch } from 'vue';
import App from '~/layout/app/index.vue';


const props = defineProps<{
  cols: {
    k: string
    v: string
    w?: number|string
    slot?: {
      type: string
      attr?: object
    }
  }[]
  modelValue?: string
}>()

const emits = defineEmits(["update:modelValue"])

type RowData = {
  [key: string]: any
}

const data = ref<RowData[]>(props.modelValue ? JSON.parse(props.modelValue) : [])

function newRow() {
  const obj: RowData = {}
  props.cols.forEach(({ k }) => {
    obj[k] = undefined
  })
  return obj
}

const addData = (i: number) => {
  data.value.splice(i, 0, newRow())
}

const removeData = (i: number) => {
  data.value.splice(i, 1)
}


watch(
  () => data.value,
  (val) => {
    emits("update:modelValue", JSON.stringify(val))
  },
  {
    deep: true
  }
)
</script>

<template>
  <el-table :data="data" cell-class-name="py-0">
    <el-table-column v-for="({ k, v, slot, w }) in cols" :prop="k" :label="v" :width="w ?? 'auto'">
      <template #default="{ row }">
        <template v-if="slot">
          <el-date-picker v-if="slot.type === 'datetimerange'" type="datetimerange" v-model="row[k]"
            value-format="YYYY-MM-DD HH:mm:ss" clearable v-bind="slot.attr"  class="w-full"/>
          <remote-select v-else-if="slot.type === 'remoteselect'" v-model="row[k]" v-bind="slot.attr" />
          <remote-multi-select v-else-if="slot.type === 'remotemultiselect'" v-model="row[k]" v-bind="slot.attr" />
        </template>
        <template v-else>
          <el-input size="small" v-model="row[k]"></el-input>
        </template>


      </template>
    </el-table-column>

    <el-table-column width="160">
      <template #header>
        <el-button size="small" @click="addData(0)">新增</el-button>
      </template>

      <template #default="{ row, $index }">
        <el-button size="small" @click="addData($index + 1)">新增</el-button>
        <el-button size="small" @click="removeData($index)">移除</el-button>
      </template>
    </el-table-column>
  </el-table>
</template>
