import React from 'react'
import * as mobx from 'mobx'

import {
	inject,
	observer,
} from 'mobx-react'

import {
	WeaTop,
	WeaFormItem,
	WeaRightMenu,
	WeaAlertPage,
	WeaSearchGroup,
} from 'ecCom'

import {
	WeaSwitch
} from 'comsMobx'

import { cloneDeep } from "lodash";

import {
	Spin,
	Button,
} from 'antd'
import {
	i18n
} from '../../public/i18n';

const toJS = mobx.toJS;

@inject('hrmAdminDecentralizationSet')
@observer
export default class AdminDecentralization extends React.Component {
	constructor(props) {
		super(props);
	}

	componentWillMount() {
		let bool = window.location.href.indexOf('/spa/hrm/engine.html') > -1;
		if (bool) {
			document.title = i18n.module.managementDecent();
		}
	}

	componentWillReceiveProps(nextProps) {
		if (this.props.location.key !== nextProps.location.key) {
			this.init();
		}
	}

	componentDidMount() {
		this.init();
	}

	init() {
		const {
			hrmAdminDecentralizationSet
		} = this.props, {
			mobxDataReset,
			getRight
		} = hrmAdminDecentralizationSet;

		mobxDataReset();
		getRight();
	}

	getDropMenuDatas = () => {
		const {
			hrmAdminDecentralizationSet
		} = this.props, {
			menu
		} = hrmAdminDecentralizationSet, {
			rightMenu
		} = menu;

		let menus = [];
		toJS(rightMenu).map((item, index) => {
			let obj = {
				key: item.menuFun,
				icon: <i className={`${item.menuIcon}`}/>,
				content: item.menuName,
			}
			if (item.menuFun == 'custom' || item.menuFun == 'collection' || item.menuFun == 'help' || item.menuFun == 'pageAddress') {
				obj.disabled = true;
			}
			menus.push(obj);
		})

		return menus;
	}

	handleMenuClick = (key) => {
		this[key] && this[key]();
	}

	getTopMenuBtns = () => {
		const {
			hrmAdminDecentralizationSet
		} = this.props, {
			menu
		} = hrmAdminDecentralizationSet, {
			topMenu
		} = menu;

		let btns = [];
		toJS(topMenu).map((item, i) => {
			btns.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@4if6jo@${i}`} type='primary' onClick={() => this.handleClick(item)} >{item.menuName}</Button>);
		});
		return btns;
	}

	handleClick = (item) => {
		this[item.menuFun] && this[item.menuFun]();
	}


	log = () => {
		window.setLogViewProps({
			logSmallType: '3021',
		});
	}

	save = () => {
		const {
			hrmAdminDecentralizationSet
		} = this.props, {
			save
		} = hrmAdminDecentralizationSet;
		save();
	}

	getForm = () => {
		let {
			hrmAdminDecentralizationSet
		} = this.props, {
			content,
			formKeys,
		} = hrmAdminDecentralizationSet, {
			form,
			condition,
		} = content, {
			isFormInit
		} = form, {
			detachable,
			hrmdetachable,
			wfdetachable,
			docdetachable,
			portaldetachable,
			cptdetachable,
			mtidetachable,
			wcdetachable,
			fmdetachable,
			mmdetachable,
			carsdetachable,
			votingdetachable,
			blogdetachable,
			executiondetachable,
			odocdetachable = '0'
		} = form.getFormParams();

		hrmdetachable=hrmdetachable||'0';
		wfdetachable=wfdetachable||'0';
		docdetachable=docdetachable||'0';
		portaldetachable=portaldetachable||'0';
		cptdetachable=cptdetachable||'0';
		mtidetachable=mtidetachable||'0';
		wcdetachable=wcdetachable||'0';
		fmdetachable=fmdetachable||'0';
		mmdetachable=mmdetachable||'0';
		carsdetachable=carsdetachable||'0';
		votingdetachable=votingdetachable||'0';
		blogdetachable=blogdetachable||'0';
		executiondetachable=executiondetachable||'0';

		const {
			couple
		} = formKeys;

		let arr = [];
		isFormInit && condition.map((c, index) => {
			let _arr = [];
			c.items.map((field, i) => {
				let key = field.domkey[0];

				if (key === "sanyuanable") {//启用三员分立管理
					if ( detachable === "1") {
						_arr.push({
							com: (
								<WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@op8h7i@${i}`}
		                            label={`${field.label}`}
		                            labelCol={{span:16}}
		                            wrapperCol={{span: 8}}
		                            error={form.getError(field)}
	  				    			tipPosition="bottom"
		                        >
		                            <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@4gpc7u@${i}`} fieldConfig={field} form={form} formParams={form.getFormParams()} onChange={(e) => this.handleChange(e)}/>
		                        </WeaFormItem>
							),
							colSpan: 1
						})
						return ;
					}else{
						return null;
					}
				}

				const broKey = couple[key];
				//broKey存在，说明正在渲染的是浏览框
				//当浏览框前面的开关关闭时，隐藏浏览框
				if (broKey && ( form.getFormParams()[broKey]  !=="1")) {
					_arr.push({
						com: <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@4lqzzs@${i}`}
	                            label={''}
	                            labelCol={{span: 0}}
	                            wrapperCol={{span: 0}}
	                        >
	                        </WeaFormItem>,
						colSpan: 1
					})
				}else{
					_arr.push({
						com: (
							<WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@6xfi7l@${i}`}
	                            label={`${field.label}`}
	                            labelCol={{span: i % 2 == 0 ? 16 : 10}}
	                            wrapperCol={{span: i % 2 == 0 ? 8 : 14}}
	                            error={form.getError(field)}
					    			tipPosition="bottom"
	                        >
	                            <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@g1byzb@${i}`} fieldConfig={field} form={form} formParams={form.getFormParams()} onChange={(e) => this.handleChange(e)}/>
	                        </WeaFormItem>
						),
						colSpan: 1
					})
				}


				
			})
			arr.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@cw1iq1@${index}`} onVisibleChange={e => this.handleTrigger(e, index)} needTigger={true} title={c.title} showGroup={c.defaultshow} items={_arr} col={2} />)
		})

		return <div className='hrm-admin-decentralization-searchgroup'>{arr}</div>;
	}

	handleTrigger = (bool, index) => {
		const {
			hrmAdminDecentralizationSet
		} = this.props, {
			setBtnStatus
		} = hrmAdminDecentralizationSet;

		index == 0 && setBtnStatus(bool);
	}

	handleChange = (e) => {
		const {
			hrmAdminDecentralizationSet
		} = this.props, {
			handleClickOfCheckbox,
			setBrowserData,
			changeReplaceDatas,
			deleteRules,
			addRules,
			content
		} = hrmAdminDecentralizationSet;

		let key = Object.keys(e)[0],
			len = Object.keys(e[key]).length;

		if (key === "detachable" && e.detachable.value !== '1') {//重置三员分立管理
			content.form.updateFields({
				sanyuanable:'0'
			})
		}

		if (key === "sanyuanable") {
			return;
		}

		if (len == 1) { //所有checkbox相关操作
			let val = e[key].value;
			handleClickOfCheckbox(key, val);
			if (key == 'detachable') return;
			if (val == '0') {
				deleteRules(key); //关闭checkbox时，删除掉condition中的校验参数: rules(目前表单组件不支持选择性校验)。
			} else {
				addRules(key); //打开checkbox时，添加参数rules。
			}

		} else if (len > 1 && key == 'dftsubcomid') { //第一个Group内的浏览按钮相关操作
			let obj = e[key].valueObj;
			setBrowserData(obj)
		} else { //第二个Group内的所有浏览按钮相关操作
			let obj = e[key].valueObj;
			changeReplaceDatas(key, obj);
		}
	}

	click = () => {
		const {
			hrmAdminDecentralizationSet
		} = this.props, {
			content,
			setPageStatus,
			changeBrowserReplaceDatas,
			formKeys,
		} = hrmAdminDecentralizationSet, {
			data,
			form
		} = content;

		setPageStatus(true);
		let d = toJS(data),
			obj = d[0];
		let indexs = this.getUncheckedIndex(form.getFormParams());
		let fields = this.getShouldUpdateFields(indexs, d, obj,formKeys.browserKeysExceptDftsubcom);
		form.updateFields(fields); //只更新开关开启的默认机构
		changeBrowserReplaceDatas(obj); //更新condition中的参数：replaceDatas
		setTimeout(() => setPageStatus(false), 500); //点击同步按钮时，会造成页面抖动，所以这里加一个loading
	}

	getUncheckedIndex = (params) => {
		const obj = cloneDeep(params);
		delete obj.sanyuanable;
		
		let arr = [],
			closedCheckboxs = [];
		Object.keys(obj).map(key => {
			arr.push({
				key: obj[key]
			});
		});
		let f = arr.filter((item, index) => index % 2 == 0);
		f.map((item, index) => {
			if (item.key == '0') {
				closedCheckboxs.push(index);
			}
		});
		return closedCheckboxs;
	}

	getShouldUpdateFields = (indexs, d, obj,keys) => {
		// const keys = ['hrmdftsubcomid', 'wfdftsubcomid', 'docdftsubcomid', 'portaldftsubcomid', 'cptdftsubcomid',
		// 	'mtidftsubcomid', 'wcdftsubcomid', 'fmdftsubcomid', 'mmdftsubcomid', 'carsdftsubcomid','votingdftsubcomid','blogdftsubcomid','executiondftsubcomid'
		// ];
		let o = {};

		keys.map(key => {
			o[key] = {
				value: obj.id,
				valueSpan: obj.name,
				valueObj: d
			}
		})

		let needUpdateFields = {};
		Object.keys(o).map((key, index) => {
			let result = indexs.findIndex(i => i - 1 == index);
			if (result == -1) {
				needUpdateFields[key] = o[key];
			}
		});

		return needUpdateFields;
	}

	render() {
		const {
			hrmAdminDecentralizationSet
		} = this.props, {
			loading,
			weaTopTitle,
			authorized,
			content,
			btnShow,
			date
		} = hrmAdminDecentralizationSet, {
			cLoading
		} = content;

		if (!authorized) {
			return (
				<div style={{height: '100%'}}>
					{loading ?  <div className='hrm-loading-center'>
									<Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@hckmtk`} spinning={loading} size='large'></Spin>
								</div>
						     :	<div className="hrm-wea-alert-page">
		                			<WeaAlertPage ecId={`${this && this.props && this.props.ecId || ''}_WeaAlertPage@4tj5gi`}>
						                <div style={{ color: '#000' }}>
						                    {i18n.message.authFailed()}
						                </div>
		                      		</WeaAlertPage>
	                        	</div>
	                }	
                </div>
			)
		} else {
			return (
				<div className='hrm-print'>
					<WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@mdp2nw`} 
						datas={this.getDropMenuDatas()} 
						onClick={ key => this.handleMenuClick(key)}
						collectParams={{favname:weaTopTitle,favouritetype:5}}
					>
					    <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@b6jb6s`} 
					        title={weaTopTitle}
					        icon={<i className='icon-coms-hrm'/>}
					        iconBgcolor='#217346'
					        loading={true}
					        buttons={this.getTopMenuBtns()}
					        showDropIcon={true}
					        dropMenuDatas={this.getDropMenuDatas()}
					        onDropMenuClick={(e) => this.handleMenuClick(e)}
					    />
					    <div style={{position: 'relative'}}>
					    	{!cLoading && <div className='hrm-form-english-lg'>{this.getForm()}</div>}
					        {!cLoading && btnShow && <div style={{position: 'absolute',top: 61,left: '75.4%'}}><Button ecId={`${this && this.props && this.props.ecId || ''}_Button@t07xe2`} type='primary' onClick={() => this.click()}>{i18n.button.synchroDecentModules()}</Button></div>}
					    </div>
					</WeaRightMenu>
				</div>
			)
		}

	}
}