<template>
  <div class="flow-table">
    <!-- 当前示例包含：输入框、单选、多选、日期 等场景 -->
    <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="TABLE">
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({
  config: { type: Object },
  modelValue: { type: Array },
});
const emit = defineEmits(['update:modelValue', 'change']);

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

const readonly = computed(() => {
  return !props.config.writable;
});

const tableColumns = computed(() => {
  let ncolumns = props.config.tablePropList.map((item) => {
    return {
      title: item.title,
      colKey: item.tdName,
      comp: {
        type: item.tdFormWidget.code.toLowerCase(),
        attrs: {
          clearable: true,
        },
      },
      rules: [
        {
          required: true,
          message: '不能为空',
          type: 'error',
          trigger: 'change',
        },
      ],
    };
  });
  ncolumns.push({
    title: '管理',
    colKey: 'operate',
    fixed: 'right',
    width: 120,
  });
  return ncolumns;
});
const formColumns = computed(() => {
  return tableColumns.value.filter((item) => item.colKey !== 'operate');
});

const rowData = props.config.tablePropList.reduce((row, item) => {
  row[item.tdName] = '';
  return row;
}, {});

const handleAdd = () => {
  curRow.value = { ...rowData };
  showEditColumnDialog.value = true;
};
const handleEdit = (row) => {
  curRow.value = row;
  showEditColumnDialog.value = true;
};
const handleDelete = (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);
};

watch(
  () => props.modelValue,
  (val, oldval) => {
    if (val === oldval) return;
    const vals = val || [];
    tableData.value = vals.map((item) => {
      return { ...item, key: randomCode() };
    });
  },
  {
    immediate: true,
  }
);
</script>
