import {
	observable,
	action,
	computed,
	autorun
} from 'mobx';
import {
	WeaSwitch
} from 'comsMobx';
import {
	message
} from 'antd';
import HrmBaseStore from './baseStore';
import * as api from '../apis/batchAdjust';
import CheckContent from '../components/batchMaintenance/adjust/CheckContent';
import {upperFirst, has, find} from 'lodash';
import {
	i18n
} from '../public/i18n';

export class HrmBatchAdjust extends HrmBaseStore {
	rootStore;
	router;

	setRootStore = (rootStore, router) => {
		this.rootStore = rootStore;
		this.router = router;
		rootStore.saveAdjust = this.saveAdjust;
		rootStore.showOpLog = this.showOpLog;
		this.menus = rootStore.topMenuDef().adjust.menus;
	}
	/********************* unobservable list *********************/
	tabConfig = {
		tabs: [],
		keyParam: 'viewCondition',
		activeTabKey: '1'
	}

	treeRef;
	scroll;
	selectedFormItemCount = 0;
	containerType = 'subCompany';
	logSmallType;
	hasHideField = true;
	orgTreeSelectedDatas = [];
	includeChild = true;
	formFieldMap = {};

	itemRender = {
		subcompanyid1: (field, form, formParams) => {
			if(form.fieldMap.supdepid && form.fieldMap.supdepid.checkboxValue){
				return (
					<WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@ioib24`} fieldConfig={{...field, viewAttr: 1, hasBorder: true}} form={form} formParams={formParams} onChange={(value) => this.onSubCompanyIdChange(value)}/>
				)
			}else{
				return null;
			}
		},
		supdepid: (field, form, formParams) => {
			return (
				<WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@afs06l`} fieldConfig={field} form={form} formParams={formParams} onChange={(value) => this.onSupDepIdChange(value)}/>
			)
		},
		accounttype: (field, form, formParams) => {
			return (
				<WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@fjuc29`} fieldConfig={field} form={form} formParams={formParams} onChange={(value) => this.onAccountTypeChange(value)}/>
			)
		},
		belongto: (field, form, formParams) => {
			if(formParams.accounttype == null || formParams.accounttype == '' || formParams.accounttype == '0'){
				this.hasHideField = true;
				window.e9HideFormFieldKeys = ['belongto'];
				return;
			}
			window.e9HideFormFieldKeys = [];
			return (
				<WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@jenzea`} fieldConfig={field} form={form} formParams={formParams}/>
			)
		},
		userUsbType: (field, form, formParams) => {
			return (
				<WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@7zqr6a`} fieldConfig={field} form={form} formParams={formParams} onChange={(value) => this.onUserUsbTypeChange(value)}/>
			)
		},
		usbstate: (field, form, formParams) => {
			if(formParams.userUsbType == null || formParams.userUsbType == ''){
				this.hasHideField = true;
				return;
			}
			const options = Array.from(field.options);
			if(formParams.userUsbType == '6')
				options.pop();
			return (
				<WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@wzrkgk`} fieldConfig={{...field, options}} form={form} formParams={formParams}/>
			)
		}
	}
	/********************* unobservable list *********************/

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

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

	/********************* observable list *********************/
	@observable refreshData = new Date().getTime();
	@observable refreshTab = new Date().getTime();
	@observable orgTreeSelectedKeys = [];
	@observable spinning = false;

	@observable isSelectedAll = false;
	@observable menus = [];
	
	@observable orgTreeProps = {
		needSearch: true,
		noCache: true,
		topPrefix: 'hrmSearch',
		inputLeftDom: `<b>${i18n.label.organization()}</b>`,
		params: {
			rightStr: 'PersonnelOrganization:Batchmaintenance',
			// checkboxLevel: 'department'
		},
		checkedDatas: [],
		showCheckStrictly: true,
		checkStrictly: false,
		// needDropMenu: true,
		onCheck: (ids, datas) => {
			this.orgTreeSelectedKeys = ids;
			this.orgTreeSelectedDatas.length = 0;
			datas.map(d => {
				this.orgTreeSelectedDatas.push(d);
			})
		},
		getCheckableTypes: () => {
			return this.getCheckableTypes()
		}
	}
	/********************* observable list *********************/

	/********************* computed list *********************/
	monitorSpinning = () => {
		this.spinning;
		this.rootStore && this.rootStore.setSpinning(this.spinning);
	}

	monitor2 = autorun(this.monitorSpinning)
	/********************* computed list *********************/

	/********************* action list *********************/
	checkStrictlyTitles = () => [i18n.label.includeChildren(), i18n.label.notIncludeChildren()];

	setTreeRef = (ref) => {
		this.treeRef = ref;
	}

	setScrollRef = (ref) => {
		this.scroll = ref;
	}

	cleanData = () => {
		this.selectedFormItemCount = 0;
		this.isSelectedAll = false;
		this.orgTreeSelectedKeys.length = 0;
		this.treeRef && this.treeRef.refs && this.treeRef.refs.tree && this.treeRef.refs.tree.setState({checkedDatas: []})
		this.refreshRootData();
	}
	loadFormInfo = (type) => {
		this.includeChild = true;
		this.containerType = type;
		switch(type){
			case 'subCompany':
				this.logSmallType = this.logTypeDef.HRM_ENGINE_Personnel_ORG_ADJUST_SUB;
				break;
			case 'department':
				this.logSmallType = this.logTypeDef.HRM_ENGINE_Personnel_ORG_ADJUST_DEPT;
				break;
			case 'resource':
				this.logSmallType = this.logTypeDef.HRM_ENGINE_Personnel_ORG_ADJUST_RES;
				break;
		}
		this.cleanData();
		this.callData();
	}

	callData = () =>{
		this.callTabInfo();
		// switch(this.containerType){
		// 	case 'resource':
		// 		this.callTabInfo();
		// 		break;
		// 	default:
		// 		this.callFormData();
		// 		break;
		// }
	}

	callFormData = (params) => {
		this.hasHideField = false;
		if(this.spinning)
			return;
		this.formFieldMap = {};
		let func = api[`batch${upperFirst(this.containerType)}`];
		if(func != null ){
			this.spinning = true;
			func(params).then(data => {
				if(data.status === '1'){
					this.formFieldMap = data.fielditem;
					this.setFormData(`${this.containerType}Form`, data.formField);
					if(this.formTarget[`${this.containerType}Form`].isFormInit){
						const formParams = this.formTarget[`${this.containerType}Form`].getFormParams();
						this.hasHideField = formParams.userUsbType == null || formParams.userUsbType == '';
						this.refreshData = new Date().getTime();
						this.scrollToTop();
					}
				}else{
					message.error(data.message);
				}
				this.spinning = false;
			}, error => {this.spinning = false;})
		}
	}

	callTabInfo = () => {
		api.getTabInfo({}, upperFirst(this.containerType.toLowerCase())).then(data => {
			if(data.status === '1'){
				let tabs = [];
				data.tabs.map(tab => {
					tabs.push({
						color: '#000000',
						groupId: tab.key,
						title: tab.title,
						viewCondition: tab.key,
					})
				});
				this.tabConfig.tabs = tabs;
				this.setActiveTab(tabs[0].viewCondition);
			}else{

			}
		}, error => {})
	}

	refreshRootData = () => {
		this.rootStore && this.rootStore.setSelectedFormItemCount(this.selectedFormItemCount);
	}

	@action selectedAllFormFields = (formName, val) => {
		let fields = this.formTarget[`${formName}Fields`];
		this.selectedFormItemCount = 0;
		fields.map(f => f.items.map(item => {
			item.checkboxValue = (val === '1');
			if(['usbstate', 'belongto'].indexOf(item.domkey[0]) >= 0 && this.hasHideField)
				item.checkboxValue = false;
			if(item.domkey[0] === 'subcompanyid1' && item.checkboxValue)
				item.checkboxEnable = 1;
			else
				item.checkboxEnable = 2;
			if(item.checkboxValue){
				this.selectedFormItemCount++;
			}
		}))
		this.isSelectedAll = (val === '1');
		this.refreshRootData();
	}

	setStatus = (key, v) => {
		let fields = this.formTarget[`${this.containerType}FormFields`];
		fields.map(g=>{
			g.items.map(f=>{
				if(f.domkey[0] === key){
					f.checkboxValue = (v === '1');
					if(key === 'subcompanyid1'){
						if(v === '1'){
							f.checkboxEnable = 1
						}else{
							f.checkboxEnable = 2
						}
					}
				}
			})
		})
	}

	@action onSelectedChangeHandle = (field, v) => {
		let fields = this.formTarget[`${this.containerType}FormFields`];
		this.selectedFormItemCount = 0;
		let total = 0;
		fields.map(f => f.items.map(item => {
			if(field.domkey[0] === item.domkey[0]){
				item.checkboxValue = (v === '1');
				if(field.domkey[0] === 'supdepid')
					this.setStatus('subcompanyid1', v);
				else if(field.domkey[0] === 'accounttype')
					!this.hasHideField && this.setStatus('belongto', v);
				else if(field.domkey[0] === 'belongto')
					this.setStatus('accounttype', v);
				else if(field.domkey[0] === 'userUsbType')
					!this.hasHideField && this.setStatus('usbstate', v);
				else if(field.domkey[0] === 'usbstate')
					this.setStatus('userUsbType', v);
			}
		}))
		fields.map(f => f.items.map(item => {
			item.checkboxValue && this.selectedFormItemCount++;
			total++;
		}))
		this.isSelectedAll = total === this.selectedFormItemCount;
		this.refreshRootData();
		this.refreshData = new Date().getTime();
	}

	@action setActiveTab = (key) => {
		this.tabConfig.activeTabKey = key || this.tabConfig.tabs[0].viewCondition;
		const tabIndex = this.getTabIndex(this.tabConfig.tabs, key);
		if (tabIndex < 0) return;
		this.cleanData();
		this.callFormData({groupid: key});
		this.refreshTab = new Date().getTime();
	}

	@action saveAdjust = () => {
		if(this.spinning)
			return;
		if (this.orgTreeSelectedKeys.length === 0) {
			message.error(i18n.message.plsSelectTarget());
			return;
		} else if (this.selectedFormItemCount === 0) {
			message.error(i18n.message.plsSelect1());
			return;
		} else {
			this.formTarget[`${this.containerType}Form`].validateForm().then(f => {
				if (f.isValid) {
					const formParams = this.formTarget[`${this.containerType}Form`].getFormParams();
					let pattern;
					if(has(formParams, 'email') && formParams.email != ''){
						pattern = /^(?:[a-z\d]+[_\-\+\.']?)*[a-z\d]+@(?:([a-z\d]+\-?)*[a-z\d]+\.)+([a-z]{2,})+$/i;
						if(!pattern.test(formParams.email)){
							message.error(i18n.message['24570']());
							return;
						}
					}
					const formFields = this.formTarget[`${this.containerType}FormFields`];
					
					const params = {
						id: this.toJS(this.orgTreeSelectedKeys).join(','),
					}
					let data = [], selectedFields = [];
					formFields.map(g => {
						g.items.map(f => {
							if(f.checkboxValue){
								let issystem = '';
								if(f.otherParams != null && f.otherParams.issystem != null)
									issystem = f.otherParams.issystem;
								data.push({
									fieldid: this.formFieldMap[f.domkey[0]],
									rowKey: f.domkey[0],
									rowValue: formParams[f.domkey[0]],
									issystem
								})
								selectedFields.push({
									key: f.domkey[0],
									name: f.label,
									value: formParams[f.domkey[0]]
								})
							}
						})
					})
					Object.assign(params, {
						data: JSON.stringify(data),
						includeChild: this.includeChild
					})
					if(this.containerType == 'resource'){
						Object.assign(params, {
							groupid: this.tabConfig.activeTabKey
						})
					}

					api.getConfirmInfo({ids: params.id, includeChild: this.includeChild, data: params.data, groupid: this.tabConfig.activeTabKey}, this.containerType.toLowerCase()).then(data => {
						if(data.status === '1'){
							if(data.count == 0){
								message.error(this.containerType === 'department' ? i18n.label.haveNotDepartment() : (this.containerType == 'subCompany' ? i18n.label['532854']() : i18n.label.haveNotPerson()));
								return;
							}
							data.data.map(d => {
								Object.keys(d).map(k => {
									let obj = find(selectedFields, {key: k});
									if(obj != null){
										obj.value = d[k];
									}
								})
							})
							this.confirmInfo({
								title: i18n.label.tips(),
								content: <CheckContent ecId={`${this && this.props && this.props.ecId || ''}_CheckContent@ceosn8`} orgTreeSelectedDatas={data} selectedFields={selectedFields} type={this.containerType.toLowerCase()}/>,
								width: 627,
								onOk: () => {
									this.spinning = true;
									api[`saveBatch${upperFirst(this.containerType)}`](params).then(data => {
										this.spinning = false;
										if(data.status === '1'){
											message.success(i18n.message.saveSuccess());
											this.treeRef && this.treeRef.refs.tree.fetchData();
											// this.loadFormInfo(this.containerType);
											this.cleanData();
											this.callFormData({groupid: this.tabConfig.activeTabKey});
										}else{
											message.error(data.message);
										}
									}, error => {this.spinning = false;})
								},
								onCancel: () => {
									this.spinning = false;
								}
							});
						}else{
							message.error(data.message);
						}
					}, error => {})
				} else {
					f.showErrors();
					this.showError = new Date().getTime();
				}
			});
		}
	}

	scrollToTop = () => {
		this.scroll && this.scroll.scrollerToTop();
	}

	@action onSubCompanyIdChange = (value) => {
		const subid = value.subcompanyid1.value;
		const formParams = this.formTarget[`${this.containerType}Form`].getFormParams();
		if(subid != '' && formParams.supdepid != null && formParams.supdepid != ''){
			api.checkSubDeptAvailable({subcompanyid1: subid, departmentid: formParams.supdepid}).then(data => {
				if(data.status === '1'){
					if(!data.available){
						this.formTarget[`${this.containerType}Form`].updateFields({
							supdepid: {
								value: '',
								valueSpan: '',
								valueObj: [{
									id: '',
									name: ''
								}]
							}
						})
					}
				}else{
					message.error(data.message);
				}
			})
		}else{
			this.formTarget[`${this.containerType}Form`].updateFields({
				supdepid: {
					value: '',
					valueSpan: '',
					valueObj: [{
						id: '',
						name: ''
					}]
				}
			})
		}
	}

	@action onSupDepIdChange = (value) => {
		const supdepid = value.supdepid.value;
		const formParams = this.formTarget[`${this.containerType}Form`].getFormParams();
		if(supdepid != ''){
			api.getSubCompanyInfo({departmentid: supdepid}).then(data => {
				if(data.status === '1'){
					this.formTarget[`${this.containerType}Form`].updateFields({
						subcompanyid1: {
							value: data.id.toString(),
							valueSpan: data.name,
							valueObj: [{
								id:  data.id.toString(),
								name: data.name
							}]
						}
					})
				}else{
					message.error(data.message);
				}
			}, error => {})
		}else{
			this.formTarget[`${this.containerType}Form`].updateFields({
				subcompanyid1: {
					value: '',
					valueSpan: '',
					valueObj: [{
						id: '',
						name: ''
					}]
				}
			})
		}
	}

	@action onAccountTypeChange = (value) => {
		this.hasHideField = value.accounttype.value == '' || value.accounttype.value == '0';
		if(this.hasHideField){
			this.formTarget[`${this.containerType}Form`].updateFields({
				belongto: {
					value: '',
					valueSpan: '',
					valueObj: [{
						id: '',
						name: ''
					}]
				}
			})
		}
		let fields = this.formTarget[`${this.containerType}FormFields`];
		this.selectedFormItemCount = 0;
		let total = 0;
		fields.map(f => f.items.map(item => {
			if('belongto' === item.domkey[0]){
				item.checkboxValue = (this.hasHideField ? false : item.checkboxValue);
				item.checkboxValue && this.selectedFormItemCount++;
			}else if(item.checkboxValue)
				this.selectedFormItemCount++;
			total++;
		}))
		this.hasHideField && total--;
		this.isSelectedAll = total === this.selectedFormItemCount;
		this.refreshRootData();
		this.refreshData = new Date().getTime();
	}

	@action onUserUsbTypeChange = (value) => {
		this.hasHideField = value.userUsbType.value == '';
		let fields = this.formTarget[`${this.containerType}FormFields`];
		const form = this.formTarget[`${this.containerType}Form`];
		if(value.userUsbType.value == '6' && form.getFormParams().usbstate == '2')
			form.updateFields({usbstate: {value: '1'}});
		this.selectedFormItemCount = 0;
		let total = 0;
		fields.map(f => f.items.map(item => {
			if('usbstate' === item.domkey[0]){
				item.checkboxValue = (this.hasHideField ? false : item.checkboxValue);
				item.checkboxValue && this.selectedFormItemCount++;
			}else if(item.checkboxValue)
				this.selectedFormItemCount++;
			total++;
		}))
		this.hasHideField && total--;
		this.isSelectedAll = total === this.selectedFormItemCount;
		this.refreshRootData();
		this.refreshData = new Date().getTime();
	}

	@action showOpLog = () => {
		this.showLog({
			logType: '4',
            logSmallType: this.logSmallType
		});
	}

	@action onCheckStrictlyChange = (val) => {
		this.includeChild = !val;
		if(!this.includeChild && this.containerType === 'department'){
			this.orgTreeProps.checkableTypes = ['2'];
		}else
			this.orgTreeProps. checkableTypes = [];
		// if(val){
		// }
	}

	@action getCheckableTypes = () => {
		if(!this.includeChild && this.containerType === 'department'){
			return ['2'];
		}else
			return null;
	}
	/********************* action list *********************/
}