import React from 'react'
import {
	toJS
} from 'mobx'
import {
	inject,
	observer,
} from 'mobx-react'
import {
	WeaTop,
	WeaTab,
	WeaFormItem,
	WeaRightMenu,
	WeaAlertPage,
	WeaLeftRightLayout,
	WeaTableEdit,
	WeaLocaleProvider,
} from 'ecCom'
import {
	WeaSwitch,
	WeaTableNew,
} from 'comsMobx'
import {
	Row,
	Col,
	Spin,
	Modal,
	Button,
	message,
} from 'antd';
import {
	i18n
} from '../../public/i18n';
import {
	IEVersion
} from '../../public/pulic-func'
const confirm = Modal.confirm;
const WeaTable = WeaTableNew.WeaTable;
const getLabel = WeaLocaleProvider.getLabel;

import Editor from './Editor'
import LeftTree from './LeftTree'
import '../../style/payrollManagement.less'

@inject('hrmPayrollManagement')
@observer
export default class PayrollManagement 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.payrollManagement();
		}
	}

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

	componentDidMount() {
		this.init();
	}

	init() {
		const {
			hrmPayrollManagement
		} = this.props, {
			getPageAuth,
			resetObserableDatas,
			forceLeftTreeRefresh,
		} = hrmPayrollManagement

		resetObserableDatas();
		getPageAuth();
		forceLeftTreeRefresh();
	}

	getDropMenuDatas = () => {
		const {
			hrmPayrollManagement
		} = this.props, {
			menu,
			table,
			searchPanel,
			exportUrl
		} = hrmPayrollManagement, {
			rightMenu
		} = menu, {
			selectedRowsIds,
			datas,
		} = table;

		let menus = [];
		toJS(rightMenu).map((item, index) => {
			const func = item.menuFun;

			let obj = {
				key: item.menuFun,
				icon: <i className={`${item.menuIcon}`}/>,
			};
			// if (func == 'exportPayroll') {
			// 	obj.content = <a href={exportUrl} style={{display: 'inline-block',color:'#000'}}>{item.menuName}</a>;
			// } else {
			// 	obj.content = item.menuName;
			// }
			obj.content = item.menuName;

			if (func == 'custom' || func == 'collection' || func == 'help' || func == 'pageAddress') {
				obj.disabled = true;
			}
			if (func == 'sendPayroll') {
				obj.disabled = selectedRowsIds ? false : true;
			}
			if (func == 'edit' || func == 'adjustSalarySetting' || func == 'closePayroll' || func == 'exportPayroll') {
				obj.disabled = (toJS(datas).length > 0 && !table.loading) ? false : true;
			}
			if (func == 'createPayroll' || func == 'openHistoryPayroll') {
				obj.disabled = table.loading ? true : false;
			}
			menus.push(obj);
		})

		return menus;
	}

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

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

	getTopMenuBtns = () => {
		const {
			hrmPayrollManagement
		} = this.props, {
			menu,
			table,
			searchPanel
		} = hrmPayrollManagement, {
			topMenu
		} = menu, {
			tableStore,
			selectedRowsIds,
			datas,
		} = table;

		let btns = [];
		toJS(topMenu).map((item, index) => {
			const func = item.menuFun;
			if (func == 'batchDelete') {
				btns.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@1tawh1@${index}`} type='primary' onClick={() => this.handleClick(item)} disabled={tableStore.selectedRowKeys.length > 0 ? false : true} >{item.menuName}</Button>);
			} else if (func == 'sendPayroll') {
				btns.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@g11p0v@${index}`} type='primary' onClick={() => this.handleClick(item)} disabled={selectedRowsIds ? false : true} >{item.menuName}</Button>);
			} else if (func == 'edit' || func == 'closePayroll') {
				btns.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@wh6bc6@${index}`} type='primary' onClick={() => this.handleClick(item)} disabled={(toJS(datas).length > 0 && !table.loading) ? false : true} >{item.menuName}</Button>);
			} else if (func == 'createPayroll') {
				btns.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@1e3fr0@${index}`} type='primary' onClick={() => this.handleClick(item)} disabled={table.loading ? true : false} >{item.menuName}</Button>);
			} else {
				btns.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@tspyh2@${index}`} type='primary' onClick={() => this.handleClick(item)}>{item.menuName}</Button>);
			}
		});
		return btns;
	}

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

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

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

	edit = () => {
		const {
			hrmPayrollManagement
		} = this.props, {
			editDeptPayrollInfoTable
		} = hrmPayrollManagement;

		editDeptPayrollInfoTable(true);
	}

	createPayroll = () => {
		const {
			hrmPayrollManagement
		} = this.props, {
			createPayroll
		} = hrmPayrollManagement;

		createPayroll();
	}

	sendPayroll = () => {
		this.showConfirm('send');
	}

	closePayroll = () => {
		this.showConfirm('close');
	}

	adjustSalarySetting = () => {
		this.showConfirm('adjust');
	}

	openHistoryPayroll = () => {
		const {
			hrmPayrollManagement
		} = this.props, {
			openHistoryPayroll
		} = hrmPayrollManagement;

		openHistoryPayroll();
	}

	save = () => {
		const {
			hrmPayrollManagement
		} = this.props, {
			saveDeptPayrollInfo
		} = hrmPayrollManagement;

		saveDeptPayrollInfo();
	}

	back = () => {
		const {
			hrmPayrollManagement
		} = this.props, {
			clickTreeNode,
			leftTree,
			table,
		} = hrmPayrollManagement, {
			nodeId,
			nodeType,
			nodeName
		} = leftTree;

		clickTreeNode(nodeId, nodeType, nodeName,table.date);
	}

	exportPayroll = () => {
		 this.props.hrmPayrollManagement.exportExcel();
	}

	showConfirm = (operation) => {
		const {
			hrmPayrollManagement
		} = this.props, {
			leftTree,
			searchPanel,
		} = hrmPayrollManagement, {
			nodeName
		} = leftTree, {
			form
		} = searchPanel, {
			yearmonth
		} = form.getFormParams();

		let _this = this;
		confirm({
			title: i18n.confirm.defaultTitle(),
			content: operation == 'close' ? `${i18n.confirm.payrollClosedConfirm()},  ${i18n.button.ok()}${i18n.button.close()}[ ${nodeName} ( ${yearmonth} ) ]${i18n.label.payroll()} ?` : operation == 'send' ? i18n.confirm.payrollSendConfirm() : i18n.confirm.salaryAdjustConfirm(),
			okText: i18n.button.ok(),
			cancelText: i18n.button.cancel(),
			onOk() {
				_this.onOk(operation);
			},
			onCancel() {
				return false
			},
		});
	}

	onOk = (operation) => {
		const {
			hrmPayrollManagement
		} = this.props, {
			closePayroll,
			adjustSalarySetting,
			sendPayroll,
		} = hrmPayrollManagement;

		if (operation == 'close') {
			closePayroll()
		} else if (operation == 'adjust') {
			adjustSalarySetting();
		} else if (operation == 'send') {
			sendPayroll();
		}
	}

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

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

	getPanelComponents() {
		const {
			hrmPayrollManagement
		} = this.props, {
			searchPanel
		} = hrmPayrollManagement, {
			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@aoqbbk@${index}`} span={10} offset={1}>
                              <div style={{marginTop: 20}} className='hrm-payroll-management'>
                                  <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@aicrn3@${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@x912bf@${index}`} fieldConfig={field} form={form} formParams={form.getFormParams()} />}
                                  </WeaFormItem>
                              </div>
                  	     </Col>)
			})
		})
		return <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@2j33vx`} spinning={loading}><Row ecId={`${this && this.props && this.props.ecId || ''}_Row@bqbzh0`}
			onKeyDown={(e) =>( e.keyCode == 13 && e.target.tagName === "INPUT")  && this.handleSearch()}
		>{arr}</Row></Spin>
	}

	handleSearch() {
		const {
			hrmPayrollManagement
		} = this.props, {
			isPanelShow,
			setPanelStatus,
			getTable,
			refreshPageTitle,
		} = hrmPayrollManagement;

		getTable();
		refreshPageTitle();
		isPanelShow && setPanelStatus(false);
	}

	reRenderColumns = (columns) => {
		let _this = this;
		columns.forEach((c, index) => {
			if (c.dataIndex == 'paydate') {
				c.render = function(text, record) {
					const {
						randomFieldId,
						subcompanyid1span,
						paydate
					} = record;

					return <a onClick={() => _this.editTableRow(randomFieldId, subcompanyid1span, paydate)} >{paydate}</a>
				}
			};
		})
	}

	editTableRow = (id, name, date) => {
		const {
			hrmPayrollManagement
		} = this.props, {
			clickTreeNode,
			setCurrentPage,
			setPageSize,
		} = hrmPayrollManagement;
		setCurrentPage(1);
		setPageSize(10);
		clickTreeNode(id, '1', name, date);
	}

	onOperatesClick = (record, rowIndex, operate) => {
		const {
			randomFieldId,
			subcompanyid1span,
			paydate
		} = record, {
			index
		} = operate;

		if (index == 0) {
			this.editTableRow(randomFieldId, subcompanyid1span, paydate);
		}
	}

	getBrowserViewHeight = () => {
		let height;
		if (window.innerHeight) {
			height = window.innerHeight;
		} else
		if (document.body && document.body.clientHeight) {
			height = document.body.clientHeight;
		}

		return height;
	}

	getSearchItemsLength = () => {
		const {
			hrmPayrollManagement
		} = this.props, {
			leftTree,
			table,
		} = hrmPayrollManagement, {
			nodeType
		} = leftTree, {
			isHistoryTable
		} = table;

		let len;
		if (nodeType == '0' || isHistoryTable) {
			len = 2;
		}
		if (nodeType !== '0' && !isHistoryTable) {
			len = 6;
		}

		return len;
	}

	getScroll = () => {
		const {
			hrmPayrollManagement
		} = this.props, {
			table
		} = hrmPayrollManagement, {
			columns,
			datas,
		} = table;

		return {
			x:true,
			y: $(".hrm-payroll-table-wrap").height() - 105
		}

		if (IEVersion() == '-1' && toJS(datas).length > 0) {
			return {
				x: (toJS(columns).length - 1) * 150 + 100,
				y: $(".hrm-payroll-table-wrap").height() - 105
			}
		} else {
			return {
				y: $(".hrm-payroll-table-wrap").height() - 105
			}
		}
	}

	render() {
		const {
			hrmPayrollManagement
		} = this.props, {
			authorized,
			loading,
			title,
			isPanelShow,
			table,
			searchPanel,
			leftTree,
			setPanelStatus,
			setBaseSearchValue,
			setTableEditRef,
			setTableEditDatas,
			setDeptPayrollTableSelectedRows,

			total,
			pageSize,
			currentPage,
			setPageSize,
			setCurrentPage,
			getDeptPayrollInfoTable,
			getEditableDeptPayrollTable,

			spinning,
			percentage,
		} = hrmPayrollManagement, {
			tableStore,
			columns,
			datas,
			isHistoryTable,
			selectedRowIndexs,
			isEdit,
		} = table, {
			baseSearchValue,
		} = searchPanel, {
			triggerRefresh,
			nodeType
		} = leftTree;

		const tableEditProps = {};
		if (isEdit) {
			Object.assign(tableEditProps,{
				getRowSelection:()=>null
			});
		}

		if (!authorized) {
			return (
				<div style={{height: '100%'}}>
					{loading ?  <div className='hrm-loading-center'>
									<Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@h0x3d8`} spinning={loading} size='large'></Spin>
								</div>
						     :	<div className="hrm-wea-alert-page">
		                			<WeaAlertPage ecId={`${this && this.props && this.props.ecId || ''}_WeaAlertPage@whykq3`}>
						                <div style={{ color: '#000' }}>
						                    {i18n.message.authFailed()}
						                </div>
		                      		</WeaAlertPage>
	                        	</div>
	                }	
                </div>
			)
		} else {

			return (
				<Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@nslmk6`} spinning={spinning} tip={`${percentage}%`}>
					<WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@jboaud`} 
						datas={this.getDropMenuDatas()} 
						onClick={ key => this.handleMenuClick(key)}
						collectParams={{favname:title,favouritetype:5}}
					>
					        <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@n00ffj`} 
					            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@d7gi30`} 
						          	isNew={true}
						          	leftCom={<LeftTree ecId={`${this && this.props && this.props.ecId || ''}_LeftTree@09qa80`} triggerRefresh={triggerRefresh}/>}
						        >
						           	<WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@xnni1p`}
						              	searchType={['base','advanced']}
						              	showSearchAd={isPanelShow}
						              	hasMask={false}
						              	advanceHeight={Math.ceil(this.getSearchItemsLength() / 2)*52+20}
						              	buttonsAd={this.getDropPanelButtons()}
						              	searchsBaseValue={baseSearchValue}
						              	setShowSearchAd={  b => setPanelStatus(b)}
						              	hideSearchAd={ () => setPanelStatus(false)}
						              	searchsAd= {isPanelShow ? this.getPanelComponents():<div></div>}
						              	onSearch={() => this.handleSearch()}
						              	onSearchChange={(val) => setBaseSearchValue(val)}
						            />
						            	{(nodeType == '0'||isHistoryTable) ? <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@in7om4`} 
						                  										comsWeaTableStore={tableStore}
						                  										hasOrder={true}
						                  										needScroll={true}
						                  										uniqueId={true}
						                  										getColumns={c => this.reRenderColumns(c)}
						                  										onOperatesClick={(record, rowIndex, operate) => this.onOperatesClick(record, rowIndex, operate)}/>
						                  			     				   : <div className="hrm-payroll-table-wrap">
							                  			     				   	<WeaTableEdit ecId={`${this && this.props && this.props.ecId || ''}_WeaTableEdit@48djmh`}
							                  			     				   		{...tableEditProps}
																					ref={com => setTableEditRef(com)}
		          																	columns={toJS(columns)}
		          																	datas={toJS(datas)}
		          																	showAdd={false}
		          																	showCopy={false}
		          																	showDelete={false}
		          																	showTitle={false}
		          																	selectedRowKeys={toJS(selectedRowIndexs)}
		          																	onRowSelect={selectedRows => setDeptPayrollTableSelectedRows(selectedRows)}
		          																	tableProps = {{
																						scroll: this.getScroll(),
																						rowKey:"chkresourceid",
																						pagination: {
																							total,
																							pageSize,
																							showSizeChanger:true,
																							showQuickJumper:true,
																							current:currentPage,
																							pageSizeOptions:[10, 20, 50, 100],
																							showTotal: total => getLabel("385617", "共$s条").replace(/\$s/, total),
																							onShowSizeChange: 
																								(page, pagesize) => {
																									setPageSize(pagesize);
																									setCurrentPage(1);
																									if (isEdit) {
																										getEditableDeptPayrollTable()
																									}else{
																										getDeptPayrollInfoTable();
																									}
																								},
																							onChange: page=>{
																								setCurrentPage(page);
																								if (isEdit) {
																									getEditableDeptPayrollTable()
																								}else{
																									getDeptPayrollInfoTable();
																								}
																							}
																						}
																				}}
		          																	onChange={datas => setTableEditDatas(datas)}
		        																/>
		        																</div>
	        																
						                }
						        </WeaLeftRightLayout>
					        </WeaTop>
					</WeaRightMenu>
				</Spin>
			)
		}
	}
}