import { fetchDeptTree } from '@/services/dept';
import { fetchCreateUser, fetchUpdateUser } from '@/services/user';
import { DrawerForm, ProFormItem, ProFormText } from '@ant-design/pro-components';
import { TreeSelect } from 'antd';
import { useEffect, useState } from 'react';

interface UserFormProps {
  mode: EditorFormMode;
  initialValues?: Partial<API.UserItem>;
  trigger: React.ReactElement;
  onSuccess: (credentialsTicket?: string) => void;
}

const buildDeptOptions = (items: API.DeptItem[]): any[] =>
  items.map((d) => ({
    value: d.id,
    title: d.name,
    children: d.children ? buildDeptOptions(d.children) : undefined,
  }));

export const UserForm = ({ mode, initialValues, trigger, onSuccess }: UserFormProps) => {
  const [deptTree, setDeptTree] = useState<any[]>([]);
  const [open, setOpen] = useState(false);

  useEffect(() => {
    if (!open || deptTree.length > 0) return;
    fetchDeptTree().then((res) => setDeptTree(buildDeptOptions(res.data ?? [])));
  }, [open]);

  const title = { add: '新建用户', edit: '编辑用户', copy: '复制用户' }[mode];

  const formValues =
    mode === 'copy'
      ? {
          ...initialValues,
          id: undefined,
          username: undefined,
          deptId: initialValues?.deptId || undefined,
        }
      : mode === 'edit'
        ? { ...initialValues, deptId: initialValues?.deptId || undefined }
        : undefined;

  const handleFinish = async (values: any) => {
    if (mode === 'edit' && initialValues?.id) {
      const res = await fetchUpdateUser({
        id: initialValues.id,
        nickname: values.nickname,
        email: values.email,
        phone: values.phone,
        remark: values.remark,
        deptId: values.deptId ?? 0,
      });
      if (!res.success) return false;
      onSuccess();
    } else {
      const res = await fetchCreateUser(values);
      if (!res.success) return false;
      onSuccess(res.data?.credentialsTicket);
    }
    return true;
  };

  return (
    <DrawerForm
      title={title}
      trigger={trigger}
      initialValues={formValues}
      onFinish={handleFinish}
      onOpenChange={setOpen}
      drawerProps={{ destroyOnClose: true }}
    >
      <ProFormText
        name="username"
        label="用户名"
        rules={[{ required: true }]}
        disabled={mode === 'edit'}
        readonly={mode === 'edit'}
      />
      <ProFormText name="nickname" label="昵称" />
      <ProFormText name="email" label="邮箱" rules={[{ type: 'email' }]} />
      <ProFormText name="phone" label="手机号" />
      <ProFormText name="remark" label="备注" />
      <ProFormItem name="deptId" label="所属部门">
        <TreeSelect treeData={deptTree} allowClear placeholder="请选择部门" />
      </ProFormItem>
    </DrawerForm>
  );
};
