import {
	observable,
	action,
	computed
} from 'mobx';
import {
	WeaForm,
	WeaTableNew,
	WeaSwitch
} from 'comsMobx';
import {
	Button,
	message
} from 'antd';
import FormInfo from '../coms/FormInfo';
import DetachEdit from '../components/appDetach/DetachEdit';
import HrmBaseStore from './baseStore';
import * as api from '../apis/appDetach';
import {
	has,
	findIndex
} from 'lodash';
import {
	i18n
} from '../public/i18n';

const {
	TableStore
} = WeaTableNew;

class HrmAppDetach extends HrmBaseStore {
	/********************* unobservable list *********************/
	//override baseStore.tabConfig
	tabConfig = {
		tabs: [{
			color: '#000000',
			groupId: 'globalSetting',
			title: i18n.label.globalSetting,
			viewCondition: '1',
			topButtonDef: [{
				comType: 'button',
				type: 'primary',
				onClickHandle: this.saveGlobalSetting,
				label: i18n.button.save,
				icon: this.menuIconCollection.save,
			}]
		}, {
			color: '#000000',
			groupId: 'appDetachList',
			title: i18n.label.appDetachList,
			viewCondition: '2',
			searchType: ['base', 'advanced'],
			searchKey: 'name',
			doSearch: (params) => this.getTableData('appDetachListTable', params),
			topButtonDef: [{
				comType: 'button',
				type: 'primary',
				onClickHandle: this.createDetach,
				label: i18n.button.create,
				icon: this.menuIconCollection.create,
			}, {
				comType: 'button',
				type: 'primary',
				onClickHandle: this.removeAppDetach,
				label: i18n.button.multiDelete,
				icon: this.menuIconCollection.remove,
				checkAction: 'appDetachListTableMultiRemoveable'
			}]
		}],
		keyParam: 'viewCondition',
		activeTabKey: '1'
	}

	editDetachTabConfig = {
		tabs: [{
			color: '#000000',
			groupId: 'basicInfo',
			title: i18n.label.basicInfo,
			viewCondition: '1',
			searchType: []
		}, {
			color: '#000000',
			groupId: 'target',
			title: i18n.label.target,
			viewCondition: '2',
			searchType: ['advanced'],
			searchKey: 'name',
			sourcetype: '2',
			doSearch: (params) => this.getTableData('targetListTable', { ...params,
				mainId: this.selectedDetach.id,
				sourcetype: '2'
			}),
			tabButtonDef: [{
				comType: 'button',
				icon: 'icon-coms-Add-to-hot',
				label: i18n.button.create,
				rightMenuIcon: this.menuIconCollection.create,
				onClickHandle: () => this.createDetachDetail('2')
			}, {
				comType: 'button',
				icon: 'icon-coms-form-delete-hot',
				label: i18n.button.delete,
				rightMenuIcon: this.menuIconCollection.remove,
				onClickHandle: () => this.removeDetachDetail({}),
				checkAction: 'targetListTableMultiRemoveable'
			}]
		}, {
			color: '#000000',
			groupId: 'range',
			title: i18n.label.viewRange,
			viewCondition: '3',
			searchType: [ 'advanced'],
			searchKey: 'name',
			sourcetype: '1',
			doSearch: (params) => this.getTableData('rangeListTable', { ...params,
				mainId: this.selectedDetach.id,
				sourcetype: '1'
			}),
			tabButtonDef: [{
				comType: 'button',
				icon: 'icon-coms-Add-to-hot',
				label: i18n.button.create,
				rightMenuIcon: this.menuIconCollection.create,
				onClickHandle: () => this.createDetachDetail('1')
			}, {
				comType: 'button',
				icon: 'icon-coms-form-delete-hot',
				label: i18n.button.delete,
				rightMenuIcon: this.menuIconCollection.remove,
				onClickHandle: () => this.removeDetachDetail({}),
				checkAction: 'rangeListTableMultiRemoveable'
			}]
		}],
		keyParam: 'viewCondition',
		activeTabKey: '1'
	}

	globalSettingFormItemRender = {
		appdetachable: (field, textAreaProps, form, formParams) => {
			return (
				<WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@cesl8y`} fieldConfig={{...field, ...textAreaProps}} form={form} formParams={formParams} onChange={this.onChangeAppDetachable}/>
			)
		},
		appdetachinit: (field, textAreaProps, form, formParams) => {
			if (formParams.appdetachable === '1') {
				return (
					<WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@32behz`} fieldConfig={{...field, ...textAreaProps}} form={form} formParams={formParams}/>
				)
			}
			return;
		},
		appDetachDisableAll: (field, textAreaProps, form, formParams) => {
			if (formParams.appdetachable === '1') {
				return (
					<WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@sb8bxy`} fieldConfig={{...field, ...textAreaProps}} form={form} formParams={formParams}/>
				)
			}
			return;
		}
	}

	conditionItemRender = {
		type1: (field, form, formParams) => {
			const fieldKey = formParams.type1;
			const index = findIndex(form.fieldArr, {
				domkey: [fieldKey]
			})
			let coms;
			if (index >= 0) {
				const browserField = form.fieldArr[index];
				let {
					browserConditionParam
				} = browserField;
				browserConditionParam.onChange = (ids, names, datas) => {
					const d = Object.assign({
						hrmId: {
							value: ''
						},
						subId: {
							value: ''
						},
						depId: {
							value: ''
						},
						roleId: {
							value: ''
						}
					}, {
						[fieldKey]: {
							value: ids
						}
					});
					form.updateFields(d, false)
				}
				coms = <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@ktmk0t`} 
                            fieldConfig={browserField} 
                            form={form} 
                            formParams={formParams}/>
			}
			return (
				<div>
                    <div style={{float: 'left', width: '40%'}}>
                        <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@e1b76l`} 
                            fieldConfig={field} 
                            form={form} 
                            formParams={formParams}/>
                    </div>
                    {
                        coms != null &&
                        <div style={{float: 'left', width: '58%', marginLeft: '2%'}}>
                        	{coms}
                        </div>
                    }
                </div>
			)
		},
		hrmId: (field, form, formParams) => {
			return;
		},
		depId: (field, form, formParams) => this.conditionItemRender.hrmId(field, form, formParams),
		subId: (field, form, formParams) => this.conditionItemRender.hrmId(field, form, formParams),
		roleId: (field, form, formParams) => this.conditionItemRender.hrmId(field, form, formParams)
	}

	selectedDetach = {}
	selectedDetailInfo = {}
	sourcetype;
	/********************* unobservable list *********************/

	/********************* dialog info setting *********************/
	editorDialogRightMenu = [];
	getDialogOpButtons = () => {
		let buttons = [];
		this.editorDialogRightMenu.length = 0;
		if (!this.dialogParams.isEdit) {
			buttons.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@pfna2u`} type="primary" op="create" onClick={() => this.saveAppDetach()}>{i18n.button.save()}</Button>);
			buttons.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@1wowkv`} type="primary" op="entry" onClick={() => this.saveAppDetach(true)}>{i18n.button.saveAndSetting()}</Button>);
		} else if (this.editDetachTabConfig.activeTabKey === '1') {
			buttons.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@p8s77a`} type="primary" op="save" onClick={() => this.saveAppDetach(true, false)}>{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
			});
		})

		this.dialogParams.moreBtn.datas = this.editorDialogRightMenu;
		return buttons;
	}
	/********************* dialog info setting *********************/

	/********************* observable list *********************/
	dialogParams = { //override baseStore.dialogParams
		...this.dialogPropsDef,
		isEdit: false,
		onCancel: () => {
			this.selectedDetach = {};
			this.dialogParams.isEdit = false;
			this.dialogParams.visible = false;
		},
		table: new TableStore(),
	}

	@observable detachDetailParams = {
		icon: "icon-coms-hrm",
		iconBgcolor: "#217346",
		height: 200,
		// title: i18n.label.addMemberAuth(),
		visible: false,
		onOk: (data) => this.doSaveDetachDetail(data),
		onCancel: () => {
			this.selectedDetailInfo = {};
			this.detachDetailParams.visible = false
		}
	}

	@observable appDetachListTable = new TableStore();
	@observable targetListTable = new TableStore();
	@observable rangeListTable = new TableStore();

	@observable refreshForm = new Date().getTime();
	@observable refreshMainTabComponent = new Date().getTime();
	@observable refreshEditTabComponent = new Date().getTime();
	@observable refreshDialog = new Date().getTime();
	/********************* observable list *********************/

	/********************* computed list *********************/
	@computed get appDetachListTableMultiRemoveable() {
		return this.appDetachListTable.selectedRowKeys.length === 0;
	}
	@computed get targetListTableMultiRemoveable() {
		return this.targetListTable.selectedRowKeys.length === 0;
	}
	@computed get rangeListTableMultiRemoveable() {
		return this.rangeListTable.selectedRowKeys.length === 0;
	}
	/********************* computed list *********************/

	/********************* action list *********************/
	@action initData = () => {
		this.containerInitFinished = {
			...this.containerInitFinished,
			init: true
		}
		this.setActiveTab(this.tabConfig, '1');
	}

	@action setActiveTab = (tabConfig, key) => {
		tabConfig.activeTabKey = key || tabConfig.tabs[0].viewCondition;
		const tabIndex = this.getTabIndex(tabConfig.tabs, key);
		if (tabIndex < 0) return;
		switch (tabConfig.activeTabKey) {
			case '1':
				!this.dialogParams.isEdit ? this.getGlobalSettingForm() : this.getDetachInfo();
				break;
			case '2':
				!this.dialogParams.isEdit ? this.initAppDetachListData() : this.initDetailList('2');
				break;
			case '3':
				this.initDetailList('1');
				break;
		}
	}

	getGlobalSettingForm = () => {
		api.getGlobalSettingForm().then(data => {
			if (data.status === '1') {
				this.setFormData('globalSettingForm', data.formField);
				this.refreshMainTabComponent = new Date().getTime();
			} else {
				message.error(data.message);
			}
		}, error => {})
	}

	initAppDetachListData = () => {
		api.initAppDetachListData().then(rs => {
			rs.map((result, index) => {
				if (result.status === '1') {
					switch (index) {
						case 0:
							this.setFormData('conditionForm', result.formField);
							break;
						case 1:
							this.appDetachListTable.getDatas(result.sessionkey, 1);
							this.refreshMainTabComponent = new Date().getTime();
							break;
					}
				}
			})
		}, error => {})
	}

	getDetachInfo = () => {
		api.getAppDetachForm(this.selectedDetach).then(data => {
			if (data.status === '1') {
				this.setFormData('detachForm', data.formField);
				this.refreshEditTabComponent = new Date().getTime();
				this.refreshDialog = new Date().getTime();
			}
		})
	}

	initDetailList = (sourcetype) => {
		this.sourcetype = sourcetype;
		const apiFunc = sourcetype === '1' ? api.initRangeListData : api.initTargetListData;
		apiFunc({
			mainId: this.selectedDetach.id,
			sourcetype
		}).then(rs => {
			rs.map((result, index) => {
				if (result.status === '1') {
					switch (index) {
						case 0:
							this.setFormData('dialogConditionForm', result.formField);
							break;
						case 1:
							sourcetype === '2' ? this.targetListTable.getDatas(result.sessionkey, 1) : this.rangeListTable.getDatas(result.sessionkey, 1);
							this.refreshEditTabComponent = new Date().getTime();
							this.refreshDialog = new Date().getTime();
							break;
					}
				}
			})
		})
	}

	onChangeAppDetachable = (obj) => {
		this.refreshForm = new Date().getTime();
	}

	@action getTableData = (tbStore, params) => {
		this[tbStore] = new TableStore();
		switch (tbStore) {
			case 'appDetachListTable':
				this.requestTableData(this[tbStore], api.getAppDetachList, params);
				break;
			case 'targetListTable':
				this.requestTableData(this[tbStore], api.getDetachDetail, params);
				break;
			case 'rangeListTable':
				this.requestTableData(this[tbStore], api.getDetachDetail, params);
				break;
			default:
				break;
		}
	}

	@action saveGlobalSetting = () => {
		const formParams = this.formTarget.globalSettingForm.getFormParams();
		this.formTarget.globalSettingForm.validateForm().then(f => {
			if (f.isValid) {
				api.saveGlobalSetting(formParams).then(data => {
					if (data.status === '1')
						message.success(i18n.message.saveSuccess());
					else
						message.error(data.message);
				}, error => {})
			} else {
				f.showErrors();
				this.showError = new Date().getTime();
			}
		})
	}

	@action createDetach = () => {
		api.getAppDetachForm().then(data => {
			if (data.status === '1') {
				this.setFormData('detachForm', data.formField);
				const {
					detachForm: form,
					detachFormFields: fields
				} = this.formTarget;
				if (this.formTarget.detachForm.isFormInit) {
					this.dialogParams.isEdit = false;
					this.dialogParams.title = i18n.label.createAppDetach();
					this.dialogParams.coms = <FormInfo ecId={`${this && this.props && this.props.ecId || ''}_FormInfo@cb2s8o`} form={form} formFields={fields} menu={this.editorDialogRightMenu}></FormInfo>;
					this.dialogParams.visible = true;
				}
			} else {
				message.error(data.message);
			}
		}, errpr => {})
	}

	@action saveAppDetach = (setting = false, closeDialog = true) => {
		this.formTarget.detachForm.validateForm().then(f => {
			if (f.isValid) {
				let params = {
					...this.formTarget.detachForm.getFormParams(),
					id: this.selectedDetach.id,
					operation: 'add'
				}
				if (has(this.selectedDetach, 'id') && this.selectedDetach.id.length > 0) {
					Object.assign(params, {
						id: this.selectedDetach.id,
						operation: 'edit'
					})
				}
				api.saveAppDetach(params).then(data => {
					if (data.status === '1') {
						message.success(i18n.message.saveSuccess());
						if (!setting) {
							this.dialogParams.onCancel();
							if (!this.dialogParams.isEdit)
								this.getTableData('appDetachListTable');
							else
								this.appDetachListTable.getDatas();
						} else {
							if (closeDialog) {
								this.dialogParams.visible = false;
								this.showEditDialog({
									id: data.id
								}, '1');
							}
						}
					} else
						message.error(data.message);
				}, error => {
					message.error(i18n.message.actionError());
				});
			} else {
				f.showErrors();
				this.showError = new Date().getTime();
			}
		});
	}

	@action removeAppDetach = (params) => {
		let content;
		if (!has(params, 'id')) {
			params = {
				id: this.appDetachListTable.selectedRowKeys
			}
			content = i18n.confirm.deleteSelected();
		} else {
			content = i18n.confirm.delete();
		}

		this.confirmInfo({
			content,
			onOk: () => {
				api.removeAppDetach(params).then(data => {
					if (data.status === '1') {
						message.success(i18n.message.deleteSuccess());
						this.getTableData('appDetachListTable');
					} else
						message.error(data.message);
				}, error => {
					message.error(i18n.message.actionError());
				});
			}
		});
	}

	showEditDialog = (params, tabKey) => {
		this.selectedDetach = params;
		this.dialogParams.isEdit = true;
		this.setActiveTab(this.editDetachTabConfig, tabKey);
		this.dialogParams.title = i18n.label.editAppDetach();
		this.dialogParams.coms = <DetachEdit ecId={`${this && this.props && this.props.ecId || ''}_DetachEdit@pi5srk`} store={this}/>;
		this.dialogParams.visible = true;
	}

	createDetachDetail = () => {
		const title = this.editDetachTabConfig.activeTabKey === '2' ? i18n.label.addObject() : i18n.label.addRange();
		api.getAppDetachDetialForm().then(data => {
			if (data.status === '1') {
				Object.assign(this.detachDetailParams, {
					conditions: data.conditions,
					title,
					visible: true
				})
			}
		})
		// this.detachDetailParams.title = title;
		// this.detachDetailParams.visible = true;
	}

	doSaveDetachDetail = (data) => {
		const obj = this.editDetachTabConfig.activeTabKey === '2' ? {
			sourcetype: '2',
			operation: 'saveMembers',
			table: this.targetListTable,
		} : {
			sourcetype: '1',
			operation: 'saveRange',
			table: this.rangeListTable,
		};
		const params = { ...data,
			mainId: this.selectedDetach.id,
			operation: obj.operation,
			...this.selectedDetailInfo,
			sourcetype: obj.sourcetype
		}
		api.saveAppDetachDetial(params).then(data => {
			if (data.status === '1') {
				obj.table.getDatas();
				this.detachDetailParams.onCancel();
				// this.initDetailList(this.sourcetype)
				this.appDetachListTable.getDatas();
			} else
				message.error(data.message);
		}, error => {})
	}

	@action modifyDetachDetail = (params) => {
		this.selectedDetailInfo = params;
		api.getAppDetachDetialForm(params).then(data => {
			if (data.status === '1') {
				// this.detachDetailParams.conditions = data.conditions;
				const title = this.editDetachTabConfig.activeTabKey === '2' ? i18n.label.editObject() : i18n.label.editRange();
				Object.assign(this.detachDetailParams, {
					conditions: data.conditions,
					title,
					visible: true
				})
			}
		})
	}

	@action removeDetachDetail = (params) => {
		const tableName = this.editDetachTabConfig.activeTabKey === '2' ? 'targetListTable' : 'rangeListTable';
		const sourcetype = this.editDetachTabConfig.activeTabKey === '2' ? '2' : '1';
		let content;
		if (!has(params, 'id')) {
			params = {
				id: this[tableName].selectedRowKeys
			}
			content = i18n.confirm.deleteSelected();
		} else {
			content = i18n.confirm.delete();
		}
		params.mainId = this.selectedDetach.id;
		params.sourcetype = sourcetype;

		this.confirmInfo({
			content,
			onOk: () => {
				api.delAppDetachDetial(params).then(data => {
					if (data.status === '1') {
						message.success(i18n.message.deleteSuccess());
						this[tableName].getDatas();
					} else
						message.error(data.message);
				}, error => {
					message.error(i18n.message.actionError());
				});
			}
		});
	}
	/********************* action list *********************/
}

export const hrmAppDetach = new HrmAppDetach();