import React, {useEffect, useState} from 'react';
import {Modal, Form, Input, Select, Message} from '@arco-design/web-react';
import UploadFile from '@/components/Upload';
import {createUser, updateUser} from '@/api/user';
import {genderDict, statusDict} from "@/enum/dict";

interface Props {
	record: { [key: string]: any } | null,
	visible: boolean,
	handleConfirm: () => void,
	handleCancel: () => void
}

function FormComponent(props: Props) {
	const {visible, record, handleConfirm, handleCancel} = props;
	const [confirmLoading, setConfirmLoading] = useState(false);

	const onOk = async () => {
		try {
			setConfirmLoading(true);
			const values = await form.validate();
			const data = {
				...values,
				avatarId: values.avatar?.[0]?.response ?? null
			};
			if (record?.id) {
				await updateUser(data);
			} else {
				await createUser(data);
			}
			Message.success(`${record?.id ? '更新' : '新增'}成功！`);
			handleConfirm();
		} catch (e) {
			console.log(e);
		} finally {
			setConfirmLoading(false);
		}
	};

	const [form] = Form.useForm();

	useEffect(() => {
		record && form.setFieldsValue({
			...record,
			avatar: record.avatar ? [{
				uid: record.avatar.id,
				response: record.avatar.id,
				url: record.avatar.path
			}] : undefined
		});
	}, [record]);

	useEffect(() => {
		!visible && form.resetFields()
	}, [visible]);

	return (
		<Modal
			title={<span>{`${record?.id ? '更新' : '新增'}数据`}</span>}
			visible={visible}
			onOk={onOk}
			onCancel={handleCancel}
			confirmLoading={confirmLoading}
		>
			<Form form={form}>
				<Form.Item hidden={true} field="id" rules={[{required: false}]}>
					<Input/>
				</Form.Item>
				<Form.Item triggerPropName="fileList" label="用户头像"
				           field="avatar">
					<UploadFile limit={1} dir="user"/>
				</Form.Item>
				<Form.Item label="用户昵称" field="name" rules={[{required: true}]}>
					<Input placeholder="请输入用户昵称"/>
				</Form.Item>
				<Form.Item disabled={record?.id} label="用户账号" field="account" rules={[{required: true}]}>
					<Input placeholder="请输入用户账号"/>
				</Form.Item>
				{!record?.id && <Form.Item label="用户密码" field="password" rules={[{required: true}]}>
          <Input type="password" placeholder="请输入用户密码"/>
        </Form.Item>}
				<Form.Item label="用户状态" field="status" rules={[{required: true}]} initialValue={1}>
					<Select placeholder="请选择" options={statusDict}/>
				</Form.Item>
				<Form.Item label="用户性别" field="gender" rules={[{required: true}]}>
					<Select placeholder="请选择"
					        options={genderDict}/>
				</Form.Item>
			</Form>
		</Modal>
	);
}

export default FormComponent;
