import { BasicColumn, FormSchema } from '@/components/Table';
import { useI18n } from '@/hooks/web/useI18n';
import { formatToDateTime } from '@/utils/dateUtil';
import { updateServer } from '@/api/wechat/server';
import { Switch } from 'ant-design-vue';
import { h } from 'vue';
const { t } = useI18n();

export const columns: BasicColumn[] = [
  {
    title: t('wechat.server.name'),
    dataIndex: 'name',
    width: 100,
  },
  {
    title: t('wechat.server.publicIp'),
    dataIndex: 'publicIp',
    width: 100,
  },
  {
    title: t('wechat.server.privateIp'),
    dataIndex: 'privateIp',
    width: 100,
  },
  {
    title: t('wechat.server.adminPort'),
    dataIndex: 'adminPort',
    width: 100,
  },
  {
    title: t('common.status'),
    dataIndex: 'status',
    width: 50,
    customRender: ({ record }) => {
      if (!Reflect.has(record, 'pendingStatus')) {
        record.pendingStatus = false;
      }
      return h(Switch, {
        checked: record.status === 1,
        checkedChildren: t('common.on'),
        unCheckedChildren: t('common.off'),
        loading: record.pendingStatus,
        onChange(checked, _) {
          record.pendingStatus = true;
          const newStatus = checked ? 1 : 2;
          updateServer({ id: record.id, status: newStatus })
            .then(() => {
              record.status = newStatus;
            })
            .finally(() => {
              record.pendingStatus = false;
            });
        },
      });
    },
  },
  {
    title: t('common.createTime'),
    dataIndex: 'createdAt',
    width: 70,
    customRender: ({ record }) => {
      return formatToDateTime(record.createdAt);
    },
  },
];

export const searchFormSchema: FormSchema[] = [
  {
    field: 'name',
    label: t('wechat.server.name'),
    component: 'Input',
    colProps: { span: 8 },
  },
  {
    field: 'publicIp',
    label: t('wechat.server.publicIp'),
    component: 'Input',
    colProps: { span: 8 },
  },
  {
    field: 'privateIp',
    label: t('wechat.server.privateIp'),
    component: 'Input',
    colProps: { span: 8 },
  },
];

export const formSchema: FormSchema[] = [
  {
    field: 'id',
    label: 'ID',
    component: 'Input',
    show: false,
  },
  {
    field: 'name',
    label: t('wechat.server.name'),
    component: 'Input',
    required: true,
  },
  {
    field: 'publicIp',
    label: t('wechat.server.publicIp'),
    component: 'Input',
    required: true,
  },
  {
    field: 'privateIp',
    label: t('wechat.server.privateIp'),
    component: 'Input',
    required: true,
  },
  {
    field: 'adminPort',
    label: t('wechat.server.adminPort'),
    component: 'Input',
    required: true,
  },
  {
    field: 'status',
    label: t('wechat.server.status'),
    component: 'RadioButtonGroup',
    defaultValue: 1,
    componentProps: {
      options: [
        { label: t('common.on'), value: 1 },
        { label: t('common.off'), value: 2 },
      ],
    },
  },
];
