import React from 'react'
import {
	toJS
} from 'mobx'
import {
	inject,
	observer,
} from 'mobx-react'
import {
	WeaTop,
	WeaTab,
	WeaFormItem,
	WeaRightMenu,
	WeaAlertPage,
	WeaPopoverHrm,
	WeaLeftRightLayout,
} 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 LeftTree from './LeftTree'

@inject('hrmSignatureManagement')
@observer
export default class SignatureManagement 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.signatureManagement();
		}
	}

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

	componentDidMount() {
		this.init();
	}

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

		mobxDatasReset();
		getRight();
		forceLeftTreeRefresh();
	}

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

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

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

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

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

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

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

		setEditorDialogVisible(true, 'new');
	}

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

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

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

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

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

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

		deleteTableRows();
	}

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

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

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

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

	getPanelComponents() {
		const {
			hrmSignatureManagement
		} = this.props, {
			searchPanel
		} = hrmSignatureManagement, {
			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@m8gp5f@${index}`} span={10} offset={1}>
                              <div style={{marginTop: 20}}>
                                  <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@mq1spo@${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@rps1h6@${index}`} fieldConfig={field} form={form} formParams={form.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@8c0jtd`} spinning={loading}></Spin>
				</div>
			)
		} else {
			return <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@mnc19s`}
				onKeyDown={(e) =>( e.keyCode == 13 && e.target.tagName === "INPUT")  && this.handleSearch()}
			>{arr}</Row>
		}

	}

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

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

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

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

	reRenderColumns(columns) {
		let _this = this;
		columns.forEach((c, index) => {
			if (c.dataIndex == 'hrmresid') {
				c.render = function(t, r) {
					return <a href={`javaScript:openhrm(${r.hrmresid})`} onClick={e => window.pointerXY(e)} >{r.hrmresidspan}</a>
				}
			};
			if (c.dataIndex == 'MarkName') {
				c.render = function(t, r) {
					return <a onClick={() => _this.doEdit(r.randomFieldId)} >{r.MarkName}</a>
				}
			};
		})
	}

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

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

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

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

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

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

		if (!authorized) {
			return (
				<div style={{height: '100%'}}>
					{loading ?  <div className='hrm-loading-center'>
									<Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@hb0ogk`} spinning={loading} size='large'></Spin>
								</div>
						     :	<div className="hrm-wea-alert-page">
		                			<WeaAlertPage ecId={`${this && this.props && this.props.ecId || ''}_WeaAlertPage@gnbrzk`}>
						                <div style={{ color: '#000' }}>
						                    {i18n.message.authFailed()}
						                </div>
		                      		</WeaAlertPage>
	                        	</div>
	                }	
                </div>
			)
		} else {
			return (
				<div>
					<WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@a4cdmo`} 
						datas={this.getDropMenuDatas()} 
						onClick={ key => this.handleMenuClick(key)}
						collectParams={{favname: title(),favouritetype:5}}
					>
				            <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@ym8n0q`} 
				                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)}
				            >
				            <WeaLeftRightLayout ecId={`${this && this.props && this.props.ecId || ''}_WeaLeftRightLayout@bwqq30`} 
					            isNew={true}
					            leftCom={<LeftTree ecId={`${this && this.props && this.props.ecId || ''}_LeftTree@cvmihl`} triggerRefresh={triggerRefresh}/>}
					        >
					        	<WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@v53fwg`}
					                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@156ybo`} 
					                comsWeaTableStore={tableStore}
					                hasOrder={true}
					                needScroll={true}
					                getColumns={c => this.reRenderColumns(c)}
					                onOperatesClick={(record, index, operate) => this.onOperatesClick(record, index, operate)}
					            />
					        </WeaLeftRightLayout>
				        </WeaTop>
				    </WeaRightMenu>
				    <Editor ecId={`${this && this.props && this.props.ecId || ''}_Editor@dsww3g`} />
				</div>
			)
		}

	}
}