<template>
  <div class="p-4">
    <a-button v-if="isAdd" type="primary" @click="addRow"> 新增 </a-button>
    <BasicTable @register="registerTable" @edit-change="onEditChange">
      <template #action="{ record, column }">
        <TableAction :actions="createActions(record, column)" />
      </template>
      <template #bodyCell="{ column, record }">
        <slot name="filterCell" v-bind="{ column, record }"> </slot>
      </template>
    </BasicTable>
  </div>
</template>
<script lang="ts">
  import { defineComponent, ref, nextTick } from 'vue';
  import { BasicTable, useTable, TableAction, BasicColumn, ActionItem, EditRecordRow } from '/@/components/Table';
  import { useMessage } from '/@/hooks/web/useMessage';
  // import { nextTick } from 'process';

  export default defineComponent({
    components: { BasicTable, TableAction },
    props: {
      columns: {
        type: Array,
        requried: true,
      },
      list: {
        type: Function,
        requried: true,
      },
      isAdd: {
        type: Boolean,
      },
      isRadio: {
        type: Boolean,
      },
    },
    emits: ['saveOrUpdate', 'deleteById', 'rowChange'],
    setup(props, { emit }) {
      const { createMessage: msg } = useMessage();
      const currentEditKeyRef = ref('');

      const [registerTable, { insertTableDataRecord, reload, getSelectRows, getDataSource, setTableData }] = useTable({
        title: '',
        api: props.list,
        rowKey: 'id',
        clickToRowSelect: false,
        columns: props.columns as BasicColumn[],
        showIndexColumn: false,
        showTableSetting: false,
        rowSelection: !props.isRadio ? undefined : { type: 'radio', onChange: rowChange },
        tableSetting: { fullScreen: true },
        actionColumn: {
          width: 160,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
        },
      });

      function rowChange(e) {
        emit('rowChange', e[0], getSelectRows()[0]);
      }

      function addRow() {
        const record = {} as EditRecordRow;
        insertTableDataRecord(record);
        nextTick(() => {
          handleEdit(record);
        });
      }
      function handleEdit(record: EditRecordRow) {
        currentEditKeyRef.value = record.key;
        record.onEdit?.(true);
      }

      function handleCancel(record: EditRecordRow) {
        currentEditKeyRef.value = '';
        record.onEdit?.(false, false);
        if (!record.id) {
          const dataSource = getDataSource();
          const res = dataSource.filter((item) => {
            return item.id != undefined;
          });
          setTableData(res);
        }
      }

      function handleDelete(record: EditRecordRow) {
        if (record.id) emit('deleteById', record.id, reload);
      }

      async function handleSave(record: EditRecordRow) {
        // 校验
        msg.loading({ content: '正在保存...', duration: 0, key: 'saving' });
        const valid = await record.onValid?.();
        if (valid) {
          try {
            //TODO 此处将数据提交给服务器保存
            emit('saveOrUpdate', Object.assign(record, record.editValueRefs));
            // 保存之后提交编辑状态
            const pass = await record.onEdit?.(false, true);
            if (pass) {
              currentEditKeyRef.value = '';
            }
            msg.success({ content: '数据已保存', key: 'saving' });
          } catch (error) {
            msg.error({ content: '保存失败', key: 'saving' });
          }
        } else {
          msg.error({ content: '请填写正确的数据', key: 'saving' });
        }
      }

      function createActions(record: EditRecordRow, column: BasicColumn): ActionItem[] {
        if (!record.editable) {
          if (props.isAdd) {
            return [
              {
                label: '编辑',
                disabled: currentEditKeyRef.value ? currentEditKeyRef.value !== record.key : false,
                onClick: handleEdit.bind(null, record),
              },
              {
                label: '删除',
                disabled: currentEditKeyRef.value ? currentEditKeyRef.value !== record.key : false,
                popConfirm: {
                  title: '是否删除',
                  confirm: handleDelete.bind(null, record),
                },
              },
            ];
          } else {
            return [
              {
                label: '编辑',
                disabled: currentEditKeyRef.value ? currentEditKeyRef.value !== record.key : false,
                onClick: handleEdit.bind(null, record),
              },
            ];
          }
        }
        return [
          {
            label: '保存',
            popConfirm: {
              title: '是否保存',
              confirm: handleSave.bind(null, record, column),
            },
          },
          {
            label: '取消',
            popConfirm: {
              title: '是否取消编辑',
              confirm: handleCancel.bind(null, record, column),
            },
          },
        ];
      }

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

      return {
        registerTable,
        handleEdit,
        createActions,
        onEditChange,
        addRow,
        reload,
        getDataSource,
      };
    },
  });
</script>
<style scoped lang="less">
  @ventSpace: zxm;
  :deep(.@{ventSpace}-table-body) {
    height: auto !important;
  }
</style>
