/**
 * onestop 流程详情
 * 公共代码 - 谨慎修改
 * 钟是志
 * */
import React, { Component } from 'react';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import Shell from '@/webPublic/one_stop_public/App/ButtonDiy/Shell';
import ButtonDiy from '@/webPublic/one_stop_public/App/ButtonDiy/ButtonDiy';
import router from 'umi/router';
import { getToken } from '@/utils/authority';
import config from '@/config/config';
import { message, Modal, notification, Popconfirm, Button } from 'antd';
import DetailOneStop from '@/webPublic/one_stop_public/DetailForAudit/IframeForDetail';
import { getIsBei_Dian, getIsGui_Jian } from '@/webPublic/zyd_public/utils/utils';
import { getUrlInfo } from '@/webPublic/one_stop_public/DetailForAudit/utils';
import { getWaitIds } from '@/webPublic/Services';

window.iframeParentComponent = {
	Modal,
	message,
	notification,
	Popconfirm,
};

export default class Detail extends Component {
	constructor(props) {
		super(props);
		const { state } = this.props.location;
		let id = '';
		let code = '';
		if (state && state.record) {
			if (state.record.id) {
				id = state.record.id;
			}
			if (state.record.code) {
				code = state.record.code;
			}
		}
		if (!id) {
			id = getUrlInfo().id;
		}
		if (!code) {
			code = getUrlInfo().code;
		}
		this.state = {
			id,
			code,
			showAll: props.from !== 'onestopApp2.0' && getUrlInfo().showAll !== 'false',
			allWaitIds: [], // 解决禅道 3604 多人并行 【1.0低代码】审核页面新增，上一页下一页功能
		};
    window.zdyTableTemplateWillMountProps = true;
	}

	getWaitInfos() {
		const { state } = this.props.location;
		const { from = '' } = this.props;
		const { code } = this.state;
		if (state && state.activeType === '待处理' && getIsBei_Dian() && code && from === 'ActiveMenuComponent.js') {
			// 后续再考虑 开放给其他学校.
			getWaitIds({
				appId: state.workId, //
				...state.searchFormValues, // 搜索条件
			}).then((res) => {
				if (res && Array.isArray(res)) {
				  res.forEach((g, index) => {
				    g.taskId = g.id;
				    delete g.id;
				    if(g.code === code){
				      g.rightNow = true;
				      if(index > 0){
				        res[index - 1].prev = true;
              }
				      if(index < res.length - 1){
				        res[index + 1].next = true;
              }
            }
          });

					this.setState({
						allWaitIds: res,
					});
				}
			});
		}
	}

	componentDidMount() {
		this.getWaitInfos();
		window.addEventListener(
			'message',
			(event) => {
				if (event.data && event.data.indexOf && event.data.indexOf('iframeDetailHeight') > -1) {
					const height = Number(event.data.split('-')[1]);
					const dom = document.getElementById('detailIframeId');
					if (dom) {
						document.getElementById('detailIframeId').height = height + 50;
					}
				}
			},
			false,
		);
	}

	showAll = () => {
		this.setState({
			showAll: true,
		});
	};

	getButtons = () => {
		const { showAll, allWaitIds } = this.state;
		const { hiddenButton, fromCheckRecord, location: { state } } = this.props;
		if (hiddenButton) {
			return null;
		}
		const nextForm = allWaitIds.find((x) => x.next) || null;
		const prevForm = allWaitIds.find((x) => x.prev) || null;
		console.log(window.zdyTableTemplateWillMountProps.applyDetailsBtns);
		return (
			<>
				<Shell>
					<div
						style={{
							height: '54px',
							padding: '12px 0 12px 12px',
						}}>
						{showAll ? (
							<ButtonDiy
								name="返回"
								className="defaultBlue"
								handleClick={() => {
									if (fromCheckRecord) {
										window.keepAliveCheckRecord.showList();
									} else {
										router.goBack();
									}
								}}
								icon="arrow-left"
							/>
						) : null}
						<ButtonDiy
							name={'全屏查看'}
							className="defaultBlue"
							handleClick={() => {
								document.getElementById('detailIframeId').requestFullscreen();
							}}
						/>
            {
              !!prevForm && (
              <ButtonDiy
                name={'上一条'}
                className="defaultBlue"
                handleClick={() => {
                  router.replace({
                    pathname: './Detail',
                    state: {
                      ...state,
                      record: {
                        id: undefined,
                        code: prevForm.code,
                      },
                      taskId: prevForm.taskId,
                    },
                  });
                }}
              />
              )
            }
            {
              !!nextForm && (
                <ButtonDiy
                  name={'下一条'}
                  className="defaultBlue"
                  handleClick={() => {
                    router.replace({
                      pathname: './Detail',
                      state: {
                        ...state,
                        record: {
                          id: undefined,
                          code: nextForm.code,
                        },
                        taskId: nextForm.taskId,
                      },
                    });
                  }}
                />
              )
            }

					</div>
				</Shell>
			</>
		);
	};

	render() {
		const { from, hiddenButton } = this.props;
		const { id, showAll, code } = this.state;
		const url = config.onestopPC.split('/#/');
		let showPrint = this.props.location?.state?.showPrint;
		if (getIsGui_Jian() && !showPrint) {
			// 27590 寝室调整管理-寝室调整申请，详情的打印预览按钮不见了210301080119-122617
			// 贵建把打印预览显示出来
			showPrint = true;
		}
		let iframeUrl = `${url[0]}/#/IframeForDetail?id=${id}&token=${getToken()}`;
		if (showPrint) {
			iframeUrl = iframeUrl + '&showPrint=true';
		}
		if (from === 'onestopApp2.0') {
			iframeUrl =
				config.gateWayPort +
				`/portal/#/showAuditIframe?id=${id}&code=${code}&hasSingle=false&token=${getToken()}&isPrint=false`;
		}
		// iframeUrl = `http://localhost:8000/onestop/IframeForDetail?id=${id}&token=${getToken()}`;
		// console.log(showPrint);
		return (
			<PageHeaderWrapper title="">
				{this.getButtons()}
				<Shell>
					{from === 'onestopApp2.0' ? (
						<iframe
							src={iframeUrl}
							frameBorder={0}
							id="detailIframeId"
							name="applyIframe"
							marginWidth="0"
							marginHeight="0"
							onLoad={this.showAll}
							allowtransparency="yes"
							seamless
							scrolling={'no'}
							style={{
								width: '100%',
								overflowY: 'hidden',
								minHeight: '80vh',
							}}
						/>
					) : (
						<div id={'detailIframeId'} data-page-info={'detail'}>
							<DetailOneStop id={id} {...this.props} code={code} showPrint={showPrint || false} />
						</div>
					)}
				</Shell>
				{this.getButtons()}
			</PageHeaderWrapper>
		);
	}
}
