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

import Editor from './Editor';

@inject('hrmTrainResource')
@observer
export default class TrainResource 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.trainResource();
		}
	}

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

	componentDidMount() {
		this.init();
	}

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

		mobxDatasReset();
		getRight();
	}

	getDropMenuDatas = () => {
		const {
			hrmTrainResource
		} = this.props, {
			menu,
			table,
		} = hrmTrainResource, {
			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 {
			hrmTrainResource
		} = this.props, {
			isPanelShow,
			setPanelStatus
		} = hrmTrainResource;

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

	getTopMenuBtns = () => {
		const {
			hrmTrainResource
		} = this.props, {
			menu,
			table,
		} = hrmTrainResource, {
			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@euanot@${index}`} type='primary' onClick={() => this.handleClick(item)}>{item.menuName}</Button>);
			} else {
				btns.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@j1bvjf@${index}`} type='primary' onClick={() => this.handleClick(item)} disabled={tableStore.selectedRowKeys.length > 0 ? false : true} >{item.menuName}</Button>);
			}
		});
		return btns;
	}

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

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

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

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

		setEditorDialogVisible(true, 'new');
	}

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

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

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

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

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

		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 {
			hrmTrainResource
		} = this.props, {
			deleteTableRows
		} = hrmTrainResource;

		deleteTableRows();
	}

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

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

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

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

	getPanelComponents() {
		const {
			hrmTrainResource
		} = this.props, {
			searchPanel
		} = hrmTrainResource, {
			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@djmk0c@${index}`} span={10} offset={1}>
                              <div style={{marginTop: 20}}>
                                  <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@j2gykk@${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@pez8pr@${index}`} fieldConfig={field} form={form} formParams={form.getFormParams()} />}
                                  </WeaFormItem>
                              </div>
                  	     </Col>)
			})
		})
		return <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@8btm9k`} spinning={loading}><Row ecId={`${this && this.props && this.props.ecId || ''}_Row@yu6ccx`}
			onKeyDown={(e) =>( e.keyCode == 13 && e.target.tagName === "INPUT")  && this.handleSearch()}
		>{arr}</Row></Spin>
	}

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

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

	handleSearchChange(val) {
		const {
			hrmTrainResource
		} = this.props, {
			searchPanel,
			updateFields,
			setBaseValueOfSearch
		} = hrmTrainResource, {
			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 <a onClick={() => jumpToHrmCard(record.typeoperator)} >{record.typeoperatorspan}</a>
				}
			};
		})
	}

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

		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: '3035',
					targetId: id,
				});
				break;
		}
	}

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

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

	render() {
		const {
			hrmTrainResource
		} = this.props, {
			authorized,
			loading,
			title,
			isPanelShow,
			table,
			searchPanel,
			editor,
			setPanelStatus,
			setEditorDialogVisible,
		} = hrmTrainResource, {
			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@gnrygf`} spinning={loading} size='large'></Spin>
								</div>
						     :	<div className="hrm-wea-alert-page">
		                			<WeaAlertPage ecId={`${this && this.props && this.props.ecId || ''}_WeaAlertPage@l6kakx`}>
						                <div style={{ color: '#000' }}>
						                    {i18n.message.authFailed()}
						                </div>
		                      		</WeaAlertPage>
	                        	</div>
	                }	
                </div>
			)
		} else {
			return (
				<WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@tzrae6`} 
					datas={this.getDropMenuDatas()} 
					onClick={ key => this.handleMenuClick(key)}
					collectParams={{favname: title,favouritetype:5}}
				>
				        <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@leuvct`} 
				            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@1xj7w1`}
					            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@u5ocm7`} 
					            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@sx27yt`} />}
				        </WeaTop>
				    </WeaRightMenu>
			)
		}
	}


}