import React, { Component, Fragment } from 'react';
import SearchDom from '@/highOrderComponent/SearchDom';
import ButtonListDom from '../ButtonListDom';
import Shell from '@/baseComponent/Shell';
import StandardTable from '@/components/StandardTable';
import PropTypes from 'prop-types';
import { deepCopy } from '@/baseComponent/utils';
import { handleAudit } from '../publicApiService';
import { handleColumns } from '@/webPublic/FormInsertDiy/AffairPage/destruction';
import { connect } from 'dva';

@connect(({ auditPageData }) => {
  return {
    auditPageData,
  }
})
export default class List extends Component {
	constructor(props) {
		super(props);
		const { keepAliveData } = props;
		this.state = {
			list: [],
			selectRows: [],
			formValues: this.giveDefaultValue(props),
			loading: true,
			sortGetPageFields: {},
			pagination: {
				current: (keepAliveData && keepAliveData.pageCurrent) || 1,
				total: 1,
				pageSize: this.props.listConfig.pageSize || 10,
				pageSizeOptions: ['10', '20', '50', '100', '500'],
				showQuickJumper: true,
				onShowSizeChange: (current, size) => {
					this.pageChange(current, size);
				},
				onChange: (current, size) => {
					this.pageChange(current, size);
				},
			},
		};
		this.trueSearchParams = {}; // 真实的搜索条件
	}

	giveDefaultValue = (props) => {
		// 如果设置了 giveFieldsToFormValues 则将默认值赋值给formValues
		let formValues = {};
		if (
			props.pageSearch &&
			props.pageSearch.search &&
			props.pageSearch.search.giveFieldsToFormValues
		) {
			for (let x in props.pageSearch.search.field) {
				if (props.pageSearch.search.field[x].required === true) {
					formValues[x] = props.pageSearch.search.field[x].defaultValue;
				}
			}
		}
		if (props.keepAliveData?.trueSearchParams) {
			formValues = {
				...formValues,
				...props.keepAliveData?.trueSearchParams,
			};
		}
		return formValues;
	};

	giveGetPageFields = () => {
		const { listConfig, pageSearch, beforeGetPage } = this.props;
		const { pagination, formValues } = this.state;
		const search = pageSearch.search;
		let data = deepCopy(formValues);
		// /** 如果配置了默认值 则 加进去 **/
		// for (let item in search.field) {
		// 	let one = search.field[item];
		// 	if (one.required && typeof data[item] === 'undefined') {
		// 		/**
		// 		 * 存在必填项 且当前必填项没有值时 则传入. 如果必填项有值则不需要修改
		// 		 * */
		// 		data[item] = one.defaultValue;
		// 	}
		// }
		if (listConfig.paging) {
			// 是否分页
			data.pageSize = pagination.pageSize;
			data.pageNo = pagination.current;
		}
		if (search.beforeGetPage) {
			data = search.beforeGetPage(data);
		}
		return data;
	};

	getPage = () => {
		const { listConfig, pageSearch, workId } = this.props;
		const { pagination, sortGetPageFields } = this.state;
		const { search } = pageSearch;
		let data = this.giveGetPageFields();
		if (!data) {
			return false;
		}
		if (search.handleSort) {
			data = {
				...data,
				...sortGetPageFields, // 增加排序的搜索条件
			};
		}
		this.setState({
			list: [],
			loading: true,
		});

		if (search.beforeSearchData && typeof search.beforeSearchData === 'function') {
			data = search.beforeSearchData(data, { ...this.props });
		}

		if (search.beforeSearchDataOutSide && typeof search.beforeSearchDataOutSide === 'function') {
			data = search.beforeSearchDataOutSide(data, { ...this.props });
		}
    this.trueSearchParams = { ...data };
		delete this.trueSearchParams.pageNo;
		delete this.trueSearchParams.pageSize;
    this.props.dispatch({
      type: 'auditPageData/setSearchParams',
      payload: this.trueSearchParams,
    });
		search.getPageService({ ...data, appId: workId }).then((response) => {
			this.setState({
				loading: false,
			});
			if (
				!response ||
				(search.paging && typeof response.total === 'undefined') ||
				response.errMsg
			) {
				return false;
			}
			if (listConfig.paging) {
				pagination.total = Number(response.total);
			}
			if (typeof search.responseCallBack !== 'undefined') {
				response = search.responseCallBack(response);
			}
			this.setState({
				list: response.rows || response,
				selectRows: [],
				pagination: pagination,
			});
		});
	};

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

	pageChange = (current, size) => {
		this.setState(
			{
				pagination: {
					...this.state.pagination,
					current: current,
					pageSize: size,
				},
			},
			() => {
				this.getPage();
			},
		);
	};

	formStateChange = (value, key) => {
		const { search } = this.props.pageSearch;
		const { condition } = search;
		let oldValue = this.state.formValues;
		oldValue[key] = value;
		/**
		 * 如果设置了beforeChange回调函数 则调用此回调函数改变另外的字段的值
		 * */
		const index = condition.findIndex((item) => {
			return item.key === key;
		});
		if (index !== -1) {
			const thisConfig = condition[index];
			if (thisConfig.beforeChange) {
				oldValue = thisConfig.beforeChange(oldValue, thisConfig);
			}
		}
		this.setState(
			{
				formValues: oldValue,
			},
			() => {
				if (search.afterFormValuesChange) {
					search.afterFormValuesChange(key, oldValue, this.getPage);
				}
			},
		);
	};

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

	componentDidMount() {
		const { search } = this.props.pageSearch;
		if (!search.noNeedInitData) {
			this.getPage();
		}
		if (this.props.setRefInfo) {
			this.props.setRefInfo('List', this);
		}
	}

	resetFormValues = () => {
		const { beforeResetFormValues } = this.props.pageSearch.search;
		let { formValues } = this.state;
		if (beforeResetFormValues) {
			formValues = beforeResetFormValues(formValues);
		} else {
			formValues = {};
		}
		let pagination = this.state.pagination;
		pagination.current = 1;
		this.setState({
			formValues,
      pagination,
		}, () => {
		  this.getPage();
    });
	};

	handleSearch = () => {
    let pagination = this.state.pagination;
    pagination.current = 1;
    this.setState({
      pagination,
    }, () => {
      this.getPage();
    });
  };

	/**
	 * 处理排序
	 * */
	handleOnChange = (pagination, filters, sorter) => {
		const { pageSearch } = this.props;
		if (sorter) {
			const sortGetPageFields = pageSearch.search.handleSort(sorter);
			this.setState(
				{
					sortGetPageFields,
				},
				() => {
					this.getPage();
				},
			);
		}
	};

	pageButton = () => {
		return [];
		const { list } = this.state;
		let re = {};
		let buttonConfig = [];
		for (let item of list) {
			if (item.btns && Array.isArray(item.btns)) {
				for (let x of item.btns) {
					if (typeof re[x.name] === 'undefined') {
						re[x.name] = x;
					}
				}
			}
		}
		for (let z in re) {
			let info = re[z];
			buttonConfig.push({
				type: z,
				name: z,
				component: 'ModalBatch',
				className: z !== '通过' ? 'defaultRed' : 'defaultBlue',
				nameSpan: { big: 4, small: 5 },
				fileSpan: { big: 1, small: 1 },
				values: {
					[info.key]: info.value,
				},
				fields: [
					{
						key: 'reason',
						name: '审核意见',
						type: 'textarea',
					},
				],
				beforeSubmit: (props, formValues) => {
					return {
						taskForm: {},
						examineMap: JSON.stringify(formValues),
					};
				},
				sourceKey: 'taskId',
				postKey: 'taskIds',
				apiServiceApi: handleAudit,
			});
		}
		return buttonConfig;
	};

	render() {
		const { formValues, selectRows, list, pagination, loading } = this.state;
		const { listConfig, pageSearch, pageButton, children, addFields } = this.props;
		let { columns, search } = pageSearch;
		columns = handleColumns(columns);

		let data = list;
		for (let item of addFields) {
			if (item.type === 'tableSelect' && item.c1) {
				for (let i = 0; i < data.length; i++) {
					let nameKey = item.componentProps.labelName;
					if (data[i][item.c1] && data[i][item.c1].selects) {
						let res = [];
						for (let x in data[i][item.c1].selects) {
							res.push(data[i][item.c1].selects[x][nameKey]);
						}
						data[i][item.c1] = res.join(',');
					}
				}
			}
		}

		const tableProps = {
			rowKey: pageSearch.tableRowKey || 'id',
			selectedRows: selectRows,
			data: { list: data, pagination },
			columns,
			bordered: pageSearch.bordered || false,
			loading,
			noSelectRow: !listConfig.selectRows,
			onSelectRow: this.handleSelectRows,
			scroll: pageSearch.scroll || { x: true },
		};
		if (!listConfig.paging) {
			tableProps.data = { list: data, pagination: false };
		}
		if (search && search.handleSort) {
			tableProps.onChange = this.handleOnChange;
		}
		return (
			<Fragment>
				{listConfig.searchArea && this.props.searchCondition?.length ? (
					<SearchDom
						formStateChange={this.formStateChange}
						formValues={formValues}
						getPage={this.handleSearch}
						resetFormValues={this.resetFormValues}
						config={pageSearch.search}
					/>
				) : null}

				<Shell>
					{pageButton.length ? (
						<ButtonListDom
							config={pageButton}
							handleSelectRows={this.handleSelectRows}
							selectRows={selectRows}
							formValues={formValues}
							listData={list}
							search={pageSearch.search}
							getPage={this.getPage}
							children={children}
							columns={columns}
              searcherKeyValue={this.trueSearchParams?.searcherKeyValue}
						/>
					) : null}
					<StandardTable {...tableProps} />
				</Shell>
			</Fragment>
		);
	}
}

List.propTypes = {
	listConfig: PropTypes.object.isRequired,
	// pageButton: PropTypes.array,
	pageSearch: PropTypes.object.isRequired,
};

List.defaultProps = {
	listConfig: {
		selectRows: true, // 是否可以行选择,
		paging: true, // 是否可以分页,
		searchArea: true, // 是否拥有 搜索区dom,
		buttonArea: true, // 是否拥有 按钮区,
	},
	pageSearch: {
		search: {
			url: '',
			field: {},
			responseCallBack: (response) => {
				return response;
			},
			condition: [
				{
					key: 'studentNo',
					name: '学号',
					type: 'input',
				},
			],
			tableRowKey: 'id',
			columns: [
				{
					title: '姓名',
					dataIndex: '',
				},
				{
					title: '操作',
					dataIndex: 'operation',
					renderType: 'update', // 修改
				},
			],
			nameSpan: { big: 8, small: 9 },
			fileSpan: { big: 4, small: 4 },
		},
	},
};
