import { BizContainer, BizValueType, ModeType } from '@/components';
import useSearch from '@/models/useSearch';
import { business } from '@/services';
import { filterTreeAndKeepParents, findParentChains } from '@/utils/tree';
import { useIntl } from '@@/exports';
import {
	ProColumns,
	ProFormSelect,
	ProFormText,
	ProFormTextArea,
	ProFormTreeSelect,
} from '@ant-design/pro-components';
import { ProDescriptionsItemProps } from '@ant-design/pro-descriptions';
import { TreeSelect } from 'antd';
import React, { useEffect, useState } from 'react';

export interface IRoleListProps {
	ghost?: boolean;
	search?: boolean;
	mode?: ModeType;
	trigger?: () => React.ReactNode;
	onValueChange?: () => void;
}

export default function RoleList(props: IRoleListProps) {
	const {
		mode = 'page',
		ghost = false,
		search = true,
		onValueChange,
		trigger,
	} = props;
	const intl = useIntl();
	const intlPrefix = 'role';

	const { getPlatformList } = useSearch();
	const [menuTree, setMenuTree] = useState<BusinessAPI.TreeLong[]>();

	const [platformList, setPlatformList] = useState<BusinessAPI.PlatformVO[]>();

	const [platformId, setPlatformId] =
		useState<BusinessAPI.PlatformVO['platformId']>('');

	const initPlatform = async () => {
		const { data: platformList } = await business.platform.listPlatform({
			platformListQry: {},
		});

		setPlatformList(platformList);
		if (platformList) {
			setPlatformId(platformList[0].platformId);
		}
	};

	useEffect(() => {
		initPlatform().then();
	}, []);

	if (!platformList) {
		return;
	}

	const formContext = [
		<ProFormSelect
			key={'platformId'}
			label={intl.formatMessage({
				id: intlPrefix + '.form.platformId.label',
			})}
			placeholder={intl.formatMessage({
				id: intlPrefix + '.form.platformId.placeholder',
			})}
			name={'platformId'}
			required={true}
			rules={[
				{
					required: true,
					message: intl.formatMessage({
						id: intlPrefix + '.form.platformId.required',
					}),
				},
			]}
			request={async (params) => await getPlatformList(params)}
			fieldProps={{
				fetchDataOnSearch: false,
				showSearch: true,
				autoClearSearchValue: true,
				fieldNames: {
					label: 'platformName',
					value: 'platformId',
				},
			}}
		/>,
		<ProFormText
			key={'slug'}
			label={intl.formatMessage({
				id: intlPrefix + '.form.slug.label',
			})}
			placeholder={intl.formatMessage({
				id: intlPrefix + '.form.slug.placeholder',
			})}
			name={'slug'}
			required={true}
			fieldProps={{
				showCount: true,
				maxLength: 50,
			}}
			rules={[
				{
					required: true,
					message: intl.formatMessage({
						id: intlPrefix + '.form.slug.required',
					}),
				},
			]}
		/>,
		<ProFormText
			key={'name'}
			label={intl.formatMessage({
				id: intlPrefix + '.form.name.label',
			})}
			placeholder={intl.formatMessage({
				id: intlPrefix + '.form.name.placeholder',
			})}
			name={'name'}
			required={true}
			fieldProps={{
				showCount: true,
				maxLength: 50,
			}}
			rules={[
				{
					required: true,
					message: intl.formatMessage({
						id: intlPrefix + '.form.name.required',
					}),
				},
			]}
		/>,
		<ProFormTreeSelect
			key={'menuId'}
			label={intl.formatMessage({
				id: intlPrefix + '.form.menuId.label',
			})}
			placeholder={intl.formatMessage({
				id: intlPrefix + '.form.menuId.label',
			})}
			name="menuId"
			required={true}
			rules={[
				{
					required: true,
					message: intl.formatMessage({
						id: intlPrefix + '.form.menuId.required',
					}),
				},
			]}
			dependencies={['platformId', 'appId']}
			request={async (params) => {
				const response = await business.menu.treeMenu(params);
				setMenuTree(response.data);
				return response.data || [];
			}}
			fieldProps={{
				fieldNames: {
					label: 'name',
					children: 'routes',
					value: 'menuId',
				},
				popupMatchSelectWidth: false,
				treeCheckable: true,
				treeCheckStrictly: false,
				showCheckedStrategy: TreeSelect.SHOW_ALL,
				placeholder: '搜索菜单',
				maxTagCount: 10,
				treeDefaultExpandAll: true,
			}}
		/>,
		<ProFormTextArea
			key={'description'}
			label={intl.formatMessage({
				id: intlPrefix + '.form.description.label',
			})}
			name={'description'}
		/>,
	];

	const columns: ProColumns<BusinessAPI.RoleVO, BizValueType>[] = [
		{
			title: intl.formatMessage({
				id: intlPrefix + '.column.name',
			}),
			fieldProps: {
				placeholder: intl.formatMessage({
					id: intlPrefix + '.column.name.placeholder',
				}),
			},
			dataIndex: 'name',
			key: 'name',
		},
		{
			title: intl.formatMessage({
				id: intlPrefix + '.column.slug',
			}),
			fieldProps: {
				placeholder: intl.formatMessage({
					id: intlPrefix + '.column.slug.placeholder',
				}),
			},
			dataIndex: 'slug',
			key: 'slug',
		},
		{
			title: intl.formatMessage({
				id: intlPrefix + '.column.description',
			}),
			dataIndex: 'description',
			search: false,
		},
		{
			title: intl.formatMessage({
				id: intlPrefix + '.column.createdAt',
			}),
			dataIndex: 'createdAt',
			search: false,
		},
	];

	const detailColumns: ProDescriptionsItemProps<
		BusinessAPI.RoleVO,
		BizValueType
	>[] = columns as ProDescriptionsItemProps<BusinessAPI.RoleVO, BizValueType>[];

	return (
		<BizContainer<
			typeof business.role,
			BusinessAPI.RoleVO,
			BusinessAPI.RolePageQry,
			BusinessAPI.RoleCreateCmd,
			BusinessAPI.RoleUpdateCmd
		>
			rowKey={'roleId'}
			permission={'operation-role'}
			func={business.role}
			method={'role'}
			methodUpper={'Role'}
			intlPrefix={intlPrefix}
			modeType={mode}
			onValueChange={onValueChange}
			container={{
				ghost,
				fieldProps: {
					tabActiveKey: platformId,
					onTabChange: (platformId) => {
						setPlatformId(platformId as BusinessAPI.PlatformVO['platformId']);
					},
					tabList: [
						...platformList.map((platformVO) => ({
							key: platformVO.platformId,
							tab: platformVO.platformName,
						})),
					],
				},
			}}
			page={{
				fieldProps: {
					ghost,
					//@ts-ignore
					search,
					params: {
						platformId: platformId,
					},
				},
				columns,
			}}
			create={{
				formType: 'drawer',
				initValues: {
					platformId: platformId,
				},
				formContext,
				trigger,
				request: async (formData) => {
					formData.menuId = findParentChains(menuTree, formData.menuId);
					console.log('formData', formData);
					const { success } = await business.role.createRole(formData);

					return success;
				},
			}}
			update={{
				formType: 'drawer',
				formContext,
				trigger,
				transform: async (data) => {
					const { data: menuData } = await business.menu.treeMenu({
						menuTreeQry: {},
					});
					setMenuTree(menuData);

					data.menuId = filterTreeAndKeepParents(menuData, data.menuId);
					return data;
				},
				request: async (formData) => {
					formData.menuId = findParentChains(menuTree, formData.menuId);
					const { success } = await business.role.updateRole(formData);

					return success;
				},
			}}
			destroy={{}}
			detail={{
				formType: 'drawer',
				columns: detailColumns,
				trigger,
			}}
		/>
	);
}
