import React from 'react'
import {
	toJS
} from 'mobx'
import {
	inject,
	observer,
} from 'mobx-react'
import {
	WeaTop,
	WeaTab,
	WeaFormItem,
	WeaRightMenu,
	WeaAlertPage,
	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('hrmSalaryIndexSetting')
@observer
export default class SalaryIndexSetting 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.salaryIndexSetting();
		}
	}

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

	componentDidMount() {
		this.init();
	}

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

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

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

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

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

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

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

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

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

		setEditorDialogVisible(true, 'new');
	}

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

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


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

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

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

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

		deleteTableRows();
	}

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

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

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

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

	getPanelComponents() {
		const {
			hrmSalaryIndexSetting
		} = this.props, {
			searchPanel
		} = hrmSalaryIndexSetting, {
			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@kperx6@${index}`} span={10} offset={(index%2==0)?1:2}>
                              <div style={{marginTop: 20}}>
                                  <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@pyltes@${index}`}
                                      label={`${field.label}`}
                                      labelCol={{span: 6}}
                                      wrapperCol={{span: 18}}>
                                          {<WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@imr5eb@${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@2ejujt`} spinning={loading}></Spin>
                </div>
			)
		} else {
			return <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@zjan9k`}
				onKeyDown={(e) =>( e.keyCode == 13 && e.target.tagName === "INPUT")  && this.handleSearch()}
			>{arr}</Row>
		}
	}

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

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

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

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

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

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

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

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

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

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

	render() {
		const {
			hrmSalaryIndexSetting
		} = this.props, {
			authorized,
			loading,
			title,
			isPanelShow,
			table,
			searchPanel,
			editor,
			leftTree,
			setPanelStatus,
			setEditorDialogVisible,
		} = hrmSalaryIndexSetting, {
			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@100108`} spinning={loading} size='large'></Spin>
								</div>
						     :	<div className="hrm-wea-alert-page">
		                			<WeaAlertPage ecId={`${this && this.props && this.props.ecId || ''}_WeaAlertPage@bix38c`}>
						                <div style={{ color: '#000' }}>
						                    {i18n.message.authFailed()}
						                </div>
		                      		</WeaAlertPage>
	                        	</div>
	                }	
                </div>
			)
		} else {
			return (
				<div>
					<WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@vuls5z`} 
						datas={this.getDropMenuDatas()} 
						onClick={ key => this.handleMenuClick(key)}
						collectParams={{favname: title,favouritetype:5}}
					>
				            <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@eu7unh`} 
				                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@op9swi`} 
					            isNew={true}
					            leftCom={<LeftTree ecId={`${this && this.props && this.props.ecId || ''}_LeftTree@0ikoi6`} triggerRefresh={triggerRefresh}/>}
					        >
					        	<WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@cqm9yv`}
					                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@g4hcqo`} 
					                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@n6v192`} />
				</div>
			)
		}

	}
}