/**
 * 困难学生家庭情况调查-申请
 * 钟是志
 * 2019年11月6日
 * 因业务复杂只能特殊开发
 * */
import React, { Component } from 'react';
import ApplyPage from '../index';
import { getDefaultValues } from '../../destruction';
import { deepCopy } from '@/baseComponent/utils';

const getIndex = (arr, name) => {
	return arr.findIndex((x) => {
		return x.name === name;
	});
};

const KNXSJTQKSQ = (WrappedComponent) =>
	class extends Component {
		diyFunction = () => {
			this.instanceComponent.handleButtonSet = () => {
				let that = this.instanceComponent;
				const { addFields, workId, tableInfo } = that.state;

				const familyTypeIndex = getIndex(addFields, '家庭类型');
				const fileIndex = getIndex(addFields, '家庭类型证明材料');
				const famliyMemberIndex = getIndex(addFields, '家庭成员(不含自己)');
				const famliyMoneyIndex = getIndex(addFields, '家庭人均年收入(元)');
				const familyNumberIndex = getIndex(addFields, '家庭人口数');

				const defaultValues = getDefaultValues(addFields, tableInfo);
				const diyFormStateChange = (value, key, ModalFormComponent) => {
					let oldValue = ModalFormComponent.state.formValues;
					if (typeof value === 'object') {
						oldValue[key] = deepCopy(value);
					} else {
						oldValue[key] = value;
					}

					if (familyTypeIndex >= 0 && key === addFields[familyTypeIndex].key) {
						// 改变家庭类型时.
						let testOne = value.substring(0, 1);
						if ([2, 3, 4, 5, 6, 7].indexOf(Number(testOne)) > -1) {
							// 如果学生勾选了项目234567，就必须要上传附件；
							addFields[fileIndex].required = true;
						} else {
							addFields[fileIndex].required = false;
						}
						that.setState({ addFields });
					}

					if (famliyMemberIndex >= 0 && key === addFields[famliyMemberIndex].key) {
						// 改变家庭成员时
						let money = 0;
						const famliyMemberFileds = addFields[famliyMemberIndex].componentProps.thisFields;
						const onePersonIndex = getIndex(famliyMemberFileds, '年收入(元)');
						for (let item of value) {
							money = money + item[famliyMemberFileds[onePersonIndex].key];
						}
						oldValue[addFields[famliyMoneyIndex].key] = parseInt(money / (value.length + 1), 10); // 计算家庭平均年收入
						oldValue[addFields[familyNumberIndex].key] = value.length + 1; // 计算家庭人数
					}

					ModalFormComponent.setState({
						formValues: oldValue,
					});
				};
				return [
					{
						type: 'add',
						name: '申请',
						component: 'ModalForm',
						diyFormStateChange,
						workId,
						fields: addFields,
						modalWidth: 800,
						values: {
							...defaultValues,
						},
						nameSpan: { big: 6, small: 6 },
						fileSpan: { big: 1, small: 1 },
					},
				];
			};
		};

		componentDidMount() {
			this.diyFunction();
		}

		render() {
			return (
				<WrappedComponent
					ref={(instanceComponent) => (this.instanceComponent = instanceComponent)}
				/>
			);
		}
	};
export default KNXSJTQKSQ(ApplyPage); // 高阶组件
