<script lang="ts" setup>
import type { Recordable } from '@vben/types';

import type {
  OnActionClickParams,
  VxeTableGridOptions,
} from '#/adapter/vxe-table';
import type { SystemModel } from '#/api';

import { Page, useVbenModal } from '@vben/common-ui';
import { Plus } from '@vben/icons';

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

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { $t } from '#/locales';

import { useUserSearchFormSchema, useUserTableColumns } from './data';
import { mockData } from './mock';
import Form from './modules/form.vue';

const [FormModal, formModalApi] = useVbenModal({
  connectedComponent: Form,
  destroyOnClose: true,
});

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions: {
    schema: useUserSearchFormSchema(),
    submitOnChange: true,
  },
  gridOptions: {
    columns: useUserTableColumns(onActionClick, onStatusChange),
    height: 'auto',
    keepSource: true,
    // proxyConfig: {
    //   ajax: {
    //     query({ page }, formValues) {
    //       return listUsersMethod(page.currentPage, page.pageSize, formValues);
    //     },
    //   },
    // },
    // rowConfig: {
    //   keyField: 'id',
    // },
    proxyConfig: {
      response: {
        result: 'Data.Items',
        total: 'Data.TotalRecordCount',
      },

      ajax: {
        query() {
          return Promise.resolve({
            Data: mockData,
            ResultInfo: '操作成功',
            ResultCode: 0,
          });
        },
      },
    },

    rowConfig: {
      keyField: 'pid',
    },
  } as VxeTableGridOptions<SystemModel.User>,
});

function onActionClick(e: OnActionClickParams<SystemModel.User>) {
  switch (e.code) {
    case 'delete': {
      onDeleteHandle(e.row);
      break;
    }
    case 'edit': {
      onEditHandle(e.row);
      break;
    }
  }
}

/**
 * 将Antd的Modal.confirm封装为promise，方便在异步函数中调用。
 * @param content 提示内容
 * @param title 提示标题
 */
function confirm(content: string, title: string) {
  return new Promise((reslove, reject) => {
    Modal.confirm({
      content,
      onCancel() {
        reject(new Error('已取消'));
      },
      onOk() {
        reslove(true);
      },
      title,
    });
  });
}

/**
 * 状态开关即将改变
 * @param newStatus 期望改变的状态值
 * @param row 行数据
 * @returns 返回false则中止改变，返回其他值（undefined、true）则允许改变
 */
async function onStatusChange(newStatus: 0 | 1, row: SystemModel.User) {
  const status: Recordable<string> = {
    0: '启用',
    1: '禁用',
  };
  try {
    await confirm(
      `你要将${row.name}的状态切换为 【${status[newStatus.toString()]}】 吗？`,
      `切换状态`,
    );

    try {
      // await updateUserStatusMethod(row.pid!, { status: newStatus });
      mockData.Items = mockData.Items.map((item) => {
        if (item.pid === row.pid) {
          return {
            ...item,
            status: newStatus,
          };
        }
        return item;
      });
      notification.success({
        message: '切换状态成功',
      });
    } catch (error: any) {
      notification.error({
        message: error.message || '切换状态失败',
      });
    }

    return true;
  } catch {
    return false;
  }
}

function onRefresh() {
  gridApi.query();
}

function onEditHandle(row?: SystemModel.User) {
  formModalApi.setData(row ?? {}).open();
  console.log('row', row);
  console.log('mockdata', mockData)
}

async function onDeleteHandle(row: SystemModel.User) {
  const hideLoading = message.loading({
    content: $t('ui.actionMessage.deleting', [row.name]),
    duration: 0,
    key: 'action_process_msg',
  });
  try {
    console.log('删除', row);;
    // await deleteUserMethod(row);
    message.success({
      content: $t('ui.actionMessage.deleteSuccess', [row.name]),
      key: 'action_process_msg',
    });
    onRefresh();
  } finally {
    hideLoading();
  }
}
</script>
<template>
  <Page auto-content-height>
    <FormModal @success="onRefresh" />
    <Grid>
      <template #toolbar-tools>
        <Button type="primary" @click="onEditHandle()">
          <Plus class="size-5" />
          {{ $t('ui.actionTitle.create', [$t('system.user._')]) }}
        </Button>
      </template>
    </Grid>
  </Page>
</template>
