import React, { useEffect, useState, useRef } from 'react';
import ZdyTable from '@/webPublic/one_stop_public/Table';
import styles from './index.less';
import { fetchTemplateByCode, fetchTableItem } from '@/webPublic/Services';
import { isJSON } from '@/webPublic/zyd_public/utils/utils';
import SelectPerson from '@/webPublic/FormInsertDiy/ExportComponent/SelectPerson/Index';
import Detail from '@/webPublic/FormInsertDiy/AffairPage/Detail';


const showDiv = () => {
  document.getElementById('listZdyTable').style.position = 'static';
  document.getElementById('listZdyTable').style.zIndex = 'auto';
};

const hideDiv = () => {
  document.getElementById('listZdyTable').style.position = 'absolute';
  document.getElementById('listZdyTable').style.zIndex = '-10';
};

export default function RenderForm({ get = 'web', isCg = 'yes', style, ...rest }) {
	let content = rest?.postData?.unifiedServicePatternModel?.content;
	if (isJSON(content)) {
		content = JSON.parse(content);
	}
	const tableRoot = useRef();
	const [showPageType, setShowPageType] = useState(0);
	const [pageProps, setPageProps] = useState({});
	useEffect(() => {
		const timerId = setTimeout(() => {
			// 修改样式
			const div = tableRoot.current && tableRoot.current.root;
			if (div) {
				div.style.overflow = 'unset';
			}
			let new_element = document.createElement('style');
			new_element.innerHTML = `main>div>#web_table .login-form>div>div>div{
      overflow: inherit !important;
      }`;
			document.body.appendChild(new_element);
		}, 0);

		window.keepAliveCheckRecord = {
			showList: (props) => {
        setShowPageType(0);
        setPageProps({});
        showDiv();
      },
			showDetail: (p) => {
        setPageProps({
          ...p,
          history: {...p},
        });
        setShowPageType(1);
				console.log(p);
        hideDiv();
			},
		};

		return () => {
			clearTimeout(timerId);
		};
	}, []);
	if (!content) {
		return null;
	}

	// console.log(showPageType);

	return (
		<>
			<div className={styles.zyd_onestop_style_class} style={style} id={'listZdyTable'}>
				<ZdyTable
					ref={tableRoot}
					get={get}
					{...rest}
					isQuery={true}
					init={undefined}
					{...content}
				/>
				<SelectPerson />
			</div>
			{showPageType === 1 && <Detail fromCheckRecord={true}
                                     {...pageProps} />}
		</>
	);
}

/**
 * 根据表单code渲染表单
 * @param {Object} content 表单内容，传入对象
 * @param {String} templateCode 表单模板
 */
export function RenderFormByContent({ content, templateCode, form, get, isCg }) {
	const [formTemplate, setFormTemplate] = useState();
	useEffect(
		() => {
			fetchTemplateByCode(templateCode).then((res) => {
				if (res) {
					setFormTemplate(res);
				}
			});
		},
		[templateCode],
	);

	return formTemplate ? (
		<RenderForm
			get={get}
			isCg={isCg}
			postData={{
				content: JSON.stringify(content),
				unifiedServicePatternModel: formTemplate,
			}}
			form={form}
		/>
	) : null;
}

/**
 *渲染元数据库中的某条数据
 * @param {Object} objId 元数据库id
 * @param {String} dataTypeKey 元数据库表格键
 * @param {String} dataTypeValue 键对应的值
 * @param {Function} onLoad 数据加载的回调函数
 */
export function RenderFormByObjId({
	objId,
	dataTypeKey,
	dataTypeValue,
	onLoad,
	templateCode,
	form,
	get,
	isCg,
}) {
	const [content, setContent] = useState({});
	useEffect(
		() => {
			fetchTableItem({
				dataObjId: objId,
				key: dataTypeKey,
				value: dataTypeValue,
			}).then((res) => {
				setContent(res || {});
				if (onLoad) {
					onLoad(res);
				}
			});
		},
		[objId, dataTypeKey, dataTypeValue],
	);

	return (
		<RenderFormByContent
			get={get}
			isCg={isCg}
			content={content}
			templateCode={templateCode}
			form={form}
		/>
	);
}
