import React from 'react'
import {
	toJS
} from 'mobx'

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

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

import {
	Row,
	Col,
	Spin,
	Modal,
	Button,
	message,
} from 'antd'

import {
	WeaSwitch,
	WeaTableNew,
} from 'comsMobx'

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

import Editor from './Editor'

const confirm = Modal.confirm;
const WeaTable = WeaTableNew.WeaTable;

import '../../style/moduleManage.css'

@inject('hrmModuleManageSet')
@observer
export default class ModuleManage 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.moduleManagementDecent();
		}
	}

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

	componentDidMount() {
		this.init();
	}


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

		mobxDatasReset();
		getRight();
	}

	getDropMenuDatas = () => {
		const {
			hrmModuleManageSet
		} = this.props, {
			menu
		} = hrmModuleManageSet, {
			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;
			}
			menus.push(obj);
		})

		return menus;
	}

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

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

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

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

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

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

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

		setEditorDialogVisible(true, 'new');
	}

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

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

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

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

		deleteTableRows();
	}

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

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

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

	editorSave() {
		const {
			hrmModuleManageSet
		} = this.props, {
			editor,
			addModuleManageInfo,
		} = hrmModuleManageSet;

		addModuleManageInfo();
	}

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

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

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

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

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

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

	handlePanelStatus(bool) {
		const {
			hrmModuleManageSet
		} = this.props, {
			searchPanel,
			setPanelStatus,
			getSearchCondition
		} = hrmModuleManageSet, {
			condition
		} = searchPanel;

		if (bool) {
			setPanelStatus(true);
			condition.length == 0 && getSearchCondition(); //第一次打开面板时加载数据
		} else {
			setPanelStatus(false);
		}
	}

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

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

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

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

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

		switch (i) {
			case '0': //编辑
				this.doEdit(id)
				break;
			case '1': //删除
				this.deleteRows(id)
				break;
		}
	}

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

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

	render() {
		const {
			hrmModuleManageSet
		} = this.props, {
			loading,
			title,
			isPanelShow,
			setPanelStatus,
			tableStore,
			searchPanel,
			editor,
			setEditorDialogVisible,
			setSelectedValue,
			setDialogSaveButtonStatus,
			authorized,
			date,
		} = hrmModuleManageSet, {
			conditionCount,
			form
		} = searchPanel;

		if (!authorized) {
			return (
				<div style={{height: '100%'}}>
					{loading ?  <div className='hrm-loading-center'>
									<Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@l9siln`} spinning={loading} size='large'></Spin>
								</div>
						     :	<div className="hrm-wea-alert-page">
		                			<WeaAlertPage ecId={`${this && this.props && this.props.ecId || ''}_WeaAlertPage@gidj4w`}>
						                <div style={{ color: '#000' }}>
						                    {i18n.message.authFailed()}
						                </div>
		                      		</WeaAlertPage>
	                        	</div>
	                }	
                </div>
			)
		} else {
			return (
				<div>
					<WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@3jxgle`} 
						datas={this.getDropMenuDatas()} 
						onClick={ key => this.handleMenuClick(key)}
						collectParams={{favname:title,favouritetype:5}}
					>
				        <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@l6sfdx`} 
				            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@w8urxr`}
					            searchType={['base','advanced']}
					            showSearchAd={isPanelShow}
					            hasMask={false}
					            advanceHeight={Math.ceil(conditionCount / 2)*52+20}
					            buttonsAd={this.getDropPanelButtons()}
					            searchsBaseValue={this.getBaseValueOfSearch()}
					            setShowSearchAd={  b => this.handlePanelStatus(b)}
					            hideSearchAd={ () => setPanelStatus(false)}
					            searchsAd= {<div
									onKeyDown={(e) =>( e.keyCode == 13 && e.target.tagName === "INPUT")  && this.handleSearch()}
					            >{form.render()}</div>}
					            onSearch={() => this.handleSearch()}
					            onSearchChange={val => this.handleSearchChange(val)}
					        />
					        <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@spiwhd`} 
					            comsWeaTableStore={tableStore}
					            hasOrder={true}
					            needScroll={true}
					            getColumns={c => this.reRenderColumns(c)}
					            onOperatesClick={(record, index, operate) => this.onOperatesClick(record, index, operate)}
					        />
						</WeaTop>
					</WeaRightMenu>
					<Editor ecId={`${this && this.props && this.props.ecId || ''}_Editor@cqxm0a`} 
	                    {...editor}
	                    isFormInit={editor.form.isFormInit}
	                    isCheckboxFormInit={editor.checkboxForm.isFormInit}
	                    save={() => this.editorSave()}
	                    onCancel={() => setEditorDialogVisible(false)}
	                    setSelectedValue={val => setSelectedValue(val, false)}
	                    setDialogSaveButtonStatus={bool => setDialogSaveButtonStatus(bool)}
	                />
				</div>
			)
		}


	}

}