import React from 'react'
import {
	toJS
} from 'mobx'
import {
	inject,
	observer,
} from 'mobx-react'
import {
	WeaTop,
	WeaTab,
	WeaFormItem,
	WeaRightMenu,
	WeaAlertPage,
	WeaPopoverHrm,
} from 'ecCom'
import {
	WeaSwitch,
	WeaTableNew,
} from 'comsMobx'
import {
	Row,
	Col,
	Spin,
	Modal,
	Button,
	message,
} from 'antd'
import {
	i18n
} from '../../public/i18n';
const confirm = Modal.confirm;
const WeaTable = WeaTableNew.WeaTable;

import Editor from './Editor';

@inject('hrmTrainTypes')
@observer
export default class TrainTypes 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.trainTypes();
		}
	}

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

	componentDidMount() {
		this.init();
	}

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

		mobxDatasReset();
		getRight();
	}

	getDropMenuDatas = () => {
		const {
			hrmTrainTypes
		} = this.props, {
			menu,
			table,
		} = hrmTrainTypes, {
			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 == 'collection' || item.menuFun == 'help' || item.menuFun == 'pageAddress') {
				obj.disabled = true;
			}
			if (item.menuFun == 'batchDelete') {
				obj.disabled = (table.tableStore.selectedRowKeys.length > 0) ? false : true;
			}
			menus.push(obj);
		})

		return menus;
	}

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

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

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

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

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

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

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

	new() {
		const {
			hrmTrainTypes
		} = this.props, {
			setEditorDialogVisible
		} = hrmTrainTypes

		setEditorDialogVisible(true, 'new');
	}

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

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

	batchDelete() {
		const {
			hrmTrainTypes
		} = this.props, {
			table,
			setSelectedRowsKeys,
		} = hrmTrainTypes, {
			tableStore,
		} = table;

		let keys = toJS(tableStore.selectedRowKeys).toString();
		if (!keys) {
			message.warning(i18n.message.pleaseConfirmDelRows());
			return;
		}
		setSelectedRowsKeys(keys);
		this.deleteRows();
	}

	deleteRows(id) {
		const {
			hrmTrainTypes
		} = this.props, {
			setSelectedRowsKeys
		} = hrmTrainTypes;

		id && setSelectedRowsKeys(id);
		let v = id ? 'del' : 'batchDel';
		this.showConfirm(v);
	}

	showConfirm(v) {
		let _this = this;
		confirm({
			title: i18n.confirm.defaultTitle(),
			content: (v == 'del') ? i18n.confirm.delete() : i18n.confirm.batchDeleteConfirm(),
			okText: i18n.button.ok(),
			cancelText: i18n.button.cancel(),
			onOk() {
				_this.onOk()
			},
			onCancel() {
				return false
			},
		});
	}

	onOk() {
		const {
			hrmTrainTypes
		} = this.props, {
			deleteTableRows
		} = hrmTrainTypes;

		deleteTableRows();
	}

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

		const btn = [
			(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@rz84is`} type="primary" onClick={() => this.handleSearch()}>{i18n.button.search()}</Button>),
			(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@0esny4`} onClick={() => form.reset()}>{i18n.button.reset()}</Button>),
			(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@511c0a`} onClick={() => setPanelStatus(false)}>{i18n.button.cancel()}</Button>),
		];
		return btn;
	}

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

		let val;
		if (form.isFormInit) {
			val = form.getFormParams().trainTypeName;
		} else {
			val = value;
		}
		return val;
	}

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

		let arr = [];
		isFormInit && condition.map(c => {
			c.items.map((field, index) => {
				arr.push(<Col ecId={`${this && this.props && this.props.ecId || ''}_Col@8u89l8@${index}`} span={10} offset={1}>
                              <div style={{marginTop: 20}}>
                                  <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@jxvduh@${index}`}
                                      label={`${field.label}`}
                                      labelCol={{span: (index % 2 == 0) ? 7 : 6}}
                                      wrapperCol={{span: (index % 2 == 0) ? 17 : 18}}>
                                          {<WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@1a719q@${index}`} fieldConfig={field} form={form} formParams={form.getFormParams()} />}
                                  </WeaFormItem>
                              </div>
                  	     </Col>)
			})
		})

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

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

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

	handleSearchChange(val) {
		const {
			hrmTrainTypes
		} = this.props, {
			searchPanel,
			updateFields,
			setBaseValueOfSearch
		} = hrmTrainTypes, {
			form
		} = searchPanel

		if (form.isFormInit) {
			updateFields(val);
		}
		setBaseValueOfSearch(val);
	}

	reRenderColumns(columns) {
		let _this = this;
		columns.forEach((c, index) => {
			if (c.dataIndex == 'name') {
				c.render = function(text, record) {
					return <a onClick={() => _this.doEdit(record.randomFieldId)}>{record.name}</a>
				}
			};
			if (c.dataIndex == 'typeoperator') {
				c.render = function(text, record) {
					return _this.getHrefs(record);
				}
			};
		})
	}

	getHrefs = (record) => {
		const {
			typeoperator,
			typeoperatorspan
		} = record;

		let names = typeoperatorspan.split(' ').filter(item => item),
			children = [];

		typeoperator.split(',').map((id, index) => {
			children.push(<span> <WeaPopoverHrm ecId={`${this && this.props && this.props.ecId || ''}_WeaPopoverHrm@9p7r0a@${index}`} /><a href={`javaScript:openhrm(${id})`} onClick={e => window.pointerXY(e)} style={{ marginLeft: 3}}>{names[index]}</a></span>);
		});

		return <p>{children}</p>;

	}

	onOperatesClick(record, index, operate) {
		const {
			hrmTrainTypes
		} = this.props, {
			setEditorDialogVisible,
			setSelectedRowsKeys
		} = hrmTrainTypes;

		let i = operate.index,
			id = record.randomFieldId;

		switch (i) {
			case '0': //编辑
				this.doEdit(id)
				break;
			case '1': //删除
				this.deleteRows(id)
				break;
			case '2':
				window.setLogViewProps({
					logSmallType: '3033',
					targetId: id,
				});
				break;
		}
	}

	doEdit = (id) => {
		const {
			hrmTrainTypes
		} = this.props, {
			setSelectedRowsKeys,
			setEditorDialogVisible,
		} = hrmTrainTypes;

		setSelectedRowsKeys(id);
		setEditorDialogVisible(true, 'edit');
	}

	render() {
		const {
			hrmTrainTypes
		} = this.props, {
			authorized,
			loading,
			title,
			isPanelShow,
			table,
			searchPanel,
			editor,
			setPanelStatus,
			setEditorDialogVisible,
		} = hrmTrainTypes, {
			tableStore
		} = table, {
			conditionCount
		} = searchPanel;

		if (!authorized) {
			return (
				<div style={{height: '100%'}}>
					{loading ?  <div className='hrm-loading-center'>
									<Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@d3032j`} spinning={loading} size='large'></Spin>
								</div>
						     :	<div className="hrm-wea-alert-page">
		                			<WeaAlertPage ecId={`${this && this.props && this.props.ecId || ''}_WeaAlertPage@gsp16p`}>
						                <div style={{ color: '#000' }}>
						                    {i18n.message.authFailed()}
						                </div>
		                      		</WeaAlertPage>
	                        	</div>
	                }	
                </div>
			)
		} else {
			return (
				<WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@khgh3x`} 
					datas={this.getDropMenuDatas()} 
					onClick={ key => this.handleMenuClick(key)}
					collectParams={{favname: title,favouritetype:5}}
				>
				        <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@q90i0x`} 
				            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)}
				        >
				        	<WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@d2e3h8`}
					            searchType={['base','advanced']}
					            showSearchAd={isPanelShow}
					            hasMask={false}
					            advanceHeight={Math.ceil(conditionCount / 2)*52+20}
					            buttonsAd={this.getDropPanelButtons()}
					            searchsBaseValue={this.getBaseValueOfSearch()}
					            setShowSearchAd={  b => setPanelStatus(b)}
					            hideSearchAd={ () => setPanelStatus(false)}
					            searchsAd= {isPanelShow ? this.getPanelComponents():<div></div>}
					            onSearch={() => this.handleSearch()}
					            onSearchChange={val => this.handleSearchChange(val)}
					        />
				        	<WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@ag595o`} 
					            comsWeaTableStore={tableStore}
					            hasOrder={true}
					            needScroll={true}
					            getColumns={c => this.reRenderColumns(c)}
					            onOperatesClick={(record, index, operate) => this.onOperatesClick(record, index, operate)}
					        />
					        {editor.visible && <Editor ecId={`${this && this.props && this.props.ecId || ''}_Editor@fffes4`} />}
				        </WeaTop>
				    </WeaRightMenu>
			)
		}
	}


}