/**
 * 事务页面。 根据事务接口。达到增删发起事务流程
 * 2019年10月23日 09:48:13
 * 钟是志
 *
 * */

import React, { useContext } from 'react';
import * as service from '../publicApiService';
import AuditPage from './AuditPage';
import * as destructionFunc from '../destruction';
import CreateC from '../../ExportComponent/ContextCreate';
import exportHandledInfo from '@/webPublic/FormInsertDiy/AffairPage/AuditPage/exportHandledInfo';
import { connect } from 'dva';
import router from 'umi/router';

@connect(({ keepAlive }) => ({
	keepAlive,
}))
class Index extends React.Component {
	static defaultProps = {
		hasBatchAudit: false, //  是否有批量审核按钮 默认关掉 如果有需要再在外面包一层 2020年5月6日 18:44:11 钟是志
		batchAuditButtonName: '批量审核', // 如果需要批量审核 则直接用 BatchAudit.js 文件
	};

	constructor(props) {
		super(props);
		let pathname = this.props.location.pathname;
		this.state = {
			columns: [],
			dataList: [],
			headerInfo: [],
			workId: this.props.workId || '',
			searchCondition: [],
			pathname,
			dataBaseId: this.props.dataBaseId || '',
			addCondition: [],
			addFields: [], // 新增时填写的字段。
			tableInfo: {}, // 表格配置属性
			allConfigSetInfo: {}, // 返回的数据
		};
		window.callbackSubmitInfoZhiYong = undefined;
		this.refInfo = {
			AuditPage: null,
			ListTab: null,
			List: null,
		};
	}

	setRefInfo = (key, component) => {
		this.refInfo[key] = component;
	};

	getFormDetail = (workId) => {
		const { dataBaseId } = this.state;
		service.getFormDetail(workId).then((response) => {
			if (typeof response.unifiedServicePatternModel === 'undefined') {
				return false;
			}
			this.setState({
				smartFormData: response,
			});
			destructionFunc.destructionGetDetail(response, workId).then((x) => {
				const { addFields, tableInfo, allConfigSetInfo, searchCondition } = x;
				this.setState(
					{
						addFields,
						tableInfo,
						searchCondition,
						allConfigSetInfo,
					},
					() => {
						this.giveDetailColumns();
					},
				);
			});
		});
	};

	giveDetailColumns = () => {
		const { columns, workId, dataBaseId, addFields, tableInfo } = this.state;
		const { showPrint, routerConfig } = this.props;
		const process_status = columns.find((x) => {
			return x.name === 'process_status';
		});
		if (process_status && process_status.dataIndex) {
			process_status.render = (text, record) => {
				return record.statusName || record[process_status.dataIndex];
			};
		}
		columns.push({
			dataIndex: 'operationDiy',
			title: '操作',
			fixed: 'right',
			render: (text, record) => {
				const { refInfo } = this;
				const { dispatch } = this.props;
				function goDetail() {
					const data = {
						activeKey: refInfo.ListTab.state.activeKey || 'tab1',
						pageCurrent: refInfo.List.state.pagination.current || 1,
						searchFormValues: refInfo.List.state.formValues || {},
					};
					dispatch({
						type: 'keepAlive/setAuditPageData',
						payload: {
							path: window.location.href.split('#')[1],
							value: data,
						},
					});
					router.push({
						pathname: './Detail',
						state: {
						  activeType: refInfo.ListTab.state.activeKey === 'tab1' ? '待处理' : '已处理',
              searchFormValues: refInfo.List.state.formValues || {},
							workId,
							dataBaseId,
							record,
							addFields,
							tableInfo,
							showPrint: showPrint || routerConfig.showPrint === '1',
						},
					});
				}
				return <a onClick={goDetail}>{text || '详情'}</a>;
			},
		});
		this.setState({
			columns,
		});
	};

	getColumn = () => {
		const { workId } = this.state;
		service.getColumns(workId).then((response) => {
			if (!response || !Array.isArray(response)) {
				response = [];
			}
			for (let item of response) {
				if (item.dataIndex === 'taskName' && !item.width) {
					item.width = 150; // 29213 资助事务管理/国家三金/国家奖学金审核（高职），界面排版（100661，bdk@2022*$）
				}
				if (item.dataIndex === 'createTime' && !item.width) {
					item.width = 150; // 29213 资助事务管理/国家三金/国家奖学金审核（高职），界面排版（100661，bdk@2022*$）
				}
			}
			response = response.filter((x) => {
				return x.title !== '流程进度';
			});
			if (response && response.length) {
				this.setState(
					{
						columns: response, // 表头
					},
					() => {
						this.getFormDetail(workId);
					},
				);
			}
		});
	};

	componentDidMount() {
		const { pathname } = this.state;
		const { workId } = this.state;
		if (workId) {
			this.getColumn();
		} else {
			service.getId(pathname).then((x) => {
				this.setState(
					{
						workId: x.workId,
						dataBaseId: x.dataBaseId,
					},
					() => {
						this.getColumn();
					},
				);
			});
		}
	}

	render() {
		const {
			workId,
			dataBaseId,
			columns,
			searchCondition,
			addFields,
			allConfigSetInfo,
			tableInfo,
			smartFormData,
		} = this.state;
		const {
			hasBatchAudit,
			batchAuditButtonName,
			showPrint,
			noNeedForm,
			routerConfig: {
				isExport = '0', // 解决禅道 32898 在路由中增加配置项 如果 = '1' 表示 开启已处理数据的导出
			},
		} = this.props;
		if (!workId || !smartFormData) {
			return null;
		}
		const tab2Buttons = [];
		if (isExport === '1') {
			tab2Buttons.push({
				type: 'export',
				name: '导出',
				component: 'Normal',
				handleClick: (selectRows, formValues, getPage, search, columns) => {
					exportHandledInfo({
						columns,
						appId: workId,
            type: 'handled',
					});
				},
			}); // 解决禅道 32366 二级学院审核，所有二级学院审核后在已处理中加导出功能 103152
		}
    const tab1Buttons = [];
    if (isExport === '1' && false) { // 2023年9月27日 钟是志 待处理 增加导出功能 测试性功能只对 北电科生效  接口有问题没法搞
      tab1Buttons.push({
        type: 'export',
        name: '导出',
        component: 'Normal',
        handleClick: (selectRows, formValues, getPage, search, columns) => {
          exportHandledInfo({
            columns,
            appId: workId,
            type: null,
          });
        },
      }); // 解决禅道 32366 二级学院审核，所有二级学院审核后在已处理中加导出功能 103152
    }

		if (Array.isArray(columns)) {
			let d = [];
			for (let item of columns) {
				if (item.dataIndex !== 'operationDiy') {
					d.push({
						key: item.dataIndex,
						title: item.title,
					});
				}
			}
		}
		return (
			<AuditPage
				hasBatchAudit={hasBatchAudit}
				workId={workId}
				dataBaseId={dataBaseId}
				columns={columns}
				addFields={addFields}
				tableInfo={tableInfo}
				allConfigSetInfo={allConfigSetInfo}
				searchCondition={searchCondition}
				batchAuditButtonName={batchAuditButtonName}
				showPrint={showPrint}
				noNeedForm={noNeedForm}
				tab2Buttons={tab2Buttons}
        tab1Buttons={tab1Buttons}
        keepAliveData={this.props.keepAlive?.AuditPageData[window.location.href.split('#')[1]]}
				setRefInfo={this.setRefInfo}
			/>
		);
	}
}

export default function Pr(props) {
	const { routerConfig } = useContext(CreateC);
	return <Index {...props} routerConfig={routerConfig} />;
}
