import {
	observable,
	action,
	computed
} from 'mobx';
import {
	WeaForm,
	WeaSwitch
} from 'comsMobx';
import {WeaTools} from 'ecCom';
import {
	Button,
	message
} from 'antd';
import HrmBaseStore from './baseStore';
import * as api from '../apis/orgChart';
import FormInfo from '../coms/FormInfo';
import {
	i18n
} from '../public/i18n';

export class HrmOrgChart extends HrmBaseStore {
	/********************* unobservable list *********************/
	topBtnAndMenu = () => {
		let btns = [
			<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@bbjlro`} type='primary' op="setting" onClick={() => this.setting()}>{i18n.button.setting()}</Button>,
			<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@si0wnq`} type='primary' op="sync" onClick={() => this.getChartData(true)}>{i18n.button.reset()}</Button>
		]
		let menus = [];
		btns.map((btn, index) => {
			const {
				props
			} = btn;
			menus.push({
				key: index.toString(),
				content: props.children,
				icon: <i className={this.menuIconCollection[props.op]}/>,
				onClick: props.onClick,
				disabled: props.disabled || false
			});
		})
		const {
			orgForm,
			orgFormFields
		} = this.formTarget;
		if (orgForm != null && orgForm.isFormInit) {
			btns.splice(0, 0, <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@qu4c18`} fieldConfig={orgFormFields[0].items[0]} form={orgForm} onChange={() => this.getChartData()}/>)
		}
		return {
			btns,
			menus: [...menus, ...this.getBasicMenus('HRM_ENGINE_ORG_CHART_SET')]
		}
	}

	editorDialogRightMenu = [];
	getDialogOpButtons = () => {
		let buttons = [];
		this.editorDialogRightMenu.length = 0;
		buttons.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@svrqem`} type="primary" op="save" onClick={() => this.saveSetting()}>{i18n.button.save()}</Button>);

		buttons.map((btn, index) => {
			const {
				props
			} = btn;
			this.editorDialogRightMenu.push({
				key: index.toString(),
				content: props.children,
				icon: <i className={this.menuIconCollection[props.op]}/>,
				onClick: props.onClick
			});
		})

		return buttons;
	}

	itemRender = {
		showtype: (field, textAreaProps, form, formParams) => {
			return (
				<div className='customerSetting'>
					<WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@crdnip`} fieldConfig={{...field, ...textAreaProps}} 
						form={form}/>
					{
						formParams.showtype === '1' && 
						<WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@vigiri`} fieldConfig={{...form.fieldArr[1], ...textAreaProps, min: 1, max: 100}} form={form}/>
					}
				</div>
			)
		},
		shownum: (field, textAreaProps, form, formParams) => {
			return null;
		}
	}

	iframe;
	/********************* unobservable list *********************/

	/********************* dialog info setting *********************/

	/********************* dialog info setting *********************/

	/********************* observable list *********************/
	@observable spinning = false;
	@observable refreshOrgForm = new Date().getTime();

	dialogParams = {
		icon: "icon-coms-hrm",
		iconBgcolor: "#217346",
		visible: false,
		title: '自定义设置',
		style: {
			height: 90,
			width: 400
		},
		onCancel: () => {
			this.dialogParams.visible = false;
		}
	}
	/********************* observable list *********************/

	/********************* computed list *********************/
	/********************* computed list *********************/

	/********************* action list *********************/
	initData = (refresh = false) => {
		this.iframe = null;
		this.containerInitFinished = {
			...this.containerInitFinished,
			init: true
		}
		this.callInitData();
	}

	callInitData = () => {
		if(this.spinning)
			return;
		this.spinning = true;
		api.initData().then(rs => {
			rs.map((result, index) => {
				if (result.status === '1') {
					switch (index) {
						case 0:
							this.setFormData('orgForm', result.conditions);
							this.refreshOrgForm = new Date().getTime();
							break;
						case 1:
							this.setFormData('settingForm', result.conditions);
							this.getChartData();
							break;
					}
				}
			})
		})
	}

	setIframe = (iframe) => {
		if(iframe == null || this.iframe != null)
			return;
		this.iframe = iframe;
		this.callInitData();
	}

	@action getChartData = (reset = false) => {
		this.spinning = true;
		const params = {};
		const orgFormParams = this.formTarget.orgForm.getFormParams();
		const settingFormParams = this.formTarget.settingForm.getFormParams();
		Object.assign(params, {
			arg0: orgFormParams.sOrg,
			arg1: settingFormParams.shownum,
			arg3: orgFormParams.sOrg < 0 ? false : true,
			arg11: ';;B' //!reset ? ';;P' : ';;B'
		});
		api.getOrgChartData(params).then(data => {
			if (data.status === '1') {
				const msgData = {
					act: 'orgChart', // 自定义的消息类型、行为，用于switch条件判断等。。
					orgData: data.data,
					params: {
						sorgid: orgFormParams.sOrg,
						isShow: params.arg11,
						showNum: 'false',
						shownum: settingFormParams.shownum
					},
					client: {
						browser: WeaTools.ua.browser,
						browserVersion: {
							browser: WeaTools.ua.browser,
							version: parseInt(WeaTools.ua.version)
						},
						version: parseInt(WeaTools.ua.version),
						os: WeaTools.ua.os
					}
				};
				const sendMsg = setInterval(() => {
					if($('#orgChartFrame')[0] != null){
						clearInterval(sendMsg);
						$('#orgChartFrame')[0].contentWindow.postMessage(msgData, '*');
					}
				}, 500);
				// this.iframe && this.iframe.contentWindow.postMessage(msgData, '*');
			} else {
				this.spinning = false;
			}
		}, error => {
			this.spinning = false;
		})
	}

	onInitOrgChart = (status) => {
		this.spinning = false;
		switch (status) {
			case 0:
				message.error(i18n.message.dataNone());
				break;
			case -1:
				message.error(i18n.message.dataConstructError());
				break
		}
	}

	@action setting = () => {
		const {
			settingForm: form,
			settingFormFields: fields
		} = this.formTarget;
		this.dialogParams.title = i18n.label.customerSetting();
		this.dialogParams.coms = (<FormInfo ecId={`${this && this.props && this.props.ecId || ''}_FormInfo@d2fef1`} center={false} form={form} formFields={fields} menu={this.editorDialogRightMenu} itemRender={this.itemRender}/>);
		this.dialogParams.visible = true;
	}

	@action saveSetting = () => {
		const formParams = this.formTarget.settingForm.getFormParams();
		if (formParams.shownum == null || formParams.shownum === '') {
			this.formTarget.settingForm.updateFields({
				shownum: {
					value: 1
				}
			})
		}
		this.formTarget.settingForm.validateForm().then(f => {
			if (f.isValid) {
				api.saveOrgChartSet(formParams).then(data => {
					if (data.status === '1') {
						this.dialogParams.onCancel();
						this.getChartData(true);
					} else {
						message.error(data.message);
					}
				}, error => {})
			} else {
				f.showErrors();
				this.showError = new Date().getTime();
			}
		});
	}

	showSpin = (val) => {
		this.spinning = (val === '0');
	}
	/********************* action list *********************/
}

export const hrmOrgChart = new HrmOrgChart();