import React, { useCallback, useState, useEffect } from 'react';
import { Modal, Alert, Transfer, message } from 'antd';
import qs from 'qs';
import { getToken } from '@/utils/authority';
import reqwest from 'reqwest';
import ButtonDiy from '@/baseComponent/ButtonDiy';

function getThisInfo(data, url) {
	return reqwest({
		url,
		type: 'json',
		method: 'post',
		data: JSON.stringify(data),
		headers: {
			Accept: 'application/json;charset=UTF-8',
			'Content-Type': 'application/json',
		},
		crossOrigin: true,
		withCredentials: false,
		error: (err) => {
			message.warning('网络故障');
		},
		success: (res) => {
			return res;
		},
	});
}

function formateObjToArr(obj) {
	return Object.keys(obj).reduce((acc, key) => acc.concat({ key, title: obj[key] }), []);
}

/**
 * text: '按钮名称' 默认 自定义导出
 * modalProps: '弹窗props'
 * */

export default function DynamicExportButton({
	text,
	modalProps,
	serviceBean,
	serviceKey,
	api,
	serviceParam,
}) {
	const [visible, setVisible] = useState(false);
	const [targetKeys, setTargetKeys] = useState([]);
	const [columns, setColumns] = useState([]);
	const handleChange = useCallback((keys) => {
		setTargetKeys(keys);
	}, []);
	function btnClick() {
		setVisible(!visible);
	}

	function defaultUrl() {
		return api + '/exportApi';
	}

	function getColumns() {
		let url = defaultUrl() + '/findExportColumnHeader?token=' + getToken();
		let data = {
			serviceKey,
			serviceBean,
			serviceParam,
		};
		getThisInfo(data, url).then((y) => {
			if (y) {
				setColumns(formateObjToArr(y));
			}
		});
	}

	function exportExcel() {
		let data = {
			serviceKey,
			serviceBean,
			serviceParam,
			fieldNames: targetKeys.length ? targetKeys : columns.map((y) => y.key),
		};

		let url = defaultUrl() + '/exportData?token=' + getToken();
		getThisInfo(data, url).then((y) => {
			if (y) {
				let data = {
					serviceBean,
					serviceKey,
					fileKey: y.cacheKey,
					token: getToken(),
				};
				window.open(defaultUrl() + '/downLoadExcel?' + qs.stringify(data));
				setVisible(false);
				message.success('正在下载导出文件');

				return true;
			}
		});
	}

	useEffect(
		() => {
			if (visible) {
				getColumns();
			}
		},
		[visible],
	);
	return (
		<>
			<ButtonDiy name={text} type="default" className="defaultBlue" handleClick={btnClick} />
			<Modal
				visible={visible}
				width={1000}
				title="自定义导出"
				bodyStyle={{
					padding: '24px 36px',
					display: 'flex',
					justifyContent: 'center',
					alignItems: 'center',
					flexDirection: 'column',
				}}
				{...modalProps}
				onOk={exportExcel}
				onCancel={() => setVisible(false)}>
				<Transfer
					showSearch
					style={{
						flex: '1',
						display: 'flex',
						justifyContent: 'center',
						alignItems: 'center',
						width: '100%',
					}}
					dataSource={columns}
					titles={['可选项目', '已选项目']}
					targetKeys={targetKeys}
					listStyle={{ height: 400, flex: 1 }}
					onChange={handleChange}
					operations={['增加导出项', '移除导出项']}
					render={(item) => item.title || ''}
				/>
				<Alert
					showIcon
					style={{ marginTop: 12 }}
					message="在不选择任何导出项时，默认导出所有项目。"
					type="warning"
				/>
			</Modal>
		</>
	);
}

DynamicExportButton.defaultProps = {
	text: '自定义导出',
};
