<template>
  <el-card :bordered="false" class="proCard">
    <BasicTable
      title="表格列表"
      titleTooltip="这是一个提示"
      :columns="columns"
      :request="loadDataTable"
      :row-key="(row) => row.id"
      ref="tableRef"
      :actionColumn="actionColumn"
      @edit-end="editEnd"
      @edit-change="onEditChange"
      @checked-row-change="onCheckedRow"
      :scroll-x="1590"
    >
      <template #toolbar>
        <el-button type="primary" @click="reloadTable">刷新数据</el-button>
      </template>
    </BasicTable>
  </el-card>
</template>

<script lang="ts" setup>
  import { reactive, ref, h } from 'vue';
  import { BasicTable, TableAction } from '@/components/Table';
  import { getTableList } from '@/api/table/list';
  import { columns } from './rowColumns';

  const tableRef = ref();
  const currentEditKeyRef = ref('');
  const params = reactive({
    pageSize: 5,
    name: 'xiaoMa',
  });

  const actionColumn = reactive({
    width: 150,
    label: '操作',
    prop: 'action',
    fixed: 'right',
    align: 'center',
    render(record) {
      return h(TableAction, {
        style: 'button',
        actions: createActions(record),
      });
    },
  });

  function handleEdit(record) {
    console.log(record.row);
    currentEditKeyRef.value = record.column.prop;
    record.row.onEdit?.(true);
  }

  function handleCancel(record) {
    currentEditKeyRef.value = '';
    record.row.onEdit?.(false, false);
  }

  function onEditChange({ column, value, record }) {
    if (column.key === 'id') {
      record.editValueRefs.name4.value = `${value}`;
    }
    console.log(column, value, record);
  }

  async function handleSave(record) {
    const pass = await record.row.onEdit?.(false, true);
    if (pass) {
      currentEditKeyRef.value = '';
    }
  }

  function createActions(record) {
    if (!record.row.editable) {
      return [
        {
          label: '编辑',
          type: 'primary',
          onClick: handleEdit.bind(null, record),
        },
      ];
    } else {
      return [
        {
          label: '保存',
          type: 'primary',
          onClick: handleSave.bind(null, record),
        },
        {
          label: '取消',
          onClick: handleCancel.bind(null, record),
        },
      ];
    }
  }

  const loadDataTable = async (res) => {
    return await getTableList({ ...params, ...res });
  };

  function onCheckedRow(rowKeys) {
    console.log(rowKeys);
  }

  function reloadTable() {
    console.log(tableRef.value);
    tableRef.value.reload();
  }

  function editEnd({ value }) {
    console.log(value);
  }
</script>

<style lang="scss" scoped></style>
