import React, { Fragment } from 'react';
import { Divider, message, Modal, Popconfirm } from 'antd';
import moment from 'moment';
import ExportInfo from '../Export/index';
import { date, getFormArrayConfig } from '../config/index';
import { handleColumns } from '../AffairPage/destruction';
import ButtonDiy from '@/baseComponent/ButtonDiy';
import Shell from '../Shell';
import FormArray from '../AffairPage/component/FormArray';
import Edit from '../Edit/index';
import ImportUtil from '../ImportUtil/ImportUtil';
import SearchDom from '@/highOrderComponent/SearchDom';
import StandardTable from '@/components/StandardTable';
import { getHead, fetchData, deleteItem, add, getDetailId } from './services';
import router from 'umi/router';

const getValue = (obj) =>
	Object.keys(obj)
		.map((key) => obj[key])
		.join(',');

const CreateForm = (props) => {
	const {
		modalVisible,
		handleAdd,
		formData,
		isAdd,
		handleModalVisible,
		formItem,
		changeFormData,
	} = props;

	// 通过回调
	const okHandle = () => {
		handleAdd({}, isAdd);
	};
	// 需要获取动态表单
	return (
		<Modal
			width="1000px"
			maskClosable={false}
			destroyOnClose
			title={isAdd ? '新增' : '编辑'}
			visible={modalVisible}
			onOk={okHandle}
			onCancel={() => handleModalVisible()}>
			<FormArray
				config={getFormArrayConfig(formItem)}
				value={formData}
				fileSpan={{ big: 2, small: 2 }}
				changeValue={changeFormData}
			/>
			<div style={{ clear: 'both' }} />
		</Modal>
	);
};

class FormList extends React.Component {
	constructor(props) {
		super(props);

		this.state = {
			modalVisible: false,
			formData: null,
			formItem: [],
			searchConfig: [],
			formValues: {},
			isAdd: false,
			selectedRows: [],
			primaryKey: null,
			showEdit: false,
			pageData: {
				list: [],
				pagination: {},
			},
		};
		this.columns = [];
	}

	// 渲染值
	componentDidMount() {
		this.getTableHead();
	}

	getTableHead = () => {
		const { objId, Authority, handleColumnsDiy } = this.props;
		getHead({ dataObjId: objId }, (datas) => {
			if (!datas) return;
			let findPrimaryKey = datas.find((x) => {
				return x.isPrimaryKey === true;
			});
			if (findPrimaryKey) {
				this.setState({
					primaryKey: findPrimaryKey.name,
				});
			} else {
				console.error('没有数据主键,无法执行删除操作');
			}
			datas = datas.filter((x) => {
				return x.isHidden !== true;
			});
			for (let item of datas) {
				item.extendType = item.extendTypeId;
				item.dataIndex = item.name;
				item.dataType = item.type;
			}
			datas = handleColumns(datas);
			if (handleColumnsDiy) {
				datas = handleColumnsDiy(datas);
			}
			if (Authority && Authority.auditDetail) {
				//流程审核详情 和 编辑,查看 不能 同时存在.
				datas.push({
					dataIndex: 'auditProcessDetail',
					title: '审核详情',
					fixed: datas.length > 12 ? 'right' : false,
					render: (text, record) => {
						return (
							<a
								onClick={() => {
									this.getIdByCode(record.process_biz_key);
								}}>
								流程审核详情
							</a>
						);
						/*return (<Link to={
                {
                  pathname: './Detail',
                  state: {
                    record: {
                      id: record.process_biz_key,
                    },
                  },
                }}>
                详情
              </Link>);*/
					},
				});
			}

			this.columns = datas;
			this.setState({ formItem: datas });
			let searchConfig = [];
			for (let item of datas) {
				if (item.isShowQuery) {
					let sear = getFormArrayConfig([item]);
					if (!Array.isArray(sear)) {
						return false;
					}
					delete sear[0].required;
					delete sear[0].placeholder;
					searchConfig.push(sear[0]);
				}
			}
			this.setState({
				searchConfig,
			});
			if (Authority && Authority.edit) {
				//编辑功能
				datas.push({
					dataIndex: 'operationEdit',
					title: '编辑',
					fixed: 'right',
					width: 60,
					render: (text, record) => {
						return <a onClick={this.modify.bind(this, record)}>编辑</a>;
					},
				});
			}
			this.getPage();
		});
	};

	getIdByCode = (code) => {
		getDetailId({ code }, (res) => {
			router.push({
				pathname: './Detail',
				state: {
					record: { id: res.id },
				},
			});
		});
	};

	modify = (record) => {
		const { formItem } = this.state;
		if (formItem.length < 10 || true) {
			this.setState({
				formData: { ...record },
				modalVisible: true,
				isAdd: false,
			});
		} else {
			this.setState({
				formData: { ...record },
				showEdit: true,
			});
		}
	};

	delete = (record) => {
		const { objId } = this.props;
		// 找出主键
		const { primaryKey } = this.state;
		const Keys = {};
		Keys[primaryKey] = record[primaryKey];
		deleteItem({ keys: JSON.stringify(Keys), objId }, () => {
			this.getPage();
		});
	};

	changeFormData = (value, key) => {
		this.setState(({ formData }) => ({ formData: { ...formData, [key]: value } }));
	};

	getPage = (params, values) => {
		const { objId } = this.props;
		const { formValues, pageData: pagination } = this.state;
		if (params == null) {
			params = {
				pageNo: pagination.current ? pagination.current : 1,
				pageSize: pagination.pageSize ? pagination.pageSize : 10,
				...values,
			};
		}
		params = {
			...params,
			query: JSON.stringify(formValues),
		};
		fetchData({ ...params, dataObjId: objId }, (res) => {
			if (!res.rows) {
				console.error('分页接口rows返回null报错');
			}
			this.setState({
				pageData: {
					list: res.rows,
					pagination: {
						current: res.pageNo,
						pageSize: res.pageSize,
						total: Number(res.total),
					},
				},
			});
		});
	};

	handleStandardTableChange = (pagination, filtersArg, sorter) => {
		const filters = Object.keys(filtersArg).reduce((obj, key) => {
			const newObj = { ...obj };
			newObj[key] = getValue(filtersArg[key]);
			return newObj;
		}, {});

		const params = {
			pageNo: pagination.current,
			pageSize: pagination.pageSize,
			...filters,
		};
		if (sorter.field) {
			params.sorter = `${sorter.field}_${sorter.order}`;
		}
		this.getPage(params);
	};

	handleAdd = (fields, isAdd) => {
		const { formData } = this.state;
		const { objId } = this.props;
		add({ params: formData, objId, isAdd }, () => {
			message.success('操作成功');
			this.setState({
				modalVisible: false,
			});
			this.getPage();
		});
	};

	handleModalVisible = () => {
		this.setState({
			modalVisible: this.state.modalVisible ? false : true,
			formData: {},
		});
	};

	add = () => {
		const { formItem } = this.state;
		if (formItem.length < 10 || true) {
			this.setState({
				modalVisible: true,
				formData: {},
				isAdd: true,
			});
		} else {
			this.setState({
				formData: {},
				showEdit: true,
				isAdd: true,
			});
		}
	};

	handleSelectRows = (rows) => {
		this.setState({
			selectedRows: rows,
		});
	};

	batchDelete = (e) => {
		const { objId } = this.props;
		const { selectedRows, formItem } = this.state;
		if (!selectedRows || selectedRows.length < 1) {
			message.warning('请选择您要删除的数据');
			return false;
		}
		// 找出主键
		const { primaryKey } = this.state;
		let Keys = selectedRows.map((x) => {
			return x[primaryKey];
		});
		deleteItem(
			{
				keys: JSON.stringify({ [primaryKey]: Keys.join(',') }),
				objId,
				//  isSelf: true,
			},
			() => {
				this.setState({
					selectedRows: [],
				});
				this.getPage();
			},
		);
	};

	goBack = () => {
		router.goBack();
	};

	formStateChange = (value, key) => {
		this.setState(({ formValues }) => ({ formValues: { ...formValues, [key]: value } }));
	};

	resetFormValues = () => {
		this.setState({
			formValues: {},
		});
	};

	render() {
		const {
			modalVisible,
			selectedRows,
			formItem,
			isAdd,
			pageData,
			showEdit,
			formData,
			primaryKey,
			formValues,
			searchConfig,
		} = this.state;
		const { objId, Authority } = this.props;
		const parentMethods = {
			handleAdd: this.handleAdd,
			handleModalVisible: this.handleModalVisible,
			formData,
			formItem,
			isAdd,
			changeFormData: this.changeFormData,
		};
		return (
			<>
				{showEdit ? (
					<Edit
						id={objId}
						recordId={formData[primaryKey]}
						recordKey={primaryKey}
						returnThis={() => {
							this.setState({
								showEdit: false,
							});
							this.getPage();
						}}
					/>
				) : (
					<Fragment>
						{searchConfig.length > 0 ? (
							<SearchDom
								formStateChange={this.formStateChange}
								formValues={formValues}
								getPage={this.getPage}
								resetFormValues={this.resetFormValues}
								config={{ condition: searchConfig, fromTab: true }}
							/>
						) : null}
						<Shell styleShell={searchConfig.length > 0 ? {} : { marginTop: 0 }}>
							<div
								style={{
									paddingLeft: '10px',
									paddingTop: '10px',
								}}>
								{Authority && Authority.add === false ? null : (
									<ButtonDiy
										icon="plus"
										className="primaryBlue"
										handleClick={this.add}
										name="新建"
									/>
								)}
								{Authority && Authority.delete === false ? null : (
									<ButtonDiy handleClick={this.batchDelete} name="批量删除" />
								)}
								{Authority && Authority.exportUtil === false ? null : <ExportInfo objId={objId} />}
								{Authority && Authority.importUtil === false ? null : (
									<ImportUtil objId={objId} callback={this.getPage} />
								)}
							</div>
							<StandardTable
								rowKey={primaryKey}
								data={pageData}
								scroll={{ x: true }}
								columns={this.columns}
								selectedRows={selectedRows}
								onSelectRow={this.handleSelectRows}
								onChange={this.handleStandardTableChange}
							/>
						</Shell>
					</Fragment>
				)}

				<CreateForm {...parentMethods} modalVisible={modalVisible} />
			</>
		);
	}
}

export default FormList;
