import { ButtonAccess, SafeModal } from '@/components';
import { business } from '@/services';
import { formLayout } from '@/utils/formLayout';
import {
	ModalForm,
	ProFormSelect,
	ProFormText,
} from '@ant-design/pro-components';
import { message } from 'antd';
import React, { useState } from 'react';

interface IEmployeeUpdateProps {
	onFinish: () => void;
	employeeId: BusinessAPI.EmployeeVO['employeeId'];
	permission: string;
}

const EmployeeRoleUpdate: React.FC<IEmployeeUpdateProps> = (props) => {
	const { onFinish, employeeId, permission } = props;
	const [openSafeModal, setOpenSafeModal] = useState<boolean>(false);

	return (
		<>
			<SafeModal
				open={openSafeModal}
				onVisibleChange={(openSafeModal) => setOpenSafeModal(openSafeModal)}
			/>
			<ModalForm<BusinessAPI.UserRoleUpdateCmd>
				title="更新员工"
				{...formLayout()}
				grid={true}
				trigger={
					<ButtonAccess permission={permission} type={'link'}>
						分配角色
					</ButtonAccess>
				}
				autoFocusFirstInput
				modalProps={{
					destroyOnHidden: true,
				}}
				submitTimeout={2000}
				//@ts-ignore
				request={async () => {
					const { data } = await business.employee.showEmployee({
						employeeShowQry: { employeeId: employeeId },
					});
					return {
						...data,
						employeeId: employeeId,
					};
				}}
				onFinish={async (values) => {
					const { success, errCode } =
						await business.employee.updateEmployeeRole({
							...values,
							cover: true,
						});
					if (success) {
						if (success && errCode === '401') {
							setOpenSafeModal(true);
							return false;
						}
						message.success('更新员工角色成功');
						onFinish();
						return true;
					}
				}}
			>
				<ProFormText hidden={true} name={'userId'} />

				<ProFormSelect
					name={'roleIdList'}
					label={'角色'}
					placeholder="请选择角色"
					required={true}
					rules={[
						{
							required: true,
							message: '请选择角色',
						},
					]}
					showSearch={true}
					fieldProps={{
						mode: 'multiple',
					}}
					request={async (params) => {
						const data = await business.role.listRole({
							roleListQry: {
								...params,
							},
						});

						return (
							data?.data?.map((item) => ({
								label: item.platformVO?.platformName + '-' + item.name,
								value: item.roleId,
							})) ?? []
						);
					}}
				/>
			</ModalForm>
		</>
	);
};

export default EmployeeRoleUpdate;
