import React from 'react'
import {
	toJS
} from 'mobx'
import {
	inject,
	observer,
} from 'mobx-react'
import {
	WeaTop,
	WeaTab,
	WeaFormItem,
	WeaRightMenu,
	WeaAlertPage,
	WeaDateGroup,
	WeaLeftRightLayout,
	WeaLocaleProvider,
} from 'ecCom'
import {
	WeaSwitch,
	WeaTableNew,
} from 'comsMobx'
import {
	Row,
	Col,
	Spin,
	Button,
	message,
} from 'antd';
import OrganizationTree from '../../coms/OrganizationTree';
const WeaTable = WeaTableNew.WeaTable;
const getLabel = WeaLocaleProvider.getLabel;

import {
	i18n
} from '../../public/i18n';

@inject('hrmLoginLog')
@observer
export default class LoginLog extends React.Component {
	constructor(props) {
		super(props);
		this.state = {
			datas: [{
				name: i18n.label.all(),
				value: '0'
			}, {
				name: i18n.label.today(),
				value: '1'
			}, {
				name: i18n.label.tswk(),
				value: '2'
			}, {
				name: i18n.label.tsmth(),
				value: '3'
			}, {
				name: i18n.label.tssn(),
				value: '4'
			}, {
				name: i18n.label.tsyr(),
				value: '5'
			}, {
				name: i18n.label.preMonth(),
				value: '7'
			}, {
				name: i18n.label.preYear(),
				value: '8'
			}, {
				name: i18n.label.dateRange(),
				value: '6'
			}]
		}
	}

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

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

	componentDidMount() {
		this.init();
	}

	init() {
		const {
			hrmLoginLog
		} = this.props, {
			getRight,
			mobxDatasReset,
		} = hrmLoginLog

		mobxDatasReset();
		getRight();
	}

	getDropMenuDatas = () => {
		const {
			hrmLoginLog
		} = this.props, {
			menu
		} = hrmLoginLog, {
			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 == 'log' || item.menuFun == 'collection' || item.menuFun == 'help' || item.menuFun == 'pageAddress') {
				obj.disabled = true;
			}
			menus.push(obj);
		})

		return menus;
	}

	custom = () => {
		const {
			hrmLoginLog
		} = this.props, {
			tableStore,
		} = hrmLoginLog;

		tableStore.setColSetVisible(true);
		tableStore.tableColSet(true);
	}

	handleMenuClick = (key) => {
		const {
			hrmLoginLog
		} = this.props, {
			isPanelShow,
			setPanelStatus
		} = hrmLoginLog;

		isPanelShow && setPanelStatus(false);
		this[key] && this[key]();
	}

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

		let btns = [];
		toJS(topMenu).map((item, index) => {
			if (item.menuFun !== 'batchDelete') {
				btns.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@l3j42t@${index}`} type='primary' onClick={() => this.handleClick(item)}>{item.menuName}</Button>);
			} else {
				btns.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@7ewb4x@${index}`} type='primary' onClick={() => this.handleClick(item)} disabled={tableStore.selectedRowKeys.length > 0 ? false : true} >{item.menuName}</Button>);
			}
		});
		return btns;
	}

	handleClick = (item) => {
		const {
			hrmLoginLog
		} = this.props, {
			isPanelShow,
			setPanelStatus
		} = hrmLoginLog;

		isPanelShow && setPanelStatus(false);
		this[item.menuFun] && this[item.menuFun]()
	}

	exportExcel = () => { //导出的excel有乱码现象，等待后期解决。
		const {
			hrmLoginLog
		} = this.props, {
			tableStore
		} = hrmLoginLog;

		tableStore.exportAll();
	}

	getDropPanelButtons() {
		const {
			hrmLoginLog
		} = this.props, {
			searchPanel,
			setPanelStatus,
			conditionForm
		} = hrmLoginLog, {
			form
		} = searchPanel;

		const btn = [
			(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@oub896`} type="primary" onClick={() => this.handleSearch()}>{i18n.button.search()}</Button>),
			(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@vdd6hw`} onClick={() => this.resetConditionValue()}>{i18n.button.reset()}</Button>),
			(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@63h29j`} onClick={() => setPanelStatus(false)}>{i18n.button.cancel()}</Button>),
		];
		return btn;
	}

	resetConditionValue = () => {
		const {
			hrmLoginLog
		} = this.props, {
			setSelectedValue,
			conditionForm
		} = hrmLoginLog
		conditionForm.resetConditionValue();
		setSelectedValue(['1', null, null]);
	}

	getTabName() {
		const tabDatas = [{
			key: '0',
			title: i18n.label.all()
		}, {
			key: '1',
			title: i18n.label.today()
		}, {
			key: '2',
			title: i18n.label.tswk()
		}, {
			key: '3',
			title: i18n.label.tsmth()
		}, {
			key: '4',
			title: i18n.label.tssn()
		}, {
			key: '5',
			title: i18n.label.tsyr()
		}]

		return tabDatas;
	}

	getBaseValueOfSearch() {
		const {
			hrmLoginLog
		} = this.props, {
			searchPanel,
			conditionForm
		} = hrmLoginLog, {
			form,
			value
		} = searchPanel;

		let val;
		if (conditionForm.isFormInit) {
			val = conditionForm.getFormParams().name;
		} else {
			val = value;
		}
		return val;
	}

	getPanelComponents() {
		const {
			hrmLoginLog
		} = this.props, {
			searchPanel,
			conditionForm,
		} = hrmLoginLog, {
			condition,
			form,
			loading
		} = searchPanel, {
			isFormInit
		} = conditionForm;

		let arr = [];
		isFormInit && condition.map(c => {
			c.items.map((field, index) => {
				if (field.domkey[0] == 'selectDate') {
					arr.push(this.getWeaDateGroup(1, field.label));
				} else {
					arr.push(<Col ecId={`${this && this.props && this.props.ecId || ''}_Col@f63eyt@${index}`} span={(index%2==0)?10:11} offset={1}>
                              <div style={{marginTop: 20}}>
                                  <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@vsj6q1@${index}`}
                                      label={`${field.label}`}
                                      labelCol={{span: 5}}
                                      wrapperCol={{span: 19}}>
                                          {<WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@zrgblm@${index}`} fieldConfig={field} form={conditionForm} formParams={conditionForm.getFormParams()} />}
                                  </WeaFormItem>
                              </div>
                  	     </Col>)
				}
			})
		})

		if (loading) {
			return (
				<div className='hrm-loading-center-small' style={{top:'30%'}}>
                    <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@qy7f3t`} spinning={loading}></Spin>
                </div>
			)
		} else {
			return <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@hwfd84`}
				onKeyDown={(e) =>( e.keyCode == 13 && e.target.tagName === "INPUT")  && this.handleSearch()}
			>{arr}</Row>
		}
	}

	getWeaDateGroup = (index, label) => {
		const {
			hrmLoginLog
		} = this.props, {
			searchPanel,
			setSelectedValue,
		} = hrmLoginLog, {
			selectedValue
		} = searchPanel, {
			datas
		} = this.state;

		return (<Col ecId={`${this && this.props && this.props.ecId || ''}_Col@uzhjd0`} span={(index%2==0)?10:11} offset={1}>
                    <div style={{marginTop: 20}}>
                        <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@9pkx67`}
                            label={label}
                            labelCol={{span:5}}
                            wrapperCol={{span: 19}}>
                            	<WeaDateGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaDateGroup@xj7wbi`}
						          	isMobx
						          	value={toJS(selectedValue)}
						          	datas={datas}
						          	onChange={v=> setSelectedValue(v)}
        						/>
                        </WeaFormItem>
                    </div>
                </Col>)
	}

	handleSearch() {
		const {
			hrmLoginLog
		} = this.props, {
			isPanelShow,
			setPanelStatus,
			getTableInfo
		} = hrmLoginLog;

		getTableInfo();
		isPanelShow && setPanelStatus(false);
	}

	handleSearchChange(val) {
		const {
			hrmLoginLog
		} = this.props, {
			setBaseValueOfSearch
		} = hrmLoginLog;

		setBaseValueOfSearch(val);
	}

	render() {
		const {
			hrmLoginLog
		} = this.props, {
			title,
			tableStore,
			loading,
			authorized,
			isPanelShow,
			key,
			searchPanel,
			setPanelStatus,
			switchKey,
			setBaseValueOfSearch,
			detachable,
			orgTreeProps
		} = hrmLoginLog, {
			conditionCount,
			value
		} = searchPanel;

		if (!authorized) {
			return (
				<div style={{height: '100%'}}>
					{loading ?  <div className='hrm-loading-center'>
									<Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@gefetj`} spinning={loading} size='large'></Spin>
								</div>
						     :	<div className="hrm-wea-alert-page">
		                			<WeaAlertPage ecId={`${this && this.props && this.props.ecId || ''}_WeaAlertPage@g6nqvf`}>
						                <div style={{ color: '#000' }}>
						                    {i18n.message.authFailed()}
						                </div>
		                      		</WeaAlertPage>
	                        	</div>
	                }	
                </div>
			)
		} else {
			const coms = [
				(
					<WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@6srnmm`}
					        searchType={['advanced']}
					        showSearchAd={isPanelShow}
					        hasMask={false}
					        advanceHeight={Math.ceil(conditionCount / 2)*52+20}
					        keyParam={'key'}
					        selectedKey={key}
					        onChange={key => switchKey(key)}
					        datas={this.getTabName()}
					        buttonsAd={this.getDropPanelButtons()}
					        searchsBaseValue={value}
					        setShowSearchAd={  b => setPanelStatus(b)}
					        hideSearchAd={ () => setPanelStatus(false)}
					        searchsAd= {isPanelShow ? this.getPanelComponents():<div></div>}
					        onSearch={() => this.handleSearch()}
					        onSearchChange={val => setBaseValueOfSearch(val)}
					    />
				),
				(
					<WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@341l1l`} 
					        comsWeaTableStore={tableStore}
					        hasOrder={true}
					        needScroll={true}
					        getColumns={columns => {
					        	columns.map(c =>{
					        		if (c.dataIndex === "operateUserId") {
					        			c.render = (text, record) => {
											const {
												operateUserId,
												operateUserIdspan
											} = record;

											return (
												<a href={`javaScript:openhrm(${operateUserId});`} onClick={e => window.pointerXY(e)} title={operateUserIdspan}><div dangerouslySetInnerHTML={{ __html: operateUserIdspan }} /></a>
											)
										}
					        		}
					        	})
					        }}
					    />
				)
			];
			let children;
			if(detachable){
				children = (
					<WeaLeftRightLayout ecId={`${this && this.props && this.props.ecId || ''}_WeaLeftRightLayout@pjc44w`} leftCom={<OrganizationTree ecId={`${this && this.props && this.props.ecId || ''}_OrganizationTree@iq0gnj`} {...orgTreeProps} ref='orgTree'/>}>
						{coms}
					</WeaLeftRightLayout>
				)
			}else{
				children = coms;
			}
			return (
				<WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@n3e96v`} 
					datas={this.getDropMenuDatas()} 
					onClick={ key => this.handleMenuClick(key)}
					collectParams={{favname:title,favouritetype:5}}
				>
				        <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@zec1au`} 
				            title={title}
				            icon={<i className='icon-coms-hrm'/>}
				            iconBgcolor='#217346'
				            loading={true}
				            buttons={this.getTopMenuBtns()}
				            showDropIcon={true}
				            dropMenuDatas={this.getDropMenuDatas()}
				            onDropMenuClick={e => this.handleMenuClick(e)}
				        >
					    {children}
				    </WeaTop>
				</WeaRightMenu>
			)
		}
	}

}