import React from "react";
import { Button, message, Modal, Table, Tag } from "antd";
import FormList from "./formList/index";
import { connect } from "dva";

@connect(({ DataColumn, SqlManageEntity, loading }) => ({
	DataColumn,
	SqlManageEntity,
	loading: loading.models.DataColumn || loading.models.SqlManageEntity,
}))
export default class TableSelect extends React.Component {
	constructor(props) {
		super(props);
		const value = props.value || {};

		this.state = {
			selects: value.selects || {},
			visiable: value.visiable,
			isAll: value.isAll != null ? value.isAll : false,
			querys: value.querys || [],
			sql: value.sql,
		};
	}

	triggerChange = (changedValue) => {
		// Should provide an event to pass value to Form.
		const onChange = this.props.onChange;
		if (onChange) {
			console.log('changedValue', changedValue);
			onChange(Object.assign({}, this.state, changedValue));
		}
	};

	componentWillReceiveProps(nextProps) {
		// Should be a controlled component.
		if ('value' in nextProps) {
			const value = nextProps.value;

			if (value != null && value instanceof Object) {
				this.setState(value);
			}
			//
		}
	}

	remove = (rowKey) => {
		const { selects } = this.state;
		delete selects[rowKey];
		if (!('value' in this.props)) {
			this.setState({ selects });
		}
		this.triggerChange({ selects });
	};

	select = (obj) => {
		var { selects } = this.state;
		const {
			json: { isMultiple, optionType },
		} = this.props;
		let valueName = this.props.json.valueName;

		if (optionType == 'reference' && this.props.dataColumn.referenceObjId) {
			valueName = this.props.dataColumn.referenceCodeName;
		}

		const kk = obj[valueName];
		if (kk == null) {
			message.error('指定的取值字段不存在或者值为空');
			return;
		}
		if (!isMultiple) {
			selects = { [kk]: { ...obj, selectKey: kk } };
		} else {
			selects[kk] = obj;
			selects[kk].selectKey = kk;
		}
		if (!('value' in this.props)) {
			this.setState({ selects });
		}
		this.triggerChange({ selects });
	};

	selectAll = () => {
		let { selects } = this.state;
		const { dataSource, json } = this.props;
		let { valueName, optionType } = json;
		const { list } = dataSource;
		console.log(list);
		if (optionType == 'reference' && this.props.dataColumn.referenceObjId) {
			valueName = this.props.dataColumn.referenceCodeName;
		}
		if (list && Array.isArray(list)) {
			for (let item of list) {
				let kk = item[valueName];
				selects[kk] = item;
				selects[kk].selectKey = kk;
			}
		}
		if (!('value' in this.props)) {
			this.setState({ selects });
		}
		this.triggerChange({ selects });
	};

  cancelAll = () => {
    let selects = {};
    if (!('value' in this.props)) {
      this.setState({ selects });
    }
    this.triggerChange({ selects });
  };

  close = (i) => {
		var { values, labels } = this.state;
		values.splice(i, 1);
		labels.splice(i, 1);
		if (!('value' in this.props)) {
			this.setState({ values, labels });
		}
		this.triggerChange({ values, labels });
	};

	open = () => {
		if (!('value' in this.props)) {
			this.setState({ visiable: true });
		}
		this.triggerChange({ visiable: true });
	};

	closeModal = () => {
		if (!('value' in this.props)) {
			this.setState({ visiable: false });
		}
		const { resetSearchText } = this.props;
		resetSearchText && resetSearchText();
		this.triggerChange({ visiable: false });
	};


	render() {
		const {
			json: { isMultiple, sql, optionType, showTable },
			dataColumn: { referenceObjId },
			sqlModel,
			columns,
			dataSource,
		} = this.props;
		let { valueName, labelName } = this.props.json;
		if (optionType == 'reference' && referenceObjId) {
			valueName = this.props.dataColumn.referenceCodeName;
			labelName = this.props.dataColumn.referenceNameName;
		}
		if (valueName == null || valueName == '') {
			return <>请指定取值的列名</>;
		}
		const { selects, visiable, labels } = this.state;
		const keys = [];
		for (let i in selects) {
			keys.push(selects[i][valueName]);
		}
		const columns2 = [
			...columns,
			{
				title: '操作',
				render: (val, record) => <a onClick={this.remove.bind(this, record.selectKey)}>移除</a>,
			},
		];
		const columns3 = [
			...columns,
			{
				title: '操作',
				render: (val, record) =>
					keys.includes(record[valueName]) ? (
						<span>已选择</span>
					) : (
						<a onClick={this.select.bind(this, record)}>选择</a>
					),
			},
		];
		const custom = {
			isAll: this.state.isAll,
			querys: this.state.querys,
			sql: this.state.sql,
		};
		let allWidth = 0;
		if (columns3) {
			columns3.map((item, index) => {
				if (index === columns3.length - 1) {
					item.fixed = 'right';
					item.width = 90;
					allWidth += 90;
					return item;
				}
				if (index === columns3.length - 2) {
					allWidth += 150;
				} else {
					if (item.width) {
						allWidth += item.width;
					} else {
						item.width = 180;
						allWidth += 180;
					}
				}
				return item;
			});
		}

		// console.log(this.props);
		// console.log(this.state);
		return (
			<div>
				{Object.keys(selects).length > 0 ? (
					showTable ? (
						<Table
							rowKey={valueName}
							size="small"
							dataSource={Object.values(selects)}
							columns={columns2}
							pagination={false}
						/>
					) : (
						Object.keys(selects).map((k) => (
							<Tag key={k} closable onClose={this.remove.bind(this, k)}>
								{selects[k][labelName]}
							</Tag>
						))
					)
				) : (
					''
				)}
				<Button type="primary" onClick={this.open}>
					选择
				</Button>
				{visiable && (
					<Modal
						width={this.props.get === 'mobile' ? '100%' : '60%'}
						maskClosable={false}
						title={`请选择`}
						visible={visiable}
						onOk={this.closeModal}
						onCancel={this.closeModal}>
						{optionType == 'reference' ? (
							referenceObjId ? (
								<FormList
									rights={this.props.rights || []}
									notShowBack={true}
									value={custom}
									objId={referenceObjId}
									isFormCom={true}
									isSelect={true}
									selects={keys}
									valueName={valueName}
									callback={this.select}
									sql={sql}
								/>
							) : (
								'未关联数据对象'
							)
						) : sqlModel.dataObjId ? (
							<FormList
								rights={this.props.rights || []}
								notShowBack={true}
								value={custom}
								objId={sqlModel.dataObjId}
								isFormCom={true}
								isSelect={true}
								selects={keys}
								valueName={valueName}
								callback={this.select}
								sql={sql}
							/>
						) : (
							<>
								{isMultiple && (
									<>
										{' '}
										<Button
											type={'primary'}
											style={{ margin: '0 10px 10px 0' }}
											onClick={this.selectAll}>
											全选
										</Button>
										<Button
											type={'primary'}
											style={{ marginBottom: '10px' }}
											onClick={this.cancelAll}>
											取消全选
										</Button>
									</>
								)}

								<Table
									rowKey={valueName}
									size="small"
									dataSource={dataSource.list}
									columns={columns3}
									scroll={{ x: allWidth }}
								/>
							</>
						)}
					</Modal>
				)}
			</div>
		);
	}
}
