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';
import Test from './Test';
import '../../style/trainPlan.css'

@inject('hrmTrainPlan')
@observer
export default class TrainPlan 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.trainPlan();
		}
	}

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

	componentDidMount() {
		this.init();
	}

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

		mobxDatasReset();
		getRight();
	}

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

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

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

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

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

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

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

		setEditorDialogVisible(true, 'new');
	}

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

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

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

		let keys = toJS(tableStore.selectedRowKeys).toString();
		setSelectedRowsKeys(keys);
		this.deleteRows();
	}

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

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

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

	onOk = (oper) => {
		const {
			hrmTrainPlan
		} = this.props, {
			deleteTableRows,
			inform
		} = hrmTrainPlan;

		['del', 'batchDel'].includes(oper) ? deleteTableRows() : inform();
	}

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

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

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

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

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

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

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

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

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

	reRenderColumns(columns) {
		const {
			hrmTrainPlan
		} = this.props, {
			table
		} = hrmTrainPlan, {
			canView
		} = table;

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

	getHrefs = (record) => {
		const {
			layoutassessor,
			layoutassessorspan
		} = record;

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

		layoutassessor.split(',').map((id, index) => {
			children.push(<span> <WeaPopoverHrm ecId={`${this && this.props && this.props.ecId || ''}_WeaPopoverHrm@5yc0f5@${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 {
			hrmTrainPlan
		} = this.props, {
			setEditorDialogVisible,
			setSelectedRowsKeys
		} = hrmTrainPlan;

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

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

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

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

	test = (id) => {
		const {
			hrmTrainPlan
		} = this.props, {
			setSelectedRowsKeys,
			setTestDialogVisible
		} = hrmTrainPlan;

		setSelectedRowsKeys(id);
		setTestDialogVisible(true);
	}

	inform = (id) => {
		const {
			hrmTrainPlan
		} = this.props, {
			setSelectedRowsKeys,
		} = hrmTrainPlan;

		setSelectedRowsKeys(id);
		this.showConfirm('inform');
	}

	render() {
		const {
			hrmTrainPlan
		} = this.props, {
			authorized,
			loading,
			title,
			isPanelShow,
			table,
			searchPanel,
			editor,
			setPanelStatus,
			setEditorDialogVisible,
			test,
		} = hrmTrainPlan, {
			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@loyj3i`} spinning={loading} size='large'></Spin>
								</div>
						     :	<div className="hrm-wea-alert-page">
		                			<WeaAlertPage ecId={`${this && this.props && this.props.ecId || ''}_WeaAlertPage@md6zt8`}>
						                <div style={{ color: '#000' }}>
						                    {i18n.message.authFailed()}
						                </div>
		                      		</WeaAlertPage>
	                        	</div>
	                }	
                </div>
			)
		} else {
			return (
				<WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@p3xu23`} 
					datas={this.getDropMenuDatas()} 
					onClick={ key => this.handleMenuClick(key)}
					collectParams={{favname: title,favouritetype:5}}
				>
				        <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@9gbmjn`} 
				            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@7srr5z`}
					            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@n5w3aa`} 
					            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@0ko1bv`} />}
					        {test.visible && <Test ecId={`${this && this.props && this.props.ecId || ''}_Test@i7rlc9`} />}
				        </WeaTop>
				    </WeaRightMenu>
			)
		}
	}


}