<script lang="ts" setup>
import { ref, unref } from 'vue';

import { useAccess } from '@vben/access';
import { useVbenModal } from '@vben/common-ui';

import { Button, message } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { DatabaseApi } from '#/api';
import { TableAction } from '#/components/table-action';

import { formOptions, gridColumnOptions } from '../data.config';
import FormEdit from './editColumn.vue';

defineOptions({
  name: 'DatabaseEdit',
});
const emit = defineEmits(['success']);

const { hasAccessByCodes } = useAccess();
const modelRef = ref<Record<string, any>>({});
const isUpdate = ref(true);

const [Form, { validate, setValues, getValues, updateSchema }] = useVbenForm({
  showDefaultActions: false,
  ...formOptions,
});

const [Grid, gridApi] = useVbenVxeGrid({
  gridOptions: gridColumnOptions,
});

const [FormEditModal, formEditApi] = useVbenModal({
  connectedComponent: FormEdit,
});

const [Modal, { close, setState, getData }] = useVbenModal({
  // fullscreenButton: true,
  fullscreen: true,
  draggable: true,
  onCancel() {
    close();
  },
  onConfirm: async () => {
    try {
      const { valid } = await validate();
      if (valid) {
        const values = await getValues();
        setState({ confirmLoading: true });
        const postParams = unref(modelRef);
        Object.assign(postParams, values);

        const data = gridApi.grid.getTableData();
        postParams.columns = data.fullData;

        await (unref(isUpdate)
          ? DatabaseApi.editDetail(postParams as DatabaseApi.RecordItem)
          : DatabaseApi.addDetail(postParams as DatabaseApi.BasicRecordItem));
        message.success('操作成功');

        close();
        emit('success');
      }
    } catch {
      message.error('操作失败');
    } finally {
      setState({ confirmLoading: false });
    }
  },
  onOpenChange: async (isOpen: boolean) => {
    if (isOpen) {
      setState({ loading: true });
      const data = getData<Record<string, any>>();
      isUpdate.value = !!data.isUpdate;
      modelRef.value = { ...data.baseData };
      setState({ title: unref(isUpdate) ? '编辑表' : '新增表' });

      if (unref(isUpdate)) {
        const entity = await DatabaseApi.getDetail(data.baseData.id);
        modelRef.value = { ...entity };

        setValues(entity);

        gridApi.grid.reloadData(entity.columns);

        updateSchema([
          {
            fieldName: 'name',
            componentProps: { disabled: true },
          },
        ]);
      } else {
        updateSchema([
          {
            fieldName: 'name',
            componentProps: { disabled: false },
          },
        ]);
      }
      setState({ loading: false });
    }
  },
  title: '新增表',
});

const handleDelete = (record: any) => {
  gridApi.grid.remove(record);
};

const handleEdit = (record: any, isUpdate: boolean) => {
  formEditApi.setData({
    isUpdate,
    baseData: record,
  });
  if (isUpdate) {
    gridApi.grid.setEditRow(record);
  }
  formEditApi.open();
};

const handelSuccess = (record: any) => {
  if (record.isUpdate) {
    // const row = gridApi.grid.getEditRecord();
    // console.log('edit row', row);
    // if (gridApi.grid.isUpdateByRow(record.sourceData)) {
    //   gridApi.grid.reloadRow(record.sourceData, record.data);
    // } else {
    //   console.log('not found row');
    // }
  }
  // else {
  //   gridApi.grid.insert(record.data);
  // }
  gridApi.grid.insert(record.data);
};
</script>
<template>
  <Modal class="h-[800px] w-[1000px]">
    <FormEditModal :close-on-click-modal="false" @success="handelSuccess" />
    <div class="h-full">
      <div class="h-[168px]">
        <Form />
      </div>
      <div class="h-full" style="height: calc(100% - 168px)">
        <Grid>
          <template #toolbar-tools>
            <Button
              class="mr-2"
              type="primary"
              v-access:code="'table:add'"
              @click="() => handleEdit({}, false)"
            >
              新增列
            </Button>
          </template>

          <template #action="{ row }">
            <TableAction
              :actions="[
                {
                  label: '编辑',
                  type: 'text',
                  disabled: !hasAccessByCodes(['table:edit']),
                  onClick: handleEdit.bind(null, row, true),
                },
                {
                  label: '删除',
                  type: 'text',
                  disabled: !hasAccessByCodes(['table:delete']),
                  onClick: handleDelete.bind(null, row),
                },
              ]"
            />
          </template>
        </Grid>
      </div>
    </div>
  </Modal>
</template>
