import {
	observable,
	action,
	computed,
} from 'mobx';
import {
	WeaButtonIcon,
	WeaLocaleProvider,
} from 'ecCom';
import {
	WeaForm,
	WeaTableNew
} from 'comsMobx';
import {
	message,
	Button,
	Modal,
} from 'antd';
import * as api from '../apis/hrmgroup';
import {i18n} from '../public/i18n.js';
const {
	TableStore
} = WeaTableNew;
const getLabel = WeaLocaleProvider.getLabel;
const confirm = Modal.confirm;

class HrmSpaGroup {
	get TOP() {
		return {
			showDropIcon: true,
			iconBgcolor: '#217346',
			icon: <i className='icon-coms-hrm'/>,
			title: getLabel(81554, "常用组"),
		}
	}

	get conf() {
		return [{
			func: 'save',
			name: getLabel(86, '保存')
		}, {
			func: 'saveToDetail',
			name: getLabel(32159, '保存并进入详细设置')
		}];
	}

	get mConf() {
		return [{
			func: 'importMember',
			name: getLabel(18596, '导入')
		}, {
			func: 'new',
			name: getLabel(82, '新建')
		}, {
			func: 'batchDel',
			name: getLabel(384127, '批量删除')
		}]
	}

	@computed get tConf() {
		let c;
		if (this.pageType === '1') {
			c = this.conf;
		} else {
			const {
				selectedKey
			} = this.tab;

			let s = this.conf.slice(0, 1); //保存
			if (selectedKey === '0') {
				c = s;
			} else if (selectedKey === '1') {
				c = [...s, ...this.mConf];
			} else {
				c = this.mConf.slice(1); //新建和批量删除
			}
		}

		return c;
	}

	@computed get rConf() {
		const icons = ['icon-coms-Preservation', 'icon-coms-Flow-setting'];
		const rc = this.conf.map((c, i) => {
			return Object.assign(c, {
				icon: icons[i]
			});
		});
		let c;
		if (this.pageType === '1') {
			c = rc;
		} else {
			const {
				selectedKey
			} = this.tab;

			let s = rc.slice(0, 1); //保存
			if (selectedKey === '0') {
				c = s;
			} else {
				const icons = ['icon-coms-download2', 'icon-coms-plus', 'icon-coms-Loss'];
				const rs = this.mConf.map((c, i) => {
					return Object.assign(c, {
						icon: icons[i]
					});
				});
				if (selectedKey === '1') {
					c = [...s, ...rs];
				} else {
					c = rs.slice(1);
				}

			}
		}

		return c;
	}

	@computed get topButtons() {
		return this.tConf.map((item, index) => {
			const {
				func,
				name
			} = item;

			return (
				<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@t4dxfe@${index}`} 
					type="primary" 
					disabled={this.getDisabled(func)} 
					onClick={() => this[func]()}
				>
					{name}
				</Button>
			)
		});
	}

	@computed get dropMenuDatas() {
		return this.rConf.map((item, index) => {
			const {
				func,
				name,
				icon
			} = item;

			return {
				key: icon,
				disabled: this.getDisabled(func),
				icon: <i className={`${icon}`} />,
				content: name,
				onClick: () => this[func]()
			}
		});
	}

	getDisabled = (type) => {
		const {
			selectedKey
		} = this.tab;

		let disabled;
		if (selectedKey === '0') {
			disabled = this.pageForm.loading;
		} else {
			const {
				comsWeaTableStore
			} = this.table, {
				loading,
				selectedRowKeys
			} = comsWeaTableStore;

			if (type === 'batchDel') {
				disabled = (selectedRowKeys.length === 0)
			} else {
				disabled = loading;
			}
		}

		return disabled;
	}

	importStore = null;

	store = null;

	exportStore = (importStore, store) => {
		this.importStore = importStore;
		this.store = store;
	}

	importMember = () => {
		const {
			setTempletName,
			setImportDialogTitle,
			setImportType,
			setImportDialogVisible,
			setSourceStore,
			setOtherParams,
		} = this.importStore;

		setTempletName(getLabel(129833, '导入模板'));
		setImportDialogTitle(getLabel(511074, '常用组成员导入'));
		setImportType('groupMember');
		setImportDialogVisible(true);
		setSourceStore(this.store);
		setOtherParams({groupid:this.groupId})
	}

	new = () => {
		const {
			selectedKey,
			ref
		} = this.tab;


		if (selectedKey === '1') {
			ref && ref.openModal();
		}

		if (selectedKey === '2') {
			this.dialog.visible = true;
			this.getShareScopeForm()
		}
	}

	@action getShareScopeForm = () => {
		const params = {
			cmd: 'share'
		};
		if (this.f_weaver_belongto_userid) {
			Object.assign(params, {
				f_weaver_belongto_userid: this.f_weaver_belongto_userid
			});
		}
		api.getFormCondition(params).then(data => {
			const {
				condition
			} = data;

			condition.forEach(c => {
				c.items.forEach(item => {
					const {
						domkey,
						conditionType
					} = item;

					const key = domkey[0];
					if (conditionType === 'BROWSER') {
						Object.assign(item, {
							rules: 'required|string'
						});
					}
					if (key === 'seclevel') {
						Object.assign(item, {
							rules: 'scopeRequired',
							startValue: 10,
							endValue: 100,
						});
					}
				})
			});

			this.dialog.form = new WeaForm();
			this.dialog.conditions = condition;
			this.dialog.form.initFormFields(condition);
		}, error => {})
	}

	batchDel = () => {
		let _this = this;
		confirm({
			title: getLabel('131329', '信息确认'),
			content: getLabel('385625', '确定要删除选择的记录吗？'),
			okText: getLabel('33703', '确定'),
			cancelText: getLabel('32694', '取消'),
			onOk() {
				const {
					selectedKey
				} = _this.tab, {
					comsWeaTableStore
				} = _this.table, {
					selectedRowKeys
				} = comsWeaTableStore;

				selectedRowKeys.forEach(id => {
					_this.deleteTableRow(id);
				});

			},
			onCancel() {
				return false;
			},
		});

	}

	deleteTableRow = (id) => {
		const {
			selectedKey
		} = this.tab;

		const params = {
			groupid: this.groupId,
			id
		};

		if (selectedKey === '1') {
			Object.assign(params, {
				cmd: 'member'
			});
		} else {
			Object.assign(params, {
				cmd: 'share'
			});
		}
		if (this.f_weaver_belongto_userid) {
			Object.assign(params, {
				f_weaver_belongto_userid: this.f_weaver_belongto_userid
			});
		}

		api.deleteTableRow(params).then(data => {
			const {
				status
			} = data;

			if (status === '1') {
				message.success(getLabel(506026, '删除成功'));
				this.getSearchList();
			} else {
				message.warning(getLabel(83473, '删除失败'));
			}
		}, error => {})
	}

	@computed get pageLoading() {
		const {
			selectedKey
		} = this.tab;

		if (selectedKey === '0') {
			return this.pageForm.loading;
		} else {
			const {
				comsWeaTableStore
			} = this.table;

			return comsWeaTableStore.loading
		}

	}

	@observable pageForm = {
		form: new WeaForm(),
		loading: false,
	}

	@observable isPublicGroup = false;

	@action getHrmGroupForm = () => {
		const params = {
			cmd: 'base'
		};
		if (this.pageType === '2') {
			Object.assign(params, {
				groupid: this.groupId
			})
		}
		if (this.f_weaver_belongto_userid) {
			Object.assign(params, {
				f_weaver_belongto_userid: this.f_weaver_belongto_userid
			});
		}
		this.pageForm.loading = true;
		api.getFormCondition(params).then(data => {
			const {
				condition
			} = data;

			condition.map(c => {
				c.items.map(item => {
					const {
						domkey
					} = item;

					if (domkey[0] === 'type') {
						if (this.pageType === '1') {
							item.value = this.groupType;
						} else {
							this.isPublicGroup = item.value === '1';
						}
					}
				});
			});

			this.pageForm.form = new WeaForm();
			this.pageForm.form.setCondition(condition);
			this.pageForm.loading = false;
		}, error => {})
	}


	@observable pageType = '1';

	groupId = '';

	groupType = '0';

	f_weaver_belongto_userid = '';

	callback = (type) => {
		const pDialog = top.window.getParentDialog();
		if (pDialog) {
			pDialog.callback && pDialog.callback(type);
			pDialog.props.callback && pDialog.props.callback(type);
		}
	}

	save = () => {
		const {
			selectedKey
		} = this.tab;
		if (this.pageType === '2' && selectedKey === '1') {
			this.saveTable(() => this.callback(1));
		} else {
			this.saveForm(this.pageType, () => this.callback(0));
		}
	}

	saveToDetail = () => {
		this.saveForm('2', () => this.callback(1));
	}

	saveForm = (type, callback) => {
		const {
			form
		} = this.pageForm;

		form.validateForm().then(f => {
			if (f.isValid) {
				const params = {
					cmd: 'base',
					...form.getFormParams()
				};
				if (this.pageType === '2') {
					Object.assign(params, {
						groupid: this.groupId
					});
				}
				if (this.f_weaver_belongto_userid) {
					Object.assign(params, {
						f_weaver_belongto_userid: this.f_weaver_belongto_userid
					});
				}
				api.saveForm(params).then(data => {
					const {
						status,
						groupid,
					} = data;

					if (status === '1') {
						// message.success(data.message);
						this.pageType = type;
						this.groupId = groupid;
						this.getHrmGroupForm();
						callback && callback();
					} else {
						message.warning(data.message);
					}
				}, error => {})
			} else {
				f.showErrors();
			}
		})
	}

	get buttonsAds (){
		return [getLabel(82529, '搜索'), getLabel(27088, '重置'), getLabel(32694, '取消')];
	} 

	get TAB() {
		return {
			advanceHeight: 130,
			hasMask: false,
			keyParam: 'key',
			setShowSearchAd: bool => this.setShowSearchAd(bool),
			onSearch: () => this.onSearch(),
			onSearchChange: val => this.onSearchChange(val),
			onChange: key => this.onTabChange(key),
			buttonsAd: this.buttonsAds.map((name, index) => {
				const type = (index === 0) && "primary";
				let callback;
				if (index === 0) {
					callback = () => this.onSearch();
				} else if (index === 1) {
					callback = () => this.tab.form.resetConditionValue();
				} else {
					callback = this.setShowSearchAd
				}
				return <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@ogg7f1@${index}`} type={type} onClick={() => callback(index === 2 && false)}>{name}</Button>
			})
		}
	}
	

	@observable tab = {
		showSearchAd: false,
		form: new WeaForm(),
		selectedKey: '0',
		ref: null
	}

	@computed get searchsBaseValue() {
		const {
			form
		} = this.tab;
		return form.getFormParams().resourcename;
	}

	@computed get searchType() {
		const {
			selectedKey
		} = this.tab;

		if (selectedKey === '1') {
			return ['base', 'advanced']
		} else {
			return [];
		}
	}

	@computed get hasTab() {
		return this.pageType === '2';
	}

	@computed get tabDatas() {
		const DATAS = [{
			key: '0',
			title: getLabel(505832, '基本信息')
		}, {
			key: '1',
			title: getLabel(431, '成员')
		}, {
			key: '2',
			title: getLabel(82752, '共享范围')
		}];


		let datas;
		if (this.isPublicGroup) {
			datas = DATAS;
		} else {
			datas = DATAS.slice(0, 2);
		}

		return datas
	}

	@computed get tabButtons() {
		const {
			selectedKey
		} = this.tab;
		const total = [{
			icon: 'import',
			func: 'importMember'
		}, {
			icon: 'add',
			func: 'new'
		}, {
			icon: 'del',
			func: 'batchDel'
		}];
		let t;
		if (selectedKey === '1') {
			t = total;
		} else if (selectedKey === '2') {
			t = total.slice(1);
		} else {
			t = [];
		}
		const btns = t.map((type, index) => {
			const {
				icon,
				func,
			} = type;
			return (
				<WeaButtonIcon ecId={`${this && this.props && this.props.ecId || ''}_WeaButtonIcon@oieut2@${index}`} 
					buttonType={icon} 
					type="primary"
					disabled={this.getDisabled(func)}
					onClick={this[func]}
				/>
			)
		});

		return btns;
	}

	@action setShowSearchAd = (bool) => {
		this.tab.showSearchAd = bool;
	}

	onSearch = () => {
		this.getSearchList();
		this.setShowSearchAd(false);
	}

	onSearchChange = (val) => {
		const {
			form
		} = this.tab;

		form.updateFields({
			resourcename: {
				value: val
			}
		});

	}

	onTabChange = (key) => {
		this.tab.selectedKey = key;

		if (this.tab.showSearchAd) {
			this.tab.showSearchAd = false;
		}

		if (key === '1') {
			this.getSearchForm();
		} else {
			this.getSearchList();
		}
	}

	@action getSearchForm = () => {
		const params = {
			cmd: 'member'
		};
		if (this.f_weaver_belongto_userid) {
			Object.assign(params, {
				f_weaver_belongto_userid: this.f_weaver_belongto_userid
			});
		}
		api.getSearchCondition(params).then(data => {
			const {
				condition
			} = data;

			this.tab.form = new WeaForm();
			this.tab.form.setCondition(condition);
			this.getSearchList();
		}, error => {})
	}

	@action exportBrowserRef = (ref) => {
		this.tab.ref = ref;
	}

	TABLE = {
		hasOrder: true,
		needScroll: true,
	}

	changedOrder = [];

	@observable table = {
		comsWeaTableStore: new TableStore(),
	}

	@action getSearchList = () => {
		const {
			selectedKey
		} = this.tab;

		const params = {
			groupid: this.groupId,
		};

		if (selectedKey === '1') {
			Object.assign(params, {
				cmd: 'member',
				...this.tab.form.getFormParams()
			});
		} else {
			Object.assign(params, {
				cmd: 'share',
			});
		}
		if (this.f_weaver_belongto_userid) {
			Object.assign(params, {
				f_weaver_belongto_userid: this.f_weaver_belongto_userid
			});
		}
		api.getSearchResult(params).then(data => {
			const {
				sessionkey
			} = data;
			this.table.comsWeaTableStore = new TableStore();
			this.table.comsWeaTableStore.getDatas(sessionkey, 1);
		}, error => {})
	}

	@action onDsporderChange = (val, rowId) => {
		const orders = [],
			ids = [];

		this.changedOrder.forEach(item => {
			const a = item.split('-');
			ids.push(a[0]);
			orders.push(a[1]);
		});

		const index = ids.findIndex(id => id === rowId);
		if (index > -1) {
			this.changedOrder.splice(index, 1);
		}
		const v = `${rowId}-${val}`;
		this.changedOrder.push(v);
	}

	saveTable = (callback) => {
		const params = {
			cmd: 'saveDspOrder',
			groupid: this.groupId,
			dspOrder: this.changedOrder.toString()
		};
		if (this.f_weaver_belongto_userid) {
			Object.assign(params, {
				f_weaver_belongto_userid: this.f_weaver_belongto_userid
			});
		}
		api.saveForm(params).then(data => {
			const {
				status,
			} = data;

			if (status === 1) {
				message.success(data.message);
				this.getSearchList();
				this.changedOrder = [];
				callback && callback();
			} else {
				message.warning(data.message);
			}
		}, error => {})
	}

	del = (id) => {
		let _this = this;
		confirm({
			title: getLabel('131329', '信息确认'),
			content: getLabel('83877', '确定要删除吗？'),
			okText: getLabel('33703', '确定'),
			cancelText: getLabel('32694', '取消'),
			onOk() {
				_this.deleteTableRow(id);
			},
			onCancel() {
				return false;
			},
		});
	}

	memberIds = '';

	get BROWSER() {
		return {
			ref: this.exportBrowserRef,
			type: 17,
			title: i18n.label['83496'](),
			hasAdvanceSerach: true,
			isSingle: false,
			onChange: datas => {
				this.memberIds = datas;
				datas && this.saveDialogForm();
			}
		}
	}

	get DIALOG() {
		return {
			hasScroll: true,
			icon: 'icon-coms-hrm',
			iconBgcolor: '#217346',
			title: getLabel(125217, '添加成员'),
			onCancel: () => {
				this.dialog.visible = false
			},
			moreBtn: {
				datas: []
			},
			buttons: [<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@ksws0l@1`} type='primary' onClick={() => this.saveDialogForm()}>{getLabel(30986, '保存')}</Button>]
		}
	}
	

	@observable dialog = {
		visible: false,
		loading: false,
		conditions: [],
		form: new WeaForm(),
		date: new Date(),
	}

	@computed get dialogStyle() {
		const {
			selectedKey
		} = this.tab;

		let style;
		if (selectedKey === '1') {
			style = {
				width: 500,
				height: 120
			}
		} else {
			style = {
				width: 550,
				height: 220
			}
		}

		return style;
	}

	@computed get footerButtons() {
		const {
			selectedKey
		} = this.tab;

		let btns;
		if (selectedKey === '0') {
			btns = this.topButtons
		} else if (selectedKey === '1') {
			btns = this.topButtons.slice(0, 1);
		} else {
			btns = [];
		}

		return btns;
	}

	saveDialogForm = () => {
		const {
			selectedKey
		} = this.tab;

		const callApi = (params) => {
			if (this.f_weaver_belongto_userid) {
				Object.assign(params, {
					f_weaver_belongto_userid: this.f_weaver_belongto_userid
				});
			}
			api.saveForm(params).then(data => {
				const {
					status,
				} = data;

				if (status === '1') {
					// message.success(data.message || getLabel(-1, '保存成功'));
					this.dialog.visible = false;
					this.getSearchList();
					this.callback(1);
				} else {
					message.warning(data.message || getLabel(84544, '保存失败'));
				}
			}, error => {})
		}

		const params = {
			groupid: this.groupId,
		};
		if (selectedKey === '1') {
			Object.assign(params, {
				cmd: 'member',
				members: this.memberIds
			});
			callApi(params);
		} else {
			const {
				form
			} = this.dialog;

			const {
				sharetype,
				jobtitlelevel,
				seclevelto
			} = form.getFormParams();

			Object.assign(params, {
				cmd: 'share',
				...form.getFormParams()
			});

			//兼容
			Object.assign(params, {
				seclevelTo: seclevelto
			});

			window.e9HideFormFieldKeys = [];

			const hideKeys = [];

			this.dialog.conditions.forEach(c => {
				c.items.forEach(item => {
					const {
						conditionType,
						domkey
					} = item;

					const key = domkey[0];

					if (conditionType === 'BROWSER') {
						hideKeys.push(key);
					}
					if (key === 'customid') {
						hideKeys.push(key);
					}
					if (key === 'seclevel') {
						hideKeys.push('seclevel__seclevelto');
					}
				});
			});

			const exclude = (validateKeys) => {
				validateKeys.forEach(validateKey => {
					const index = hideKeys.findIndex(key => key === validateKey);

					hideKeys.splice(index, 1);
				});
			}

			switch (sharetype) {
				case '1': //人力资源
					exclude(['rsid']);
					break;
				case '2': //分部
					exclude(['sbid', 'seclevel__seclevelto']);
					break;
				case '3': //部门
					exclude(['did', 'seclevel__seclevelto']);
					break;
				case '4': //角色
					exclude(['rid', 'seclevel__seclevelto']);
					break;
				case '7': //岗位
					const validateKeys = ['jobtitle'];
					if (jobtitlelevel === '1') {
						validateKeys.push('jobtitledepartment');
					}
					if (jobtitlelevel === '2') {
						validateKeys.push('jobtitlesubcompany');
					}
					exclude(validateKeys);
					break;
				case '8': //客户
					exclude(['customid', 'seclevel__seclevelto']);
					break;
				case '5': //所有人
					exclude(['seclevel__seclevelto']);
					break;
			}

			window.e9HideFormFieldKeys = hideKeys;

			form.validateForm().then(f => {
				if (f.isValid) {
					callApi(params);
				} else {
					f.showErrors();
					this.dialog.date = new Date();
				}
			})
		};

	}

	TYPE = [{
		passiveKey: 'rsid', //人力资源
		activeKey: 'sharetype', //类型
		showValue: '1'
	}, {
		passiveKey: 'sbid', //分部
		activeKey: 'sharetype', //类型
		showValue: '2'
	}, {
		passiveKey: 'alllevel', //包含下级
		activeKey: 'sharetype', //类型
		showValue: '2'
	}, {
		passiveKey: 'did', //部门
		activeKey: 'sharetype', //类型
		showValue: '3'
	}, {
		passiveKey: 'rid', //角色
		activeKey: 'sharetype', //类型
		showValue: '4'
	}, {
		passiveKey: 'rolelevel', //角色级别
		activeKey: 'sharetype', //类型
		showValue: '4'
	}, {
		passiveKey: 'jobtitle', //岗位
		activeKey: 'sharetype', //类型
		showValue: '7'
	}, {
		passiveKey: 'jobtitlelevel', //岗位级别
		activeKey: 'sharetype', //类型
		showValue: '7'
	}, {
		passiveKey: 'customid', //客户
		activeKey: 'sharetype', //类型
		showValue: '8'
	}, {
		passiveKey: 'seclevel', //安全级别
		activeKey: 'sharetype', //类型
		showValue: '2,3,4,8,5'
	}];

	JOBTITLE = [{
		passiveKey: 'jobtitledepartment', //指定部门
		activeKey: 'jobtitlelevel', //岗位级别
		showValue: '1'
	}, {
		passiveKey: 'jobtitlesubcompany', //指定分部
		activeKey: 'jobtitlelevel', //岗位级别
		showValue: '2'
	}];

	FORMCONFIG = {
		dynamicFields: [...this.TYPE, ...this.JOBTITLE]
	}

	setQueryParams = (query) => {
		const {
			groupId,
			groupType,
			f_weaver_belongto_userid,
		} = query;
		if (groupId) {
			this.groupId = groupId;
			this.pageType = '2';
		} else {
			this.groupType = groupType && groupType.toString();
			this.pageType = '1';
		}
		this.f_weaver_belongto_userid = f_weaver_belongto_userid;
	}

	reset = () => {
		this.tab.selectedKey = '0';
	}

	onFormElementsChange = (datas) => {
		const {
			form
		} = this.dialog;
		if (datas.hasOwnProperty('sharetype')) {
			const sharetype = datas.sharetype.value;

			if (sharetype !== '7') {
				form.updateFields({
					jobtitlelevel: '0'
				});
			}
		}
	}

}

export const hrmSpaGroup = new HrmSpaGroup();