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';
import {addContentPath} from '../../util/index.js'
const confirm = Modal.confirm;
const WeaTable = WeaTableNew.WeaTable;

import Editor from './Editor'
import LeftTree from './LeftTree'
import '../../style/salaryIndexMaintenance.css'

@inject('hrmSalaryIndexMaintenance')
@observer
export default class SalaryIndexMaintenance 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.salaryIndexMaintenance();
		}
	}

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

	componentDidMount() {
		this.init();
	}

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

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

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

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

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

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

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

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

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

		setEditorDialogVisible(true, 'new');
	}

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

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

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

		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
			},
		});
	}

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

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

	onOk() {
		const {
			hrmSalaryIndexMaintenance
		} = this.props, {
			deleteTableRows
		} = hrmSalaryIndexMaintenance;

		deleteTableRows();
	}

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

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

	getPanelComponents() {
		const {
			hrmSalaryIndexMaintenance
		} = this.props, {
			searchPanel
		} = hrmSalaryIndexMaintenance, {
			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@xuxri4@${index}`} span={10} offset={1}>
                              <div style={{marginTop: 20}} className='hrm-salary-index-datepicker'>
                                  <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@2p4ow0@${index}`}
                                      label={`${field.label}`}
                                      labelCol={{span: 6}}
                                      wrapperCol={{span: 18}}>
                                          {<WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@l1sh6d@${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@lrg8m4`} spinning={loading}></Spin>
                </div>
			)
		} else {
			return <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@co4v7n`}
				onKeyDown={(e) =>( e.keyCode == 13 && e.target.tagName === "INPUT")  && this.handleSearch()}
			>{arr}</Row>
		}
	}

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

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

	reRenderColumns(columns) {
		let _this = this;
		columns.forEach((c, index) => {
			if (c.dataIndex == 'subcompanyid') {
				c.render = function(text, record) {
					const {
						subcompanyid,
						subcompanyidspan
					} = record;
					return <a href={addContentPath(`/spa/hrm/engine.html#/hrmengine/organization?showTree=false&type=subcompany&id=${subcompanyid}`) } target='_blank'>{subcompanyidspan}</a>
				}
			};
			if (c.dataIndex == 'yearmonth' || c.dataIndex == 'empNum') {
				c.render = function(text, record) {
					const {
						randomFieldId,
						yearmonth,
						empNumspan
					} = record;

					return <a onClick={() => _this.doEdit(randomFieldId)} >{c.dataIndex == 'yearmonth' ? yearmonth : empNumspan}</a>
				}
			};
		})
	}

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

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

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

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

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

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

		if (!authorized) {
			return (
				<div style={{height: '100%'}}>
					{loading ?  <div className='hrm-loading-center'>
									<Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@t5opkg`} spinning={loading} size='large'></Spin>
								</div>
						     :	<div className="hrm-wea-alert-page">
		                			<WeaAlertPage ecId={`${this && this.props && this.props.ecId || ''}_WeaAlertPage@ts1ea8`}>
						                <div style={{ color: '#000' }}>
						                    {i18n.message.authFailed()}
						                </div>
		                      		</WeaAlertPage>
	                        	</div>
	                }	
                </div>
			)
		} else {
			return (
				<div>
					<WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@88sm9h`} 
						datas={this.getDropMenuDatas()} 
						onClick={ key => this.handleMenuClick(key)}
						collectParams={{favname: title,favouritetype:5}}
					>
					    <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@r0a31i`} 
					        title={title}
					        icon={<i className='icon-coms-hrm'/>}
					        iconBgcolor='#217346'
					        buttons={this.getTopMenuBtns()}
					        showDropIcon={true}
					        dropMenuDatas={this.getDropMenuDatas()}
					        onDropMenuClick={e => this.handleMenuClick(e)}
					    >
					  		<WeaLeftRightLayout ecId={`${this && this.props && this.props.ecId || ''}_WeaLeftRightLayout@kn72fk`} 
							    isNew={true}
							    leftCom={<LeftTree ecId={`${this && this.props && this.props.ecId || ''}_LeftTree@l0mkc7`} triggerRefresh={triggerRefresh}/>}
							>
						      	{nodeType == '0' && <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@1otgb4`}
											            searchType={['base','advanced']}
											            showSearchAd={isPanelShow}
											            hasMask={false}
											            advanceHeight={Math.ceil(conditionCount / 2)*52+20}
											            buttonsAd={this.getDropPanelButtons()}
											            searchsBaseValue={value}
											            setShowSearchAd={  b => setPanelStatus(b)}
											            hideSearchAd={ () => setPanelStatus(false)}
											            searchsAd= {isPanelShow ? this.getPanelComponents():<div></div>}
											            onSearch={() => this.handleSearch()}
											            onSearchChange={val => setBaseValueOfSearch(val)}/>
								}
						      	<WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@bubxc9`} 
						            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@0rfyzk`} />
				</div>
			)
		}
	}
}