import {
	observable,
	action,
	computed
} from 'mobx';
import {
	WeaSwitch
} from 'comsMobx';
import {
	Button,
	message
} from 'antd';
import HrmBaseStore from './baseStore';
import * as api from '../apis/matrix';
import {
	i18n
} from '../public/i18n';
import has from 'lodash/has';
import isEmpty from 'lodash/isEmpty';
import {WeaLocaleProvider} from 'ecCom';
const getLabel = WeaLocaleProvider.getLabel;

class HrmMatrixAdjust extends HrmBaseStore {
	/********************* unobservable list *********************/
	getMenu = () => {
		if (this.showResult) {
			return [{
				key: '1',
				content: i18n.button.goBack(),
				icon: <i className='icon-coms-go-back'/>,
				onClick: this.resetData,
			}, ...this.getBasicMenus()]
		}
		return [{
			key: '1',
			content: i18n.button.doExcute(),
			icon: <i className='icon-coms-Browse-box-add-all'/>,
			onClick: this.doExcute,
		}, ...this.getBasicMenus('HRM_ENGINE_Matrix_MassMaint')]
	}

	selectedMatrixInfo;
	selectedTargetInfo;
	selectedToInfo;
	dataCols = [];
	fromFormFields = [];
	toFormFields = [];
	transferDatas = [];
	color = '#00CC2F';
	table;

	setTableRef = (t) => this.table = t;

	formItemRender = {
		objtype: (field, textAreaProps, form, formParams) => {
			return (
				<div className='cust'>
					<div className='basic'>
						<WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@n6hpow`} fieldConfig={{...field, ...textAreaProps, placeholder: field.label}} otherParams={{placeholder: '123'}} form={form} formParams={formParams} onChange={this.onMatrixChangeHandle}/>
					</div>
				</div>
			)
		},
		matrix_condition: (field, textAreaProps, form, formParams) => {
			return (
				<div className='cust'>
					<div className='basic'>
						<WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@5aoaws`} fieldConfig={{...field, ...textAreaProps}} form={form} formParams={formParams} onChange={() => this.initTable()}/>
					</div>
				</div>
			)
		}, 
		matrix_data: (field, textAreaProps, form, formParams) => {
			const {fieldMap} = form;
			return (
				<div className='cust'>
					<div className='basic'>
						<WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@ka5ric`} fieldConfig={{...field, ...textAreaProps}} form={form} formParams={formParams} onChange={this.onDisplayColChangeHandle}/>
					</div>
					{
						formParams['matrix_data'] != 0 &&
						<div className='child'>
							<WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@9klvb7`} 
								fieldConfig={{...fieldMap['colcolumn'], ...textAreaProps, 
								title: getLabel('508123','选择取值字段'),
								hasAdvanceSerach: false,
								memorise: true, otherParams: this.generateColBrowserConfig()}} 
								form={form} formParams={formParams} onChange={() => {formParams.objid != '' && this.initTable()}}/>
							{
								formParams.colcolumn != '' && <span style={{color: 'green'}}>✓</span>
							}
						</div>
					}
				</div>
			)
		}, 
		objid: (field, textAreaProps, form, formParams) => {
			return (
				<div className='cust'>
					<div className='basic'>
						<WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@8jp5cq`} fieldConfig={{...field, ...textAreaProps, placeholder: field.label}} form={form} formParams={formParams} onChange={this.onTargetResourceChangeHandle}/>
					</div>
				</div>
			)
		}, 
		optflag: (field, textAreaProps, form, formParams) => {
			return (
				<div className='cust'>
					<div className='basic'>
						<WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@fgv478`} fieldConfig={{...field, ...textAreaProps}} form={form} formParams={formParams}/>
					</div>
				</div>
			)
		},
		newobjid: (field, textAreaProps, form, formParams) => {
			if (this.formTarget.toForm.getFormParams().optflag != '1'){
				return (
					<div className='cust'>
						<div className='basic'>
							<WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@5nljwf`} fieldConfig={{...field, ...textAreaProps, placeholder: field.label}} form={form} formParams={formParams} onChange={this.onToResourceChangeHandle}/>
						</div>
					</div>
				)
			}
			return;
		},
		colcolumn: (field, textAreaProps, form, formParams) => null
	}

	childrenComponents = {
		newobjid: () => {
		  return [
			{
			  com: <div style={{float: 'left'}}><Button ecId={`${this && this.props && this.props.ecId || ''}_Button@jw6a0c`} type='primary' onClick={this.doExcute}>{i18n.button.doExcute()}</Button></div>,
			  col: 1
			}
		  ];
		},
	}
	/********************* unobservable list *********************/
	/********************* observable list *********************/
	@observable refreshTable = new Date().getTime();
	@observable refreshDialog = new Date().getTime();
	@observable refreshForm = new Date().getTime();
	@observable refreshResult = new Date().getTime();

	@observable transferCount = 0;

	@observable showSpin = false;
	@observable showResult = false;
	@observable resultMessage = {};

	@observable _tableCols = [];
	@observable _tableDatas = [];
	@observable _tableCells = [];

	set tableCols(v){
		this._tableCols = v;
	}

	@computed get tableCols(){
		return this.toJS(this._tableCols);
	}

	set tableDatas(v){
		this._tableDatas = v;
	}

	@computed get tableDatas(){
		return this.toJS(this._tableDatas);
	}

	set tableCells(v){
		this._tableCells = v;
	}

	@computed get tableCells(){
		return this.toJS(this._tableCells);
	}

	@computed get tableConfig(){
		return {
			...this.editTableConfig,
			draggable: false,
			willAdd: false,
			willDelete: false,
			willCopy: false,
			columns: this.tableCols,
			initialDatas: this.tableDatas,
			cells: this.tableCells,
			datas: this.tableDatas,
			onChange: this.onChange,
			getRowSelection: (rowSelection) => {
				return null;
			},
			tableProps: {
				scroll: {
					x: 450,
					y: 500
				}
			}
		}
	}
	/********************* observable list *********************/
	/********************* action list *********************/
	@action clear = () => {
		this.selectedMatrixInfo = null;
		this.selectedTargetInfo = null;
		this.selectedToInfo = null;
		this.transferCount = 0;
		this.dataCols = [];
		this.showResult = false;
		this.clearTable();
	}

	get fromTargetParam(){
		const formParams = this.formTarget.fromForm.getFormParams();
		return {
			...formParams,
			matrixid: formParams.objtype,
			resourceid: formParams.objid,
			olduserid: formParams.objid,
			fromid: formParams.objid,
		}
	}

	get toTargetParam(){
		const formParams = this.formTarget.toForm.getFormParams();
		return {
			...formParams,
			newuserid: formParams.newobjid,
			toid: formParams.newobjid,
			method: 'replacerecord'
		}
	}

	@action generateColBrowserConfig = () => {
		return {
			customized: true,
			children: [<i className="icon-coms-Flow-setting child" style={{marginLeft: '10px'}}/>]
		}
	}

	/**
	 *初始化函数
	 */
	@action initData = (query) => {
		this.clear();
		this.containerInitFinished = {
			...this.containerInitFinished,
			init: true
		}
		this.setQueryParams(query);
		this.getFormInfo();
	}

	@action setQueryParams = (query = {}) => {
		this.needSearch = !isEmpty(query) && query.needSearch == '1';
		if(this.needSearch){
			const {matrixid, matrixname, resourceid, resourcename} = query;
			this.selectedMatrixInfo = {
				value: matrixid,
				valueSpan: matrixname,
				valueObj: [{
					id: matrixid,
					name: matrixname
				}]
			}
			this.selectedTargetInfo = {
				value: resourceid,
				valueSpan: resourcename,
				valueObj: [{
					id: resourceid,
					name: resourcename
				}]
			}
		}
	}

	/**
	 *获取表单元素
	 */
	@action getFormInfo = (params = {}) => {
		if(this.showSpin)
			return;
		this.fromFormFields.length = 0;
		this.toFormFields.length = 0;
		this.showSpin = true;
		api.getFormInfo(params).then(data => {
			if (data.status === '1') {
				if (has(data, 'itemlist') && data.itemlist.length > 0) {
					this.fields = data.itemlist;
					data.itemlist.map((f, i) => {
						if(['optflag', 'newobjid'].indexOf(f.domkey[0]) < 0)
							this.fromFormFields.push(f);
						else
							this.toFormFields.push(f);
					})
					this.initForm();
					this.showSpin = false;
				}
			}
		}, error => {
			this.showSpin = false;
		})
	}

	/**
	 * 如果存在选中的矩阵信息，刷新form值
	 */
	@action formInitComplatedHandle = () => {
		if(this.selectedMatrixInfo != null){
			this.formTarget.fromForm.updateFields({
				objtype: this.selectedMatrixInfo
			});
		}
		if(this.selectedTargetInfo != null){
			this.formTarget.fromForm.updateFields({
				objid: this.selectedTargetInfo
			});
		}
		this.needSearch && this.initTable();
	}
	
	/**
	 *初始化form
	 */
	@action initForm = (disabled = false) => {
		if (this.fields.length > 0) {
			const formArr = ['fromForm', 'toForm'];
			formArr.map(name => {
				const formFields = [{
					title: '',
					defaultshow: true,
					items: this[`${name}Fields`]
				}]
				this.setFormData(name, formFields);
			});
			this.formInitComplatedHandle();
		}

		this.refreshForm = new Date().getTime();
	}

	/**
	 *矩阵浏览按钮变更事件
	 *变更时触发清空table数据并重新获取form数据
	 * @memberof HrmMatrixAdjust
	 */
	@action onMatrixChangeHandle = obj => {
		this.clearTable();
		const keys = Object.keys(obj);
		this.selectedMatrixInfo = obj[keys[0]];
		this.selectedTargetInfo = null;
		this.getFormInfo(this.fromTargetParam);
	}

	@action onDisplayColChangeHandle = obj => {
		const keys = Object.keys(obj);
		const data = obj[keys[0]];
		if(data.value == '0'){
			this.formTarget.fromForm.updateFields({
				colcolumn: ''
			});
			this.initTable();
		}
	}

	/**
	 *源人员浏览按钮变更事件
	 *触发查询table数据
	 */
	@action onTargetResourceChangeHandle = obj => {
		const keys = Object.keys(obj);
		this.selectedTargetInfo = obj[keys[0]];
		this.initTable();
	}
	
	@action onToResourceChangeHandle = obj => {
		const keys = Object.keys(obj);
		this.selectedToInfo = obj[keys[0]];
	}

	@action clearTable = () => {
		this._tableCols = [];
		this._tableDatas = [];
		this._tableCells = [];
		// this.refreshTable = new Date().getTime();
	}

	@action checkFormPamras = (target = 'from') => new Promise((resolve, reject) => {
		const form = this.formTarget[`${target}Form`];
		const formParams = form.getFormParams();
		window.e9HideFormFieldKeys = [];
		target == 'from' && formParams['matrix_data'] == '0' && window.e9HideFormFieldKeys.push('colcolumn');
		target == 'to' && formParams['optflag'] == '1' && window.e9HideFormFieldKeys.push('newobjid');
		form.validateForm().then(f => {
			if (f.isValid) {
				resolve(true);
			} else {
				f.showErrors();
				const fields = form.fieldMap;
				[...Object.keys(fields)].map(k => {
					const e = form.getError(fields[k]);
					if (e != null && e != "") {
					}
				});
				this.showError = new Date().getTime();
				resolve(false);
			}
		});
	})

	@action initTable = () => {
		this.checkFormPamras().then(status => {
			if(status){
				this.showSpin = true;
				let params = {
					...this.fromTargetParam,
				};
				api.getMatrixData(params).then(data => {
					if (data.status === '1') {
						const [columns, dataCols] = this.transferTableEditColumns(data.columns);
						const [datas, cells] = this.transferTableEditData(data.dataSource, dataCols);
						this.dataCols = dataCols;
						this.tableCols = columns;
						this.tableDatas = datas;
						this.tableCells = cells;
						this.resetTableScroll();
						this.calcSelectedData();
					} else {
						message.error(data.message);
					}
					this.showSpin = false;
				}, error => {
					this.showSpin = false;
				})
			}else{
				this.clearTable();
				return;
			}
		})
	}

	/**
	 *转化column数据
	 *取值字段如果有和被调整人相同的为checkbox组件
	 */
	@action transferTableEditColumns = (columns) => {
		const cols = [], dataCol = [];
		if (columns.length > 0) {
			columns.map((typeArr, index) => {
				typeArr.map(col => {
					if(col.dataIndex != 'dataorder'){
						const colProps = {
							title: col.title,
							dataIndex: col.dataIndex,
							key: col.dataIndex,
							colSpan: 1,
							width: 164
						}
						if(index == 0){
							Object.assign(colProps, {
								com: [
									{
										type: "CUSTOM",
										key: col.dataIndex,
										render: (text, record, index, onEdit) => (
										  <div>{record[`${col.dataIndex}span`]}</div>
										)
									}
								]
							})
						}else if(index == 1){
							const dataIndex = `${col.dataIndex}checkbox`;
							dataCol.push(col.dataIndex);
							Object.assign(colProps, {
								title: col.title,
								dataIndex,
								key: dataIndex,
								checkVauleType: [true, false],
								showCheckAll: true,
								className: 'dataCol',
								com: [
									{
										type: "CHECKBOX",
										key: dataIndex,
									},
									{
										type: "CUSTOM",
										key: col.dataIndex,
										render: (text, record, index, onEdit) => {
											let txt = record[`${col.dataIndex}span`];
											return (
												<div className='cust-checkbox' dangerouslySetInnerHTML={{__html: txt}}
													onClick={() => onEdit({
														type: "CUSTOM",
														record: {
															...record,
															[dataIndex]: !(record[dataIndex] || false)
														},
													})}/>
											)
										}
									}
								]
							})
						}
						cols.push(colProps);
					}
				})
			})
		}
		return [cols, dataCol];
	}

	/**
	 *格式化数据源，添加id属性，否则tableedit组件会报错
	 *取值字段如果有和被调整人相同,添加相应样式
	 *管理table的cell配置，如果数据与查询条件不匹配，则显示div
	 */
	@action transferTableEditData = (dataSource, cols) => {
		const datas = [], cells = [];
		const replaceData = this.selectedTargetInfo.valueSpan;
		const checkTargetId = this.selectedTargetInfo.value;
		dataSource.map((data, i) => {
			const d = {
				...data,
				id: data.id || i
			}
			const cell = {id: d.id};
			cols.map(c => {
				let ids = data[c];
				ids = ids.substr(1, ids.length - 2);
				const replaceIndex = ids.split(',').indexOf(checkTargetId);
				let key = `${c}span`, txt = data[key], found = false;
				txt = txt.split(',').reduce((pre, cur, index) => {
					if(index == replaceIndex){
						found = true;
						pre.push(`<span style='color: ${this.color}'>${replaceData}</span>`);
						Object.assign(d, {
							[`${c}checkbox`]: true
						});
					}else{
						pre.push(cur);
					}
					return pre;
				}, []).join(',');
				Object.assign(d, {[`${c}matching`]: found, [key]: txt});
				if(!found){
					Object.assign(cell, {
						[`${c}checkbox`]: {
							com: [
								{
									type: "CUSTOM",
									key: c,
									disabled: true,
									render: (text, record, index, onEdit) => (
										<div className='cust-lbl' dangerouslySetInnerHTML={{__html: d[`${c}span`]}} />
									)
								}
							]
						}
					})
				}
			})
			datas.push(d);
			Object.keys(cell).length > 1 && cells.push(cell);
		});
		return [datas, cells];
	}

	/**
	 *计算选中需要调整的数量
	 */
	@action calcSelectedData = () => {
		const datas = this.tableDatas;
		let count = 0;
		this.transferDatas.length = 0;
		datas.map(d => {
			const cols = [];
			this.dataCols.map(c => {
				const dataIndex = `${c}checkbox`;
				const matching = d[`${c}matching`] || false;
				const selected = d[dataIndex] || false;
				if(matching && selected){
					count++;
					cols.push(c);
				}
			});
			if(cols.length > 0){
				this.transferDatas.push({
					id: d.id,
					uuid: d.uuid,
					cols: cols.join(',')
				})
			}
		})
		this.transferCount = count;
	}

	/**
	 *tableedit onChangeHandle
	 */
	@action onChange = (datas, other) => {
		this.tableDatas = datas;
		this.calcSelectedData();
	};

	@action resetTableScroll = () => {
		jQuery(".ant-table-body", ReactDOM.findDOMNode(this.table)).scrollTop(0);
		jQuery(".ant-table-body", ReactDOM.findDOMNode(this.table)).scrollLeft(0);
	}

	@action doExcute = () => {
		this.checkFormPamras().then(status => {
			status && this.checkFormPamras('to').then(status => {
				if(status){
					if(this.transferCount == 0){
						message.error(getLabel('509530','请选择需要批量调整的数据'));
						return;
					}

					const params = {
						...this.fromTargetParam,
						...this.toTargetParam,
						datas: JSON.stringify(this.transferDatas)
					}

					let content = i18n.confirm.operationConfirm();
					content = content.replace('{param}', i18n.button[this.toTargetParam.optflag == '0' ? 'replace' : 'delete']);

					this.confirmInfo({
						content,
						onOk: () => {
							this.showSpin = true;
							api.processData(params).then(data => {
								if (data.status === '1') {
									this.showSpin = false;
									this.showResult = true;
									this.resultMessage = {
										...data
									}
								}
							}, error => {
			
							})
						}
					});
				}
			})
		});
	}

	@action onBreak = () => {
		// this.clearTable();
		this.initData();
	}
	/********************* action list *********************/
}

export const hrmMatrixAdjust = new HrmMatrixAdjust();