<template>
  <div>
    <t-table
      ref="tableRef"
      size="small"
      row-key="key"
      :columns="tableColumns"
      :data="tableData"
      bordered
    >
      <template v-if="!readonly" #operate="{ row, rowIndex }">
        <div class="table-operations">
          <t-link theme="primary" hover="color" @click="handleEdit(row)">
            修改
          </t-link>
          <t-link theme="primary" hover="color" @click="handleDelete(rowIndex)">
            删除
          </t-link>
        </div>
      </template>
    </t-table>
    <t-button
      v-if="!readonly"
      theme="primary"
      class="m-t-15px"
      @click="handleAdd"
    >
      <template #icon><Icon name="add"></Icon></template>
      添加
    </t-button>

    <!-- EditColumnDialog -->
    <edit-column-dialog
      v-model:visible="showEditColumnDialog"
      :curRow="curRow"
      :columns="formColumns"
      @success="columnConfirm"
    ></edit-column-dialog>
  </div>
</template>

<script setup name="DynamicTable">
import { computed, ref, watch } from 'vue';
import { Icon } from 'tdesign-icons-vue-next';
import { randomCode } from '@/utils/tool';
import EditColumnDialog from './edit-column-dialog.vue';

const props = defineProps({
  columns: {
    type: Array,
  },
  readonly: Boolean,
  modelValue: { type: Array },
});
const emit = defineEmits(['update:modelValue', 'change']);

const tableRef = ref();
const tableData = ref([]);
const showEditColumnDialog = ref(false);
const curRow = ref(null);

const tableColumns = computed(() => {
  let ncolumns = [...props.columns];
  const operateIndex = props.columns.findIndex(
    (item) => item.colKey === 'operate'
  );
  if (operateIndex !== -1) ncolumns.splice(operateIndex, 1);
  ncolumns.push({
    title: '管理',
    colKey: 'operate',
    fixed: 'right',
    width: 120,
  });
  return ncolumns;
});
const formColumns = computed(() => {
  return props.columns.filter((item) => item.colKey !== 'operate');
});

watch(
  () => props.modelValue,
  (val, oldval) => {
    console.log(val, oldval);
    if (val === oldval) return;
    tableData.value = val.map((item) => {
      return { ...item, key: randomCode() };
    });
  },
  {
    immediate: true,
  }
);

const rowData = props.columns.reduce((row, item) => {
  row[item.colKey] = '';
  return row;
}, {});

const handleAdd = () => {
  curRow.value = { ...rowData };
  showEditColumnDialog.value = true;
};
const handleEdit = (row) => {
  curRow.value = row;
  showEditColumnDialog.value = true;
};
const handleDelete = (index) => {
  console.log(index);
  tableData.value.splice(index, 1);
  emitChange();
};

const columnConfirm = (data) => {
  if (data.key) {
    const pos = tableData.value.findIndex((item) => item.key === data.key);
    tableData.value.splice(pos, 1, data);
  } else {
    data.key = randomCode();
    tableData.value.push(data);
  }
  emitChange();
};

const emitChange = () => {
  emit('update:modelValue', tableData.value);
  emit('change', tableData.value);
};
</script>
