import { business } from '@/services';
import { ModalForm, ProFormField } from '@ant-design/pro-components';
import { Button } from 'antd';

interface IPermissionJsonProps {
	appId?: BusinessAPI.MenuTreeQry['appId'];
}

export default function PermissionJson(props: IPermissionJsonProps) {
	const { appId } = props;

	return (
		<ModalForm
			title={`权限JSON`}
			trigger={
				<Button type="default" size={'middle'}>
					权限JSON
				</Button>
			}
			autoFocusFirstInput
			modalProps={{
				destroyOnHidden: true,
			}}
			submitTimeout={2000}
			request={async () => {
				const { data } = await business.permission.listPermission({
					permissionListQry: {
						appId,
					},
				});

				console.log('111', data);
				return {
					permission: data,
				};
			}}
		>
			<ProFormField
				fieldProps={{
					style: {
						width: '100%',
					},
				}}
				name={'permission'}
				mode="read"
				valueType="code"
				convertValue={(value) => {
					/**
					 * {
					 *     "permissionId": "1738767267065491458",
					 *     "slug": "mdb-business-dashboard",
					 *     "name": "工作台",
					 *     "appId": "1727816458802704385"
					 *   }
					 *
					 *   value 是一个集合，集合的每个项是上述json内容，现在需要写一个方法得到最后的结果为 json 对象，其中每项的结果为 MDB_BUSINESS_DASHBOARD: 'mdb-business-dashboard'
					 */
					let code = 'export const PERMISSION = {\n';
					value.forEach((item: any) => {
						code += `\t// ${item.name}\n`;
						code += `\t${item.slug
							.toUpperCase()
							.replace(/-/g, '_')}: '${item.slug}',\n`;
					});
					code += '\n}';

					code += '\n';

					code += 'public class PermissionConstant {\n';

					value.forEach((item: any) => {
						code += `\t// ${item.name}\n`;
						code += `\tpublic static final String ${item.slug
							.toUpperCase()
							.replace(/-/g, '_')} = "${item.slug}";\n`;
					});
					code += '\n}';

					return code;
				}}
			/>
		</ModalForm>
	);
}
