<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>
    </BasicTable>
  </div>
</template>
<script lang="ts">
  import { defineComponent, ref, nextTick, inject } 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,
      },
    },
    emits: ['saveOrUpdate', 'deleteById'],
    setup(props, { emit }) {
      const deviceType = inject('deviceType');
      const { createMessage: msg } = useMessage();
      const currentEditKeyRef = ref('');
      const [registerTable, { insertTableDataRecord, reload }] = useTable({
        title: '',
        api: props.list?.bind(null, { devicetype: deviceType }),
        columns: props.columns as BasicColumn[],
        showIndexColumn: false,
        showTableSetting: false,
        tableSetting: { fullScreen: true },
        actionColumn: {
          width: 160,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
        },
      });
      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);
      }

      function handleDelete(record: EditRecordRow) {
        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', record);
            // 保存之后提交编辑状态
            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,
                onClick: handleDelete.bind(null, record),
              },
            ];
          } else {
            return [
              {
                label: '编辑',
                disabled: currentEditKeyRef.value ? currentEditKeyRef.value !== record.key : false,
                onClick: handleEdit.bind(null, record),
              },
            ];
          }
        }
        return [
          {
            label: '保存',
            onClick: 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,
      };
    },
  });
</script>
<style scoped lang="less">
  :deep(.ant-table-body) {
    height: auto !important;
  }
</style>
