import {
	observable,
	action,
	computed
} from 'mobx';
import {
	WeaForm,
	WeaTableNew,
	WeaSwitch
} from 'comsMobx';
import {WeaLocaleProvider, WeaInputLocale, WeaButtonIcon, WeaSelect} from 'ecCom';
import {
	Button,
	message,
	Menu
} from 'antd';
import HrmBaseStore from './baseStore';
import * as api from '../apis/subCompanyFieldDef';
import {
	cloneDeep,
	indexOf,
	findIndex,
	uniq,
	has,
	remove,
	filter
} from 'lodash';
import find from 'lodash/find';
import isEmpty from 'lodash/isEmpty';
import {
	validDBKeys
} from '../util/index';
import {
	i18n
} from '../public/i18n';
const getLabel = WeaLocaleProvider.getLabel;
const getCurrentLabel = WeaInputLocale.getCurrentLabel;
const {TableStore} = WeaTableNew;

export class HrmSubCompanyFieldDef extends HrmBaseStore {
	/********************* unobservable list *********************/
	//override baseStore.tabConfig
	tabDef = {
		color: '#000000',
		groupId: '',
		viewCondition: '1',
		topButtonDef: [{
			comType: 'button',
			type: 'primary',
			onClickHandle: this.saveFieldDefine,
			label: i18n.button.save,
			icon: this.menuIconCollection.save
		}, {
			comType: 'button',
			type: 'primary',
			onClickHandle: () => this.editGroup(),
			label: i18n.button.createGroup,
			icon: this.menuIconCollection.create
		}, {
			comType: 'button',
			type: 'primary',
			onClickHandle: this.doGroupSetting,
			label: i18n.button.groupMaintain,
			icon: this.menuIconCollection.setting,
			checkAction: 'groupInfoOperability'
		}],
		tabButtonDef: [{
			comType: 'button',
			icon: 'icon-coms-Add-to-hot',
			label: i18n.button.create,
			rightMenuIcon: this.menuIconCollection.create,
			onClickHandle: () => this.recordOP(this.editTable['fieldDef'], 'add')
		}]
	}
	tabConfig = {
		tabs: [],
		keyParam: 'viewCondition',
		activeTabKey: '1',
		onTabEdit: this.onTabEdit
	};
	moveToGroup = false;
	moveDropDown = () => (
		<Menu ecId={`${this && this.props && this.props.ecId || ''}_Menu@czjx1d`} onClick={this.dropdownClick}>
			{
				filter(this.tabConfig.tabs, (d) => {
					try{
						return d.groupid != this.activeTabInfo.tabInfo.groupid
					}catch(e){
						return true;
					}
				}).map((tab, index) => (
					<Menu.Item ecId={`${this && this.props && this.props.ecId || ''}_undefined@n4ghu2@${index}`} key={tab.groupid}>
						<div>{tab.title}</div>
					</Menu.Item>
				))
			}
			<Menu.Divider ecId={`${this && this.props && this.props.ecId || ''}_undefined@ejjn07`} />
			<Menu.Item ecId={`${this && this.props && this.props.ecId || ''}_undefined@8jlkfc`} key='createAndMove' style={{background: '#E8E8E8', textAlign:'center'}}>
				<div>{i18n.label.createAndMoveGroup()}</div>
			</Menu.Item>
		</Menu>
	)
	getDropdownDatas = () => {
		let datas = [
			{
				key: '1',
				text: i18n.button.delete(),
				show: <span className='icon-coms-form-delete-hot' />,
				selected: this.dropdownSelectedKey === '1'
			},
			{
				key: '2', 
				text: i18n.button.copy(), 
				show: <span className='icon-coms-copy-hot' />,
				selected: this.dropdownSelectedKey === '2'
			},
			{
				key: '3', 
				text: i18n.button.moveToGroup(), 
				show: <span className='icon-coms-move2' />,
				selected: this.dropdownSelectedKey === '3',
				isDropBtn: true
			}
		]
		if(this.selectedTreeNodeInfo != null && this.selectedTreeNodeInfo.viewAttr != 1){
			datas.splice(2, 1);
		}
		return datas;
	}
	dropdownProps = () => ({
		type: 'small',
		datas: this.getDropdownDatas(),
		dropBtnProps: {
			style: { padding: '10px 4px' }
		},
		btnDropPropsDatas: {
			'3': {
				overlay: this.moveDropDown()
			}
		},
		btnOnClick: key => {
			switch(key){
				case '1':
					this.recordOP(this.editTable['fieldDef'], 'remove')
					break;
				case '2':
					this.recordOP(this.editTable['fieldDef'], 'copy')
					break;
				case '3':
					break;
			}
		},
		menuOnClick: (key, e) => {
			this.tableEditConfig.fieldDef.selectedRowKeys = [];
			this.feildDefTableSelectedRows.length = 0;
			this.refreshMainTabComponent = new Date().getTime();
			this.dropdownSelectedKey = key;
		}
	})

	fieldDefColumns = () => {
		const columns = [{
			title: i18n.label.fieldLabel(), //列名
			dataIndex: 'fieldlabel', //列的id 对应数据
			key: 'fieldlabel', //前端渲染key值
			useRecord: true,
			colSpan: 1,
			width: '15%',
			com: [{
				label: '',
				type: 'INPUT',
				key: 'fieldlabel',
				viewAttr: '3',
				otherParams: {
					...window.inputType
				}
			}],
		}, {
			title: i18n.label.fieldName(),
			dataIndex: 'fieldname',
			key: 'fieldname',
			useRecord: true,
			colSpan: 1,
			width: '15%',
			com: [{
				label: '',
				type: 'INPUT',
				key: 'fieldname',
				viewAttr: '3',
				otherParams: {
					length: 25,
					regExp: /^[a-zA-Z][a-zA-Z0-9]*$/,
					filter: (val) => {
						const {
							isValid,
							value
						} = validDBKeys(val);
						this.isDBKeyValid = isValid;
						return value;
					}
				}
			}],
		}, {
			title: i18n.label.fieldType(),
			dataIndex: 'fieldType',
			key: 'fieldType',
			useRecord: true,
			colSpan: 1,
			width: (this.moduleName === 'resourcefielddefined' && !this.isJobTreeNode) ? "30%" : "40%",
			com: [{
				label: '',
				type: 'CUSTOMFIELD',
				key: 'fieldType',
				viewAttr: '3',
				options: ['peculiar'],
				otherParams: {
					customProps: {
						'input.text': {
							viewAttr: 3
						},
						'textarea': {
							parent: {
								type: "div",
								style: {
									display: "none"
								}
							},
							style: {
								display: "none"
							}
						},
						'textarea.*': {
							parent: {
								type: "div",
								style: {
									display: "none"
								}
							},
							style: {
								display: "none"
							}
						},
						'textarea.*.*': {
							style: {
								display: "none"
							}
						},
						"select": {
							options: [{
								key: 'select',
								selected: true,
								showname: i18n.label.selectComponent()
							}]
						},
						"upload": {
							options: [{
								key: 'file',
								selected: true,
								showname: i18n.label.uploadFile()
							}]
						}
					}
				}
			}],
		}, {
			title: i18n.label.enable(),
			dataIndex: 'enable',
			key: 'enable',
			checkType: 'checkbox',
			colSpan: 1,
			width: '7%'
		}, {
			title: i18n.label.required(),
			dataIndex: 'required',
			key: 'required',
			checkType: 'checkbox',
			colSpan: 1,
			width: '8%'
		}];

		//人员卡片字段定义-添加【允许个人修改】列
		if (this.moduleName === 'resourcefielddefined') {
			if (this.isJobTreeNode) {//【工作信息】列表不添加【允许个人修改】列
			} else {
				columns.push({
					title: getLabel(510359,'允许个人修改'),
					dataIndex: 'isModify',
					key: 'isModify',
					checkType: 'checkbox',
					colSpan: 1,
					width: '11%'
				});
			}
		}
		this.encryptEnable && columns.push({
			title: getLabel('526997','加密设置'),
			dataIndex: 'canEncrypt',
			key: 'canEncrypt',
			com: [
				{
					type: 'custom',
					key: 'custom',
					render: (text, record, index, onEdit) => {
						const {canEncrypt} = record;
						if(canEncrypt == '1')
							return (
								<a onClick={() => this.onEncryptHandle(record)}>{getLabel('526997','加密设置')}</a>
							)
						return null;
					}
				}
			],
			colSpan: 1,
			width: '8%'
		});
		return columns;
	}

	groupDefColumns = () => [{
		title: i18n.label.groupName(), //列名
		dataIndex: 'groupName', //列的id 对应数据
		key: 'groupName', //前端渲染key值
		colSpan: 1,
		width: '70%',
		useRecord: true,
		com: [{
			label: '',
			type: 'INPUT',
			key: 'groupName',
			viewAttr: '3',
			otherParams: {
				...window.inputType
			}
		}],
	}, {
		title: i18n.label.show(),
		dataIndex: 'isShow',
		key: 'isShow',
		checkType: 'checkbox',
		colSpan: 1,
		useRecord: true,
		width: '30%'
	}];

	childInfoDefColumns = () => [{
		title: i18n.label.childInfoName(), //列名
		dataIndex: 'name', //列的id 对应数据
		key: 'name', //前端渲染key值
		colSpan: 1,
		width: '70%',
		useRecord: true,
		com: [{
			label: '',
			type: 'INPUT',
			key: 'name',
			viewAttr: '3',
			otherParams: {
				...window.inputType
			}
		}],
	}, {
		title: i18n.label.show(),
		dataIndex: 'isShow',
		key: 'isShow',
		checkType: 'checkbox',
		colSpan: 1,
		useRecord: true,
		width: '30%'
	}];

	getColumns = () => {
		let columns = cloneDeep(this.fieldDefColumns())
		if (this.moduleName.indexOf('resource') >= 0) {
			columns[1].com = [{
				label: '',
				type: 'TEXT',
				key: 'fieldname',
			}]
		}
		return columns;
	}

	tableEditConfig = {
		fieldDef: {
			...this.editTableConfig,
			showAdd: false,
			showDelete: false,
			showCopy: false,
			columns: this.getColumns(),
			copyFilterProps: ['id', 'fieldlabel', 'fieldname', 'com.fieldname', 'com.fieldlabel'],
			datas: [],
			selectedData: {},
			onChange: this.onFieldDefChange,
			onRowSelect: this.onFieldDefRowSelect,
			getRowSelection: this.onFieldDefRowSelection,
			onDelete: this.onFieldDefDeleteOpr,
			onEdit: this.onEdit,
			onAdd: this.onAdd
		},
		groupSetting: {
			...this.editTableConfig,
			showTitle: true,
			showAdd: true,
			showDelete: true,
			showCopy: false,
			columns: this.groupDefColumns(),
			copyFilterProps: ['id', 'groupName', 'isShow'],
			datas: [],
			selectedData: {},
			onChange: (datas) => this.onGroupSettingChange(datas, 'group'),
			onRowSelect: (sRowKeys, rows, dataIndex, selectedDatas) => this.onGroupSettingRowSelect(sRowKeys, rows, dataIndex, selectedDatas, 'group'),
			getRowSelection: this.onGroupSettingRowSelection,
			onDelete: (ks, ds) => this.onGroupSettingDeleteOpr(ks, ds, 'group')
		},
		childInfoSetting: {
			...this.editTableConfig,
			showTitle: true,
			showAdd: true,
			showDelete: true,
			showCopy: false,
			columns: this.childInfoDefColumns(),
			copyFilterProps: ['id', 'name', 'isShow'],
			datas: [],
			selectedData: {},
			onChange: (datas) => this.onGroupSettingChange(datas, 'childInfo'),
			onRowSelect: (sRowKeys, rows, dataIndex, selectedDatas) => this.onGroupSettingRowSelect(sRowKeys, rows, dataIndex, selectedDatas, 'childInfo'),
			getRowSelection: this.onGroupSettingRowSelection,
			onDelete: (ks, ds) => this.onGroupSettingDeleteOpr(ks, ds, 'childInfo')
		}
	}

	activeTabInfo = {}
	tabRecord = [];
	isDBKeyValid = true;
	/********************* unobservable list *********************/

	/********************* dialog info setting *********************/
	editorDialogRightMenu = [];
	getDialogOpButtons = () => { //获取权限组编辑对话框按钮列表
		this.editorDialogRightMenu.length = 0;
		let buttons = [<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@i3u56h`} type="primary" onClick={() => this.dialogSaveOp()}>{i18n.button.save()}</Button>];
		this.editorDialogRightMenu.push({
			key: '1',
			content: i18n.button.save(),
			icon: <i className={this.menuIconCollection.save}/>,
			onClick: () => this.dialogSaveOp(false)
		});

		if(this.dialogParams.groupInfoSetting.visible){
			let logType = '';
			switch(this.moduleName){
				case 'subcompanyfielddefined':
					logType = 'HRM_ENGINE_SUBCOMPANYFIELDDEFINED_GROUP';
					break;
				case 'departmentfielddefined':
					logType = 'HRM_ENGINE_DEPARTMENTFIELDDEFINED_GROUP';
					break;
				case 'resourcefielddefined':
					logType = 'HRM_ENGINE_RESOURCEFIELDDEFINED_GROUP';
					break;
			}
			this.editorDialogRightMenu.push(...this.getBasicMenus(logType));
		}

		return buttons;
	}
	/********************* dialog info setting *********************/

	/***** form ****/
	editGroupInfoFormFields = [{
		"title": i18n.label.basicSetting(),
		"items": [{
			"colSpan": 2,
			"conditionType": "INPUT",
			"domkey": ["groupName"],
			"fieldcol": 12,
			"isQuickSearch": false,
			"label": i18n.label.groupName,
			"labelcol": 6,
			"precision": 0,
			"rules": "required|string",
			"value": "",
			"viewAttr": 3,
		}],
		"defaultshow": true
	}]

	editChildInfoFormFields = [{
		"title": i18n.label.basicSetting,
		"items": [{
			"colSpan": 2,
			"conditionType": "INPUT",
			"domkey": ["name"],
			"fieldcol": 12,
			"isQuickSearch": false,
			"label": i18n.label.childInfoName,
			"labelcol": 6,
			"precision": 0,
			"rules": "required|string",
			"value": "",
			"viewAttr": 3
		}, {
			"colSpan": 2,
			"conditionType": "INPUTNUMBER",
			"domkey": ["infoOrder"],
			"fieldcol": 12,
			"isQuickSearch": false,
			"label": i18n.label.displayOrder,
			"labelcol": 6,
			"precision": 0,
			"value": "0",
			"viewAttr": 2
		}],
		"defaultshow": true
	}]

	/********************* observable list *********************/
	dialogParams = { //override baseStore.dialogParams
		editGroupInfo: {
			visible: false,
			title: '',
			moreBtn: {
				datas: []
			}
		},
		groupInfoSetting: {
			visible: false,
			title: '',
			moreBtn: {
				datas: []
			}
		},
		createChildInfo: {
			visible: false,
			title: '',
			moreBtn: {
				datas: []
			}
		},
		childInfoSetting: {
			visible: false,
			title: '',
			moreBtn: {
				datas: []
			}
		}
	}

	@observable dropdownSelectedKey = '1';
	@observable _groupInfoOperability = true;
	@observable feildDefTableSelectedRows = [];
	@observable groupSettingTableSelectedRows = [];
	@observable _feildDefSaveable = true;

	@observable refreshMainTabComponent = new Date().getTime();
	@observable refreshFeildDef = new Date().getTime(); //当需要刷新主页面tab时，变更此值
	@observable refreshForm = new Date().getTime(); 
	@observable refreshEditGroupTabComponent = new Date().getTime(); //当需要刷新权限组编辑tab时，变更此值
	@observable spinning = false;
	@observable moduleName = '';
	/********************* observable list *********************/

	/********************* computed list *********************/
	@computed get feildDefRemoveable() { //字段定义表是否有选中行
		return this.feildDefTableSelectedRows.length === 0;
	}

	@computed get groupInfoRemoveable() { //字段定义表是否有选中行
		return this.groupSettingTableSelectedRows.length === 0;
	}

	@computed get feildDefSaveable() { //字段定义表是否有记录
		return this._feildDefSaveable;
	}

	@computed get groupInfoOperability() { //是否有组信息
		return this._groupInfoOperability;
	}
	/********************* computed list *********************/

	/********************* action list *********************/
	/**
	 * 初始化模块数据
	 * @return {null}
	 */
	@action initData = (create = false, init = false, module) => {
		this.dropdownSelectedKey = '1';
		if (module != null) {
			this.moduleName = module;
		}
		this.selectedTreeNodeInfo = null;
		// this.tableEditConfig.fieldDef.columns = cloneDeep(this.fieldDefColumns());
		api.getTabInfo(this.moduleName).then(data => {
			this._groupInfoOperability = data.tabs.length === 0;
			if (data.status === '1') {
				let tabArr = [];
				this.tabRecord = data.tabs;
				data.tabs && data.tabs.map((tabInfo, index) => {
					let t = cloneDeep(this.tabDef);
					tabArr.push({
						...t,
						...tabInfo,
						viewCondition: `${tabArr.length + 1}`
					});
				});
				if (tabArr.length > 0) {
					this.tabConfig.tabs = [...tabArr];
					// this.setTableEditColTitle();
					this.setActiveTab(this.tabConfig, init ? '1' : !create ? this.tabConfig.activeTabKey : `${tabArr.length}`);
					this.containerInitFinished = {
						...this.containerInitFinished,
						init: true
					}
				}
			} else {
				message.error(data.message);
			}
		}, error => {

		})
	}

	setTableEditColTitle = () => {
		[...Object.keys(this.tableEditConfig)].map(k => {
			this.tableEditConfig[k].columns.map(c => {
				if (typeof(c.title) == 'function')
					c.title = c.title();
				else
					c.title = c.title;
			})
		})
	}

	/**
	 * tab change事件(通过变更refreshMainTabComponent使index重新render)
	 * @param  {Object} tabConfig [tabConfig]
	 * @param  {String} key       [tabKey]
	 * @return {null}
	 */
	@action setActiveTab = (tabConfig, key) => {
		this.tableEditConfig.fieldDef.datas = [];
		tabConfig.activeTabKey = key || tabConfig.tabs[0].viewCondition;
		const tabIndex = this.getTabIndex(this.tabConfig.tabs, key);
		if (tabIndex < 0) return;
		this.dropdownSelectedKey = '1';
		this.feildDefTableSelectedRows.length = 0;
		this.tableEditConfig.fieldDef.selectedRowKeys = [];
		this.activeTabInfo = {
			activeTabKey: this.tabConfig.activeTabKey,
			activeTabIndex: this.getTabIndex(this.tabConfig.tabs, this.tabConfig.activeTabKey),
			tabInfo: this.tabConfig.tabs[tabIndex]
		}
		let params = {
			groupId: this.activeTabInfo.tabInfo.groupid,
		}
		if (this.selectedTreeNodeInfo != null)
			params.groupType = this.selectedTreeNodeInfo.key
		this.spinning = true;
		api.getFieldDefinedInfo(this.moduleName, params).then(data => {
			if (data.status === '1') {
				const {
					datas,
					selectedData
				} = this.convertData(data.data, 'fieldDef');
				this.encryptEnable = data.encryptEnable;
				this.tableEditConfig.fieldDef.datas = datas;
				this.tableEditConfig.fieldDef.columns = this.getColumns();

				//人员卡片字段定义columns是动态的，因此需要重新计算得出selectedData
				if (this.moduleName === 'resourcefielddefined') {
					const {
						selectedData
					} = this.convertData(data.data, 'fieldDef');
					this.tableEditConfig.fieldDef.selectedData = selectedData;
				} else {
					this.tableEditConfig.fieldDef.selectedData = selectedData;
				}

				if (this.tabRecord.length > 0) {
					this.tabRecord[this.activeTabInfo.activeTabIndex].editable = (data.data.length === 0);
					this.activeTabInfo.tabInfo.editable = (data.data.length === 0);
				}
			} else
				message.error(data.message);
			this.spinning = false;
			this.refreshMainTabComponent = new Date().getTime();
		}, error => {this.spinning = false;})
	}

	@action onTabEdit = (targetKey, action) => {
		const tabIndex = this.getTabIndex(this.tabConfig.tabs, targetKey);
		if (tabIndex < 0) return;
		const tabInfo = this.tabConfig.tabs[tabIndex];
		switch (action) {
			case 'remove':
				this.confirmInfo({
					content: i18n.confirm.delete(),
					onOk: () => {
						let params = {
							id: tabInfo.groupid
						}
						if (this.selectedTreeNodeInfo != null)
							params.groupType = this.selectedTreeNodeInfo.key
						api.removeGroupInfo(this.moduleName, params).then(data => {
							if (data.status === '1') {
								message.success(i18n.message.deleteSuccess());
								this.tabConfig.activeTabKey = '1';
								if (this.moduleName.indexOf('resource') >= 0)
									this.getTabInfoByTreeNode();
								else
									this.initData();
							} else {
								message.error(data.message);
							}
						})
					}
				});
				break;
			default:
				break;
		}
	}

	@action dialogSaveOp = () => {
		this.dialogParams.editGroupInfo.visible && this.doSaveGroupInfo();
		this.dialogParams.groupInfoSetting.visible && this.doSaveGroupSetting();
		this.dialogParams.createChildInfo.visible && this.doSaveChildInfo();
		this.dialogParams.childInfoSetting.visible && this.doSaveChildInfoSetting();
	}

	@action editGroup = (group, moveToGroup = false) => {
		this.moveToGroup = moveToGroup;
		this.editGroupInfoFormFields.map(f => {
			if (typeof(f.title) == 'function')
				f.title = f.title();
			f.items.map(item => {
				if (typeof(item.label) == 'function')
					item.label = item.label();
				item.otherParams = {...window.inputType};
			})
		})
		let fields = [...this.editGroupInfoFormFields],
			dialogTitle = '';
		this.setFormData('groupInfoFrom', fields);
		if (group) {
			this.formTarget.groupInfoFrom.updateFields({
				groupName: {value: group.multiTitle || group.title || ''}
			});
			this.opId = group.groupid;
			dialogTitle = i18n.button.editGroup();
		} else {
			this.formTarget.groupInfoFrom.updateFields({
				groupName: {value: ''}
			});
			this.opId = null;
			dialogTitle = i18n.button.createGroup();
		}
		this.setDialogVisible('editGroupInfo', true, dialogTitle);
	}

	@action doGroupSetting = () => {
		this.tableEditConfig.groupSetting.datas.length = 0;
		let arr = [];
		this.tabRecord.map(tabInfo => {
			let viewAttr = tabInfo.viewAttr;
			// if (viewAttr != 1 && has(tabInfo, 'editable')) {
			// 	viewAttr = !tabInfo.editable ? 1 : 2;
			// }
			arr.push({
				"record": {
					"id": tabInfo.groupid,
					"viewAttr": tabInfo.viewAttr,
					"isShow": tabInfo.isShow,
					"groupName": tabInfo.multiTitle || tabInfo.title || '',
					"editable": tabInfo.editable
				},
				"props": {
					"checkProps": {
						"isShow": {
							viewAttr
						}
					}
				}
			})
		})
		Object.assign(this.tableEditConfig.groupSetting, { ...this.convertData(arr, 'groupSetting')
		});
		this.tableEditConfig.groupSetting.columns = this.groupDefColumns();
		this.tableEditConfig.groupSetting.datas.map(d => {
			Object.assign(d, {
				com: {
					groupName: [{
						label: '',
						type: 'INPUT',
						key: 'groupName',
						viewAttr: d.viewAttr,
						otherParams: {
							...window.inputType
						}
					}]
				}
			})
		})
		this.setDialogVisible('groupInfoSetting', true, i18n.button.groupMaintain());
	}

	doSaveGroupInfo = () => {
		this.formTarget.groupInfoFrom.validateForm().then(f => {
			if (f.isValid) {
				let record = {
					...this.formTarget.groupInfoFrom.getFormParams(),
					isShow: 1
				}
				const recordIndex = findIndex(this.tabConfig.tabs, {
					title: getCurrentLabel(record.groupName)
				});
				if (recordIndex >= 0) {
					f.showError('groupName', i18n.confirm.groupNameExist());
					this.showError = new Date().getTime();
					return;
				}
				let found = false,
					records = [];
				this.opId != null && Object.assign(record, {
					id: this.opId,
					isShow: this.activeTabInfo.tabInfo.isShow
				});
				this.tabConfig.tabs.map(tabInfo => {
					if (tabInfo.groupid === this.opId) {
						found = true;
						records.push(record)
					} else {
						records.push({
							id: tabInfo.groupid,
							isShow: tabInfo.isShow,
							groupName: tabInfo.title
						})
					}
				});
				!found && records.push(record);
				let params = {
					data: JSON.stringify({
						records: records
					})
				}
				if (this.selectedTreeNodeInfo != null)
					params.groupType = this.selectedTreeNodeInfo.key

				api.saveGroupInfo(this.moduleName, params).then(data => {
					if (data.status === '1') {
						this.setDialogVisible('editGroupInfo', false, '');
						if(this.moveToGroup){
							const ids = data.groupid.split(',');
							this.changeGroup(null, ids[ids.length - 1]);
						}else{
							if (this.moduleName.indexOf('resource') >= 0)
								this.getTabInfoByTreeNode();
							else
								this.initData(this.opId == null);
							message.success(i18n.message.saveSuccess());
						}
					} else
						message.error(data.message);
				}, error => {
					message.error(i18n.message.actionError());
				});
			} else {
				f.showErrors();
				this.showError = new Date().getTime();
			}
		});
	}

	@action saveFieldDefine = () => {
		if(this.spinning)
			return;
		this.spinning = true;
		this.recordOP(this.editTable['fieldDef'], 'valid');
		let data = cloneDeep(this.tableEditConfig.fieldDef.datas),
			labelArr = [],
			nameArr = [];
		if (!this.isDBKeyValid) {
			this.spinning = false;
			return;
		}

		const invalidEmpty = data.some((d, index) => {
			d.key = index;
			delete d.com;
			delete d.checkProps;
			delete d.viewAttr;
			if (has(d, 'fieldTypeObj')) {
				if (Array.isArray(d.fieldTypeObj) && d.fieldTypeObj.length > 0 && d.fieldTypeObj[0] != 'select')
					d.fieldType = d.fieldTypeObj;
				delete d.fieldTypeObj;
			}
			if (!Array.isArray(d.fieldType))
				delete d.fieldType;

			if (!has(d, 'enable'))
				d.enable = '0';
			if (!has(d, 'required'))
				d.required = '0';

			let fieldlabel = d.fieldlabel || '',
				fieldname = d.fieldname || '';
			if (fieldlabel === '' || (this.moduleName != 'resourcefielddefined' && fieldname === '')) {
				return true;
			}
			labelArr.push(getCurrentLabel(d.fieldlabel));
			nameArr.push(d.fieldname);
			return false;
		})
		let checkSame = false;
		if (this.moduleName.indexOf('resource') >= 0)
			checkSame = uniq(labelArr).length === data.length;
		else
			checkSame = uniq(labelArr).length === data.length && uniq(nameArr).length === data.length;
		if (invalidEmpty) {
			this.spinning = false;
			return;
		} else if (checkSame) {
			this.spinning = true;
			let dataObj = {
				groupId: this.activeTabInfo.tabInfo.groupid,
				records: data
			}
			if (this.selectedTreeNodeInfo != null)
				dataObj.groupType = this.selectedTreeNodeInfo.key;
			let params = {
				data: JSON.stringify(dataObj)
			}
			if (this.selectedTreeNodeInfo != null)
				params.groupType = this.selectedTreeNodeInfo.key;

			const checkRs = this.editTable['fieldDef'] && this.editTable['fieldDef'].refs.edit.doRequiredCheck() || {pass: true};
			if(!checkRs.pass){
				this.spinning = false;
				return;
			}
			
			api.saveFieldDefinedInfo(this.moduleName, params).then(data => {
				if (data.status === '1') {
					message.success(i18n.message.saveSuccess());
					if (this.moduleName.indexOf('resource') >= 0)
						this.getTabInfoByTreeNode();
					else
						this.initData();
				} else {
					message.error(data.message);
				}
				this.spinning = false;
			}, error => {this.spinning = false;})
		} else {
			message.error(i18n.confirm.displayOrDBFieldExist());
			this.spinning = false;
		}
	}

	@action onEdit = (keys, datas, c, dataIndex) => {
		if(dataIndex === 'fieldlabel' && this.moduleName != 'resourcefielddefined'){
			const oldRecord = this.tableEditConfig.fieldDef.datas[keys[0]];
			if(has(oldRecord, 'com') && has(oldRecord.com, 'fieldname') && oldRecord.com.fieldname.length > 0 && oldRecord.com.fieldname[0].type === 'TEXT'){
				return;
			}
			this.getPinYin({labelName: getCurrentLabel(datas[0].fieldlabel)}).then(data => {
				const {pinyin} = data;
				oldRecord.fieldname = pinyin;
				const arr = filter(this.tableEditConfig.fieldDef.datas, {fieldname: pinyin});
				if(arr.length > 1 && pinyin != ''){
					oldRecord.fieldname = pinyin + '1';
				}
				this.refreshFeildDef = new Date().getTime();
			});
		}
	}
	@action onAdd = (keys, datas) => {
		try{
			this.tableEditConfig.fieldDef.datas[keys[0] - 1].enable = '1';
			(this.tableEditConfig.fieldDef.selectedData.enable || []).push(keys[0] - 1);
			this.refreshFeildDef = new Date().getTime();
		}catch(e){

		}
	}

	@action onFieldDefChange = (datas) => {
		let selectedData = {
			enable: [],
			required: []
		}
		if (this.moduleName === 'resourcefielddefined') {
			Object.assign(selectedData,{
				isModify:[]
			});
		}
		datas.map((data, index) => {
			if (data['enable'] === '1')
				selectedData.enable.push(index);
			if (data['required'] === '1')
				selectedData.required.push(index);
			if (data['isModify'] && data['isModify'] === '1' && this.moduleName === 'resourcefielddefined') {
				selectedData.isModify.push(index);
			}
		})
		this.tableEditConfig.fieldDef.datas = datas;
		this.tableEditConfig.fieldDef.selectedData = selectedData;
		this._feildDefSaveable = datas.length === 0;
		if (datas.length === 0) {
			// this.initData();
		} else
			this.refreshFeildDef = new Date().getTime()
	}

	@action onFieldDefRowSelect = (sRowKeys, rows, dataIndex, selectedDatas) => {
		if (dataIndex == null) {
			this.feildDefTableSelectedRows = sRowKeys;
			this.tableEditConfig.fieldDef.selectedRowKeys = sRowKeys;
		} else {
			if (selectedDatas != null && selectedDatas.hasOwnProperty(dataIndex)) {
				const arr = selectedDatas[dataIndex];
				this.tableEditConfig.fieldDef.datas.map((data, index) => {
					if(dataIndex === 'enable'){
						data[dataIndex] = indexOf(arr, index) >= 0 ? '1' : '0';
						if(data[dataIndex] === '0'){
							data['required'] = '0';
							remove(selectedDatas['required'], v => v === index);
							data['isModify'] = '0';
							remove(selectedDatas['isModify'], v => v === index);
						}
					}else if(dataIndex === 'required'){
						data[dataIndex] = indexOf(arr, index) >= 0 ? '1' : '0';
						if (data[dataIndex] === '1') {
							data['enable'] = '1';
							if (selectedDatas['enable'].indexOf(index) < 0)
								selectedDatas['enable'].push(index);
						}
					} else if (dataIndex === 'isModify') {
						data[dataIndex] = indexOf(arr, index) >= 0 ? '1' : '0';
						if (data[dataIndex] === '1') {
							data['enable'] = '1';
							if (selectedDatas['enable'].indexOf(index) < 0)
								selectedDatas['enable'].push(index);
						}

					} else
						data[dataIndex] = indexOf(arr, index) >= 0 ? '1' : '0';
				})

				this.tableEditConfig.fieldDef.selectedData = selectedDatas;
			}
		}
		this.processLinkage(selectedDatas);
		this.refreshFeildDef = new Date().getTime()
	}

	//处理账号类型和主账号的联动（允许个人修改）：账号类型选中，主账号也会选中，反之亦然。
	processLinkage = (selectedDatas) => {
		const {datas} = this.tableEditConfig.fieldDef;

		const target = datas.find(data => data.fieldname === 'accounttype');

		if (!target) return;

		const accounttype = target.isModify;

		const  belongto = datas.find(data => data.fieldname === 'belongto').isModify;

		if (belongto !== accounttype) {
			datas.find(data => data.fieldname === 'belongto').isModify = accounttype;

			const belongtoIndex = datas.findIndex(data => data.fieldname === 'belongto');

			if (accounttype === '1') {
				selectedDatas['isModify'].push(belongtoIndex);
			}else{
				remove(selectedDatas['isModify'], v => v === belongtoIndex);
			}
		}

	}

	@action onFieldDefRowSelection = (rowSelection) => {
		let sel = {
			...rowSelection
		}
		sel.getCheckboxProps = (record) => {
			let disabled = false;
			switch(this.dropdownSelectedKey){
				case '2':
					disabled = false;//复制时，checkbox全部启用
					break;
				case '3':
					disabled = record.id == null || record.checkProps.enable.viewAttr === 1;//移动到组时，checkbox根据id是否为空或是否引用启用按钮状态赋值
					break;
				default:
					disabled = record.viewAttr === 1;//删除时，checkbox根据record.viewAttr赋值
					break
			}
			return {
				disabled
			};
		}
		return sel;
	}

	@action onFieldDefDeleteOpr = (ks, ds) => {
		let ids = [];
		ds.map(d => {
			if (has(d, 'id'))
				ids.push(d.id)
		});
		let params = {
			id: ids.join(',')
		}
		if (this.selectedTreeNodeInfo != null)
			params.groupType = this.selectedTreeNodeInfo.key;
		params.groupId = this.activeTabInfo.tabInfo.groupid;
		if(ids.length > 0){
			api.removeFieldDefinedInfo(this.moduleName, params).then(data => {
				if (data.status === '1') {
					// this.initData();
					this.tableEditConfig.fieldDef.selectedRowKeys.length = 0;
					message.success(i18n.message.deleteSuccess());
				} else
					message.error(data.message);
			}, error => {
	
			})
		}else{
			this.tableEditConfig.fieldDef.selectedRowKeys.length = 0;
		}

		this.feildDefTableSelectedRows.length = 0;
	}

	@action onGroupSettingChange = (datas, type) => {
		this.tableEditConfig[type === 'group' ? 'groupSetting' : 'childInfoSetting'].datas = datas;
	}

	@action onGroupSettingRowSelect = (sRowKeys, rows, dataIndex, selectedDatas, type) => {
		if (dataIndex == null) {
			this.groupSettingTableSelectedRows = sRowKeys;
		} else {
			if (selectedDatas != null && selectedDatas.hasOwnProperty(dataIndex)) {
				const arr = selectedDatas[dataIndex];
				this.tableEditConfig[type === 'group' ? 'groupSetting' : 'childInfoSetting'].datas.map((data, index) => {
					data[dataIndex] = indexOf(arr, index) >= 0 ? '1' : '0';
				})
			}
		}
	}

	@action onGroupSettingRowSelection = (rowSelection) => {
		let sel = {
			...rowSelection
		}
		sel.getCheckboxProps = (record) => {
			return {
				disabled: record.editable === false // ? true : has(record, 'editable') ? !record.editable : false
			};
		}
		return sel;
	}

	doSaveGroupSetting = () => {
		this.recordOP(this.editTable['groupSetting'], 'valid');
		let groupNameArr = [],
			tabArr = [];
		const invalidEmpty = this.tableEditConfig.groupSetting.datas.some(group => {
			groupNameArr.push(getCurrentLabel(group.groupName));
			tabArr.push({
				id: group.id,
				isShow: group.isShow == null ? '0' : group.isShow,
				groupName: group.groupName
			})
			return group.groupName === '';
		})
		if (invalidEmpty) {
			// message.error(i18n.confirm.groupNameIsEmpty());
			return;
		} else if (uniq(groupNameArr).length === this.tableEditConfig.groupSetting.datas.length) {
			let dataObj = {
				records: tabArr
			}
			let params = {}
			if (this.selectedTreeNodeInfo != null) {
				dataObj.groupType = this.selectedTreeNodeInfo.key;
				params.groupType = this.selectedTreeNodeInfo.key;
			}
			params.data = JSON.stringify(dataObj);
			api.saveGroupInfo(this.moduleName, params).then(data => {
				if (data.status === '1') {
					this.setDialogVisible('groupInfoSetting', false, '');

					if (this.moduleName.indexOf('resource') >= 0)
						this.getTabInfoByTreeNode(false, true);
					else
						this.initData(false, true);
					message.success(i18n.message.saveSuccess());
				} else
					message.error(data.message);
			}, error => {
				message.error(i18n.message.actionError());
			});
		} else {
			message.error(i18n.confirm.groupNameExist());
		}
	}

	@action onGroupSettingDeleteOpr = (ks, ds, type) => {
		let ids = [];
		ds.map(d => {
			if (has(d, 'id'))
				ids.push(d.id)
		});
		let params = {
			id: ids.join(',')
		}
		if (this.selectedTreeNodeInfo != null)
			params.groupType = this.selectedTreeNodeInfo.key;
		if (type === 'group') {
			ids.length > 0 && api.removeGroupInfo(this.moduleName, params).then(data => {
				if (data.status === '1') {
					message.success(i18n.message.deleteSuccess());
					if (this.moduleName.indexOf('resource') >= 0)
						this.getTabInfoByTreeNode(false, true);
					else
						this.initData(false, true);
				} else {
					message.error(data.message);
				}
			})
		} else {}
	}

	//人员卡片字段定义部分
	@observable refreshTree = new Date().getTime();
	@observable treeConfig = {
		data: [],
		selectedKeys: [],
		treeExpandKeys: [],
		onExpand: (keys) => {
			this.treeConfig.treeExpandKeys = keys;
		},
		onSelectedTreeNode: (key, count, countType) => {
			this.treeConfig.selectedKeys = [key];
			this.selectedTreeNodeInfo = countType.node.props.data;
			this.getTabInfoByTreeNode(null, true);
		}
	}
	//人员卡片字段定义-选中树节点的信息
	@observable selectedTreeNodeInfo;

	//计算【工作信息】树节点以及子节点的domid
	@computed get jobTreeNodeDomids() {
		const {
			data
		} = this.treeConfig;
		const domids = ['3'];
		data && data.forEach(obj => {
			const {
				key,
				childs
			} = obj;
			if (key === '3') {
				childs.forEach(child => {
					const {
						domid
					} = child;
					domids.push(domid);
				})
			}
		});
		return domids;
	}

	//当前树节点是否为【工作信息】
	@computed get isJobTreeNode() {
		if (this.selectedTreeNodeInfo) {
			const {
				domid,
			} = this.selectedTreeNodeInfo;

			return this.jobTreeNodeDomids.includes(domid);
		}
	}

	@computed get childInfoOperability() {
		return this.selectedTreeNodeInfo && this.selectedTreeNodeInfo.domid == '-1';
	}

	@action initResourceData = (module) => {
		this.selectedTreeNodeInfo = null;
		this.dropdownSelectedKey = '1';
		this.moduleName = module;
		// let columns = cloneDeep(this.fieldDefColumns())
		// columns.splice(1, 1);
		// columns[1].width = '65%';
		// this.tableEditConfig.fieldDef.columns = this.getColumns();
		this.treeConfig.treeExpandKeys.length = 0;
		api.getTree().then(data => {
			if (data.status === '1') {
				this.containerInitFinished = {
					...this.containerInitFinished,
					init: true
				}

				// this.setTableEditColTitle();
				if (data.treejson.length > 0) {
					this.treeConfig.data = data.treejson;
					this.treeConfig.selectedKeys = [data.treejson[0].key];
					this.selectedTreeNodeInfo = data.treejson[0];
					this.getTabInfoByTreeNode(null, true);
				}
			} else {
				message.error(data.message);
			}
		}, error => {})
	}

	getTree = (callback) => {
		this.treeConfig.data.length = 0;
		this.refreshTree = new Date().getTime();
		api.getTree().then(data => {
			if (data.status === '1') {
				this.treeConfig.data = data.treejson;
				this.treeConfig.data.map(p => {
					if (p.domid === this.treeConfig.selectedKeys[0])
						this.selectedTreeNodeInfo = p;
					p.childs && p.childs.map(c => {
						if (c.domid === this.treeConfig.selectedKeys[0])
							this.selectedTreeNodeInfo = c;
					})
				})
				callback && callback();
			} else {
				message.error(data.message);
			}
			this.refreshTree = new Date().getTime();
		}, error => {})
	}

	setBtn = (t) => {
		if (!this.selectedTreeNodeInfo.hasGroup) {
			t.topButtonDef.splice(1, 3);
		}
		if (this.selectedTreeNodeInfo.addChild) {
			this.tableEditConfig.childInfoSetting.showTitle = true;
			this.tableEditConfig.childInfoSetting.showAdd = true;
			this.tableEditConfig.childInfoSetting.showDelete = true;
			this.selectedTreeNodeInfo.domid != '-1' && t.topButtonDef.push({
				comType: 'button',
				type: 'primary',
				onClickHandle: this.doChildInfoSetting,
				label: i18n.button.childInfoMaintain(),
				icon: this.menuIconCollection.setting,
				checkAction: 'childInfoOperability'
			});
		} else {
			this.tableEditConfig.childInfoSetting.showTitle = false;
			this.tableEditConfig.childInfoSetting.showAdd = false;
			this.tableEditConfig.childInfoSetting.showDelete = false;
			this.selectedTreeNodeInfo.domid != '-1' && t.topButtonDef.push({
				comType: 'button',
				type: 'primary',
				onClickHandle: () => this.createChildInfo(false, {
					name: this.selectedTreeNodeInfo.name,
					multiName: this.selectedTreeNodeInfo.multiName
				}),
				label: i18n.button.editChildInfo(),
				icon: this.menuIconCollection.setting
			}) && t.topButtonDef.push({
				comType: 'button',
				type: 'primary',
				onClickHandle: this.removeChildInfo,
				label: i18n.button.delete(),
				icon: this.menuIconCollection.setting
			});
		}

		if (this.selectedTreeNodeInfo.domid === '-1' || this.selectedTreeNodeInfo.addChild) {
			this.tableEditConfig.fieldDef.columns[2].com[0].options = remove(this.tableEditConfig.fieldDef.columns[1].com[0].options, (v) => v != 'upload');
		} else {
			this.tableEditConfig.fieldDef.columns[2].com[0].options.push('upload');
		}
	}

	addEmptyTab = (groupid) => {
		let tabArr = [];
		let t = cloneDeep(this.tabDef);
		this.setBtn(t);
		tabArr.push({
			...t,
			groupid,
			viewCondition: '1'
		});
		this.tabConfig.tabs = [...tabArr];
	}

	@action getTabInfoByTreeNode = (create = false, init = false, isLeaf) => {
		api.getTabInfo(this.moduleName, {
			groupType: this.treeConfig.selectedKeys[0]
		}).then(data => {
			if (data.status === '1') {
				this._groupInfoOperability = data.tabs.length === 0;
				let tabArr = [];
				this.tabRecord = data.tabs;
				data.tabs && data.tabs.map((tabInfo, index) => {
					let t = cloneDeep(this.tabDef);
					this.setBtn(t);
					tabArr.push({
						...t,
						...tabInfo,
						viewCondition: `${tabArr.length + 1}`
					});
				});
				this.tabConfig.tabs = [...tabArr];
				if (tabArr.length > 0) {
					this.setActiveTab(this.tabConfig, init ? '1' : !create ? this.tabConfig.activeTabKey : `${tabArr.length}`);
				} else {
					this.addEmptyTab(this.treeConfig.selectedKeys[0]);
					this.setActiveTab(this.tabConfig, '1');
					this.refreshMainTabComponent = new Date().getTime();
				}
			} else {
				message.error(data.message);
			}
		})
	}

	isCreateChildInfo = false;
	@action createChildInfo = (create = true, data = {}) => {
		this.isCreateChildInfo = create;
		this.editChildInfoFormFields.map(f => {
			if (typeof(f.title) == 'function')
				f.title = f.title();
			f.items.map(item => {
				if (typeof(item.label) == 'function')
					item.label = item.label();
				if (item.conditionType === 'INPUT')
					item.otherParams = {...window.inputType};
			})
		})
		let fields = [...this.editChildInfoFormFields],
			dialogTitle = create ? i18n.button.createChildInfo() : i18n.button.editChildInfo();
		if (create) {
			this.dialogParams.createChildInfo.height = 110;
		} else {
			fields[0].items.splice(1, 1);
			this.dialogParams.createChildInfo.height = 70;
		}
		this.setFormData('childInfoForm', fields);
		if (!create) {
			this.formTarget.childInfoForm.updateFields({
				name: {
					value: data.multiName || data.name || ''
				},
				infoOrder: {
					value: data.infoOrder
				}
			})
		}
		this.setDialogVisible('createChildInfo', true, dialogTitle);
	}

	@action doSaveChildInfo = () => {
		this.formTarget.childInfoForm.validateForm().then(f => {
			if (f.isValid) {
				let record = {
					...this.formTarget.childInfoForm.getFormParams(),
					isShow: 1
				}
				let cloneTree = cloneDeep(this.toJS(this.treeConfig.data));

	
				let parentId;
				let nameArr = [];
				if (this.isCreateChildInfo) {
					this.selectedTreeNodeInfo.childs.map(c => {
						nameArr.push(getCurrentLabel(c.name));
					})
					nameArr.push(getCurrentLabel(record.name));
					if (uniq(nameArr).length != nameArr.length) {
						f.showError('name', i18n.confirm.childInfoNameExist());
						this.showError = new Date().getTime();
						return;
					}
					const i = findIndex(cloneTree, {
						key: this.selectedTreeNodeInfo.key
					});
					cloneTree[i].childs.push(record)
					parentId = this.selectedTreeNodeInfo.domid;
				} else {
					let checked = true;
					cloneTree.map(p => {
						p.childs && p.childs.map(c => {
							if (c.domid === this.selectedTreeNodeInfo.domid) {
								p.childs.map(child => {
									if (child.domid != c.domid)
										nameArr.push(getCurrentLabel(child.name));
									else
										nameArr.push(getCurrentLabel(record.name));
								})

								if (uniq(nameArr).length != nameArr.length) {
									f.showError('name', i18n.confirm.childInfoNameExist());
									this.showError = new Date().getTime();
									checked = false;
									return;
								} else {
									Object.assign(c, {
										name: record.name
									});
									parentId = p.domid;
								}
							}else{
								Object.assign(c, {
									name: c.multiName||c.name
								});
							}
						})
					})
					if (!checked)
						return;
				}
				const params = {
					data: JSON.stringify({
						records: this.convertAttr(cloneTree)
					}),
					parentId
				}
				api.saveTree(params).then(data => {
					if (data.status === '1') {
						this.setDialogVisible('createChildInfo', false, '');
						this.getTree();
						message.success(i18n.message.saveSuccess());
					} else
						message.error(data.message);
				}, error => {
					message.error(i18n.message.actionError());
				});
				// }
			} else {
				f.showErrors();
				this.showError = new Date().getTime();
			}
		});
	}

	@action doChildInfoSetting = () => {
		this.tableEditConfig.childInfoSetting.datas.length = 0;
		let arr = [];
		if (!this.selectedTreeNodeInfo.addChild) {
			arr.push({
				"record": {
					"id": this.selectedTreeNodeInfo.key,
					"viewAttr": this.selectedTreeNodeInfo.viewAttr,
					"isShow": this.selectedTreeNodeInfo.isShow,
					"name": this.selectedTreeNodeInfo.multiName || this.selectedTreeNodeInfo.name || ''
				},
				"props": {
					"checkProps": {
						"isShow": {
							"viewAttr": this.selectedTreeNodeInfo.viewAttr
						}
					}
				}
			})
		} else {
			this.selectedTreeNodeInfo.childs.map(child => {
				let viewAttr = child.viewAttr;
				if (viewAttr != 1 && has(child, 'editable')) {
					viewAttr = !child.editable ? 1 : 2;
				}
				arr.push({
					"record": {
						"id": child.key,
						"viewAttr": child.viewAttr,
						"isShow": child.isShow,
						"name": child.multiName || child.name || ''
					},
					"props": {
						"checkProps": {
							"isShow": {
								viewAttr
							}
						}
					}
				})
			})
		}

		Object.assign(this.tableEditConfig.childInfoSetting, { ...this.convertData(arr, 'childInfoSetting')
		});
		this.tableEditConfig.childInfoSetting.columns = this.childInfoDefColumns();
		this.tableEditConfig.childInfoSetting.datas.map(d => {
			Object.assign(d, {
				com: {
					name: [{
						label: '',
						type: 'INPUT',
						key: 'name',
						viewAttr: d.viewAttr,
						otherParams: {
							...window.inputType
						}
					}]
				}
			})
		})
		this.setDialogVisible('childInfoSetting', true, i18n.button.childInfoMaintain());
	}

	convertAttr = (cloneTree) => {
		let arr = [];
		cloneTree.map(root => {
			let parent = {
				id: root.key,
				infoOrder: root.infoOrder,
				name: root.name,
				isShow: root.isShow
			}
			if (root.childs) {
				parent.childs = [];
				root.childs.map(c => {
					parent.childs.push({
						id: c.key || c.id,
						name: c.name,
						isShow: c.isShow,
						infoOrder: c.infoOrder
					})
				})
			}
			arr.push(parent);
		})
		return arr;
	}

	removeChildInfo = () => {
		this.confirmInfo({
			content: i18n.confirm.deleteSelected(),
			onOk: () => {
				let parentId;
				let cloneTree = cloneDeep(this.toJS(this.treeConfig.data));
				cloneTree.map(p => {
					p.childs && p.childs.map((c, i) => {
						if (c.domid === this.selectedTreeNodeInfo.domid) {
							parentId = p.domid;
							p.childs.splice(i, 1);
						}
					})
				})
				const params = {
					data: JSON.stringify({
						records: this.convertAttr(cloneTree)
					}),
					parentId
				}
				api.saveTree(params).then(data => {
					if (data.status === '1') {
						message.success(i18n.message.deleteSuccess());
						this.getTree(() => {
							this.treeConfig.selectedKeys = ['-1'];
							this.selectedTreeNodeInfo = this.treeConfig.data[0];
							this.getTabInfoByTreeNode(null, true);
						});
						// this.treeConfig.selectedKeys = [this.treeConfig.data[0].key];
						// this.selectedTreeNodeInfo = this.treeConfig.data[0];
						// this.getTabInfoByTreeNode(null, true);
					} else
						message.error(data.message);
				}, error => {
					message.error(i18n.message.actionError());
				});
			}
		});
	}

	doSaveChildInfoSetting = () => {
		this.recordOP(this.editTable['childInfoSetting'], 'valid');
		let infoNameArr = [],
			infoArr = [];
		const invalidEmpty = this.tableEditConfig.childInfoSetting.datas.some(group => {
			infoNameArr.push(getCurrentLabel(group.name));
			infoArr.push({
				id: group.id,
				isShow: group.isShow == null ? '0' : group.isShow,
				name: group.name
			})
			return group.name === '';
		})
		if (invalidEmpty) {
			return;
		} else if (uniq(infoNameArr).length === this.tableEditConfig.childInfoSetting.datas.length) {
			let parentId;
			let cloneTree = cloneDeep(this.toJS(this.treeConfig.data));
			if (!this.selectedTreeNodeInfo.addChild) {
				cloneTree.map(p => {
					p.childs && p.childs.map(c => {
						if (c.domid === infoArr[0].id) {
							Object.assign(c, infoArr[0]);
							parentId = p.domid;
						}
					})
				})
			} else {
				parentId = this.selectedTreeNodeInfo.key;
				const i = findIndex(cloneTree, {
					key: this.selectedTreeNodeInfo.key
				});
				cloneTree[i].childs = [];
				infoArr.map(info => {
					cloneTree[i].childs.push({ ...info
					})
				})
			}

			const params = {
				data: JSON.stringify({
					records: this.convertAttr(cloneTree)
				}),
				parentId
			}
			api.saveTree(params).then(data => {
				if (data.status === '1') {
					this.setDialogVisible('childInfoSetting', false, '');
					this.getTree();
					this.getTabInfoByTreeNode(null, true);
					message.success(i18n.message.saveSuccess());
				} else
					message.error(data.message);
			}, error => {
				message.error(i18n.message.actionError());
			});
		} else {
			message.error(i18n.confirm.groupNameExist());
		}
	}
	//移动到组
	@action dropdownClick = (e) => {
		switch(e.key){
			case 'createAndMove':
				this.editGroup(null, true);
				break;
			default:
				const groupid = e.key;
				const tabInfo = this.tabConfig.tabs[findIndex(this.tabConfig.tabs, {groupid})];
				let moveFieldConfirm = i18n.confirm.moveFieldConfirm().replace('{params}', tabInfo.title);
				this.changeGroup(moveFieldConfirm, groupid);
		}
	}

	@action changeGroup = (moveFieldConfirm, groupid) => {
		const params = {};
		let ids = [];
		let names = [];
		this.tableEditConfig.fieldDef.selectedRowKeys.map(idx => {
			try{
				ids.push(this.tableEditConfig.fieldDef.datas[idx].id);
				names.push(this.tableEditConfig.fieldDef.datas[idx].fieldname);
			}catch(e){

			}
		});
		if(this.moduleName.indexOf('resource') > -1){
			Object.assign(params, {
				fieldids: ids.join(','),
				fieldnames: names.join(','),
				groupid,
				scopeid: this.selectedTreeNodeInfo.domid
			})
		}else{
			Object.assign(params, {
				ids: ids.join(','), 
				groupid
			});
		}
		moveFieldConfirm == null ? 
		this.doChangeGroup(params) : 
		this.confirmInfo({
			content:moveFieldConfirm,
			onOk: () => {
				this.doChangeGroup(params)
			}
		});
	}

	@action doChangeGroup = (params) => {
		api.changeGroup(this.moduleName, params).then(data => {
			if (data.status === '1') {
				message.success(i18n.message.moveSuccess());
				if (this.moduleName.indexOf('resource') >= 0)
					this.getTabInfoByTreeNode();
				else
					this.initData();
			} else
				message.error(data.message);
		}, error => {message.error(i18n.message.actionError());});
	}

	@observable encryptDialogVisible = false;
	@observable encryptDialogTitle = "";
	get encryptDialogButtons(){
        const buttonDef = [
            {
                content: getLabel(30986, '保存'),
                icon: 'icon-coms-Preservation',
                onClickHandle: this.saveEncryptFieldSettingForm
            }
        ]
        const buttons = [], moreBtnData = [];
        buttonDef.map((btn, index) => {
            const {content, icon, onClickHandle} = btn;
            buttons.push(
                (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@jyb1jz@${index}`} type='primary' onClick={onClickHandle}>{content}</Button>)
            );

            moreBtnData.push({
                key: index.toString(),
                content,
                icon: <i className={icon} />,
                onClick: onClickHandle
            });
		})
		const {scopeId} = this.opParams;
		let arr = [];
		if(scopeId == '-1'){
            arr = this.generateLogMenu('38', 'HRM_RSOURCE_RESOURCEBASE', this.encryptParams.encryptId);
        }else if(scopeId == '1'){
            arr = this.generateLogMenu('38', 'HRM_RSOURCE_RESOURCEPERSONAL', this.encryptParams.encryptId);
        }else if(scopeId == '3'){
            arr = this.generateLogMenu('38', 'HRM_RSOURCE_RESOURCEWORK', this.encryptParams.encryptId);
        }else if(scopeId == 'subcompany'){
            arr = this.generateLogMenu('38', 'HRM_RSOURCE_SUBCOMPANY', this.encryptParams.encryptId);
        }else if(scopeId == 'department'){
            arr = this.generateLogMenu('38', 'HRM_RSOURCE_DEPARTEMENT', this.encryptParams.encryptId);
        }else if(scopeId == 'salary'){
            arr = this.generateLogMenu('38', 'HRM_RSOURCE_SALARY');
		}else{}
		moreBtnData.push(...arr);
        return {buttons, moreBtn: {datas: moreBtnData}};
	}
	
	@computed get encryptDialogProps(){
		return {
			title: this.encryptDialogTitle,
            style: {
                width: 600,
                height: 350
            },
			...ecCom.WeaTools.getIconBGC('currency'),
			...this.encryptDialogButtons,
			visible: this.encryptDialogVisible,
			onCancel: this.onEncryptDialogClose
		}
	}

	@computed get encryptFormItemRender(){
		return {
			desensitization: (field, textAreaProps, form, formParams) => {
				return (
					<WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@v2n5at`} fieldConfig={{...field, textAreaProps}} form={form} formParams={formParams} onChange={this.onDesensitizationChangeHandle}/>
				)
			},
			secondauth: (field, textAreaProps, form, formParams) => {
				return (
					<WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@rdlc6m`} fieldConfig={{...field, textAreaProps, disabled: formParams.desensitization != '1'}} form={form} formParams={formParams} />
				)
			},
			viewscope: (field, textAreaProps, form, formParams) => {
				if(formParams.desensitization == '1')
					return (
						<div>
							<div style={{width: '70%', float: 'left'}}>
								<WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@0wzv1t`} fieldConfig={{...field, textAreaProps}} form={form} formParams={formParams} />
							</div>
							{
								formParams.viewscope == '1' &&
								<span style={{color: '#00A9FF', cursor: 'pointer', paddingLeft: '8px', lineHeight: '30px'}} onClick={this.showSettingDialog}>{getLabel(30747, '设置')}</span>
							}
						</div>
					)
				return null;
			},
		}
	}

	@action onDesensitizationChangeHandle = data => {
		const desensitization = data.desensitization.value;
		desensitization == '0' && this.formTarget.encryptForm.updateFields({
			secondauth: {
				value: '0'
			}
		})
	}

	@action onEncryptDialogClose = () => this.encryptDialogVisible = false;

	encryptParams = {};
	@action onEncryptHandle = async record => {
		const {fieldname, tablename, fieldlabel, encryptId} = record;
		this.encryptParams = {fieldname, tablename, encryptId};
		const label = getCurrentLabel(fieldlabel);
		const data = await api.getEncryptFieldSettingForm({...this.encryptParams, ...this.opParams});
		if(data.status == '1'){
			this.setFormData('encryptForm', data.conditions);
			if(this.formTarget.encryptForm.isFormInit){
				this.encryptDialogTitle = `${getLabel('526997','加密设置')}(${getLabel('261','字段')}:${label})`;
				this.encryptDialogVisible = true;
			}
		}else{
			message.error(data.message);
		}
	}

	@observable needInitData = '1';
	get encrypt(){
		const {isencrypt} = this.formTarget.encryptForm.getFormParams();
		const fields = this.formTarget.encryptFormFields;
		const col = find(fields[0].items, {domkey: ['isencrypt']});
		const {otherParams} = col || {};
		const {disabled} = otherParams || {};
		return isencrypt == '1' && !disabled;
	}
	@action saveEncryptFieldSettingForm = async () => {
		const f = await this.formTarget.encryptForm.validateForm();
		if (f.isValid) {
			if(this.encrypt){
				this.confirmInfo({
					width: 500,
					content: (
						<div>
							<div>1.{getLabel('524355','提示: 字段一旦加密后无法取消，同时加密后的字段不支持查询，请谨慎操作！')}</div><br />
							<div>
								<span>2.{getLabel('531157','历史数据量可能较大， 此操作可能需要较长时间，对系统性能也可能会造成一定影响，请确认是否处理历史数据：')}</span>
								<span>
									<WeaSelect style={{display: 'inline'}} ecId='bs_hrm_fielddefine_confirm_select'
										options={[
											{
												key: '1',
												selected: false,
												showname: getLabel('553','处理')
											},{
												key: '0',
												selected: false,
												showname: getLabel('529752','不处理')
											},
										]}
										detailtype={3}
										value={this.needInitData}
										supportCancel
										onChange={(v,showname)=>{
											this.needInitData = v;
										}}
									/>
								</span>
							</div>
						</div>
					),
					onOk: this.doSaveEncryptFieldSettingForm
				})
			}else{
				this.needInitData = '0';
				this.doSaveEncryptFieldSettingForm();
			}
		} else {
			f.showErrors();
			this.showError = new Date().getTime();
		}
	}

	@action doSaveEncryptFieldSettingForm = async () => {
		if(this.spinning)
			return;
		this.spinning = true;
		const params = {...this.formTarget.encryptForm.getFormParams(), ...this.encryptParams, needInitData: this.needInitData, ...this.opParams}
		if (this.selectedTreeNodeInfo != null) {
			Object.assign(params, {
				scopeid: this.selectedTreeNodeInfo.key
			})
		}
		try{
			const data = await api.saveEncryptFieldSettingForm(params);
			if(data.status == '1'){
				this.encryptDialogVisible = false;
				message.success(i18n.message.saveSuccess());
				if (this.moduleName.indexOf('resource') >= 0)
					this.getTabInfoByTreeNode();
				else
					this.initData();
			}else{
				message.error(data.message);
			}
			this.spinning = false;
		}catch(e){
			this.spinning = false;
		}
	}

	//#region 查看范围设置
    target = {};
    @observable dialogVisible = false;
    @observable table = new TableStore();
    @observable canAdd = false;
    @observable canDel = false;

    @computed get tableMultiDelete() {
        return this.table.selectedRowKeys.length === 0 || !this.canDel;
    }

    @computed get rangeViewTabProps(){
        return {
            datas: [],
            buttons: [
                <WeaButtonIcon ecId={`${this && this.props && this.props.ecId || ''}_WeaButtonIcon@yj28no@${'add'}`} buttonType='add' type='primary' onClick={this.getViewRangeForm} disabled={!this.canAdd} />,
                <WeaButtonIcon ecId={`${this && this.props && this.props.ecId || ''}_WeaButtonIcon@ru7ee8@${'del'}`} buttonType='del' type='primary' onClick={this.doMultiDel} disabled={this.tableMultiDelete} />,
            ]
        }
    }

    @action onDialogCancleHandle = () => this.dialogVisible = false;

    get dialogButtons(){
        const buttonDef = [
            {
                content: getLabel(30986, '保存'),
                icon: 'icon-coms-Preservation',
                onClickHandle: this.saveViewRange
            }
        ]
        const buttons = [], moreBtnData = [];
        buttonDef.map((btn, index) => {
            const {content, icon, onClickHandle} = btn;
            buttons.push(
                (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@lq21or@${index}`} type='primary' onClick={onClickHandle}>{content}</Button>)
            );

            moreBtnData.push({
                key: index.toString(),
                content,
                icon: <i className={icon} />,
                onClick: onClickHandle
            });
		})
		
		const {scopeId} = this.opParams;
		let arr = [];
		if(scopeId == '-1'){
            arr = this.generateLogMenu('38', 'HRM_RSOURCE_RESOURCEBASE', this.encryptParams.encryptId);
        }else if(scopeId == '1'){
            arr = this.generateLogMenu('38', 'HRM_RSOURCE_RESOURCEPERSONAL', this.encryptParams.encryptId);
        }else if(scopeId == '3'){
            arr = this.generateLogMenu('38', 'HRM_RSOURCE_RESOURCEWORK', this.encryptParams.encryptId);
        }else if(scopeId == 'subcompany'){
            arr = this.generateLogMenu('38', 'HRM_RSOURCE_SUBCOMPANY', this.encryptParams.encryptId);
        }else if(scopeId == 'department'){
            arr = this.generateLogMenu('38', 'HRM_RSOURCE_DEPARTEMENT', this.encryptParams.encryptId);
        }else if(scopeId == 'salary'){
            arr = this.generateLogMenu('38', 'HRM_RSOURCE_SALARY');
		}else{}
		moreBtnData.push(...arr);
        return {buttons, moreBtn: {datas: moreBtnData}};
    }

    @computed get dialogProps(){
        return {
            title: getLabel('125012','查看范围设置'),
            style: {
                width: 800,
                height: 600
            },
            ...ecCom.WeaTools.getIconBGC('currency'),
            ...this.dialogButtons,
            visible: this.dialogVisible,
            onCancel: this.onDialogCancleHandle,
        }
    }

    @computed get rangeViewTableProps(){
        return {
            comsWeaTableStore: this.table,
            hasOrder: true,
            needScroll: true,
            scroll: {
				y: 550
            },
            onOperatesClick: this.onOperatesClickHandle
        }
    }

    @action showSettingDialog = async () => {
		if(this.encryptParams.encryptId == null || this.encryptParams.encryptId == ''){
            this.confirmInfo({
                content: getLabel('524355','提示: 字段一旦加密后无法取消，同时加密后的字段不支持查询，请谨慎操作！'),
                onOk: async () => {
                    const rs = await api.saveEncryptFieldSettingForm({...this.formTarget.encryptForm.getFormParams(), ...this.encryptParams, ...this.opParams});
                    if(rs.status == '1'){
                        this.encryptParams.encryptId = rs.encryptId;
                        if (this.moduleName.indexOf('resource') >= 0)
							this.getTabInfoByTreeNode();
						else
							this.initData();
                        this.dialogVisible = this.getEncryptFieldScopeList();
                    }else{
                        message.error(data.message);
                    }
                }
            });
        }else
            this.dialogVisible = this.getEncryptFieldScopeList();
    }

    @action getEncryptFieldScopeList = async () => {
        const d = await api.getEncryptFieldScopeList({id: this.encryptParams.encryptId});
        if(d.status == '1'){
            const {canAdd, canDel, sessionkey} = d;
            this.canAdd = canAdd;
            this.canDel = canDel;
            this.table = new TableStore();
            this.table.getDatas(sessionkey);
            return true;
        }else{
            message.error(d.message);
            return false;
        }
    }

    @action onOperatesClickHandle = (record, index, operate) => {
        const func = operate.href ? operate.href.split(':')[1].split('(')[0] : '';
        const id = record.id || '';
		this[func] && this[func](id, record);
    }

    @action doMultiDel = () => this.doDel();

    @action doDel = ids => {
        const params = {
            fieldid: this.encryptParams.encryptId,
            ids: ids || this.table.selectedRowKeys
        };
        let content = isEmpty(ids) ? getLabel(385625, '确定要删除选择的记录吗？') : getLabel(83877, '确定要删除吗？');
        this.confirmInfo({
            content,
            onOk: async () => {
                const data = await api.delEncryptFieldScopeSetting({...params, ...this.opParams});
                if (data.status === "1") {
                    message.success(getLabel(83472, '删除成功！'));
                    this.table.getDatas(null, 1);
                }else{
                    message.error(data.message);
                }
            }
        });
    }

    @action saveViewRange = async () => {
        this.onDialogCancleHandle();
    }
	//#endregion
	
	//#region 范围form
    @observable conditions = [];

    @observable viewRangeAuthVisible = false;

    @computed get viewRangeAuthProps(){
        return {
            title: getLabel('383694','添加人员'),
            conditions: this.toJS(this.conditions),
            ...ecCom.WeaTools.getIconBGC('currency'),
            visible: this.viewRangeAuthVisible,
            onOk: this.onOKHandle,
            onCancel: this.onViewRangeAuthCancleHandle,
        }
    }

    @action getViewRangeForm = async () => {
        const data = await api.getEncryptFieldScopeForm();
        if(data.status == "1"){
            this.conditions = data.conditions;
            this.viewRangeAuthVisible = true;
        }
    }

    @action onOKHandle = async data => {
        const d = await api.saveEncryptFieldScopeSetting({id: this.encryptParams.encryptId, ...data, ...this.opParams});
        if(d.status == '1'){
            message.success(getLabel(83551, '保存成功！'));
            this.getEncryptFieldScopeList();
        }else{
            message.error(d.message);
        }
        this.viewRangeAuthVisible = false;
    }

    @action onViewRangeAuthCancleHandle = () => {
        this.viewRangeAuthVisible = !this.viewRangeAuthVisible;
	}
	
	get opParams(){
		const obj = {
			fieldname: this.encryptParams.fieldname
		}
		const name = (this.moduleName || '').toLocaleLowerCase();
		if(name.indexOf('subcompany') > -1){
			Object.assign(obj, {
				scopeId: 'subcompany'
			});
		}else if(name.indexOf('department') > -1){
			Object.assign(obj, {
				scopeId: 'department'
			});
		}
		this.selectedTreeNodeInfo != null && Object.assign(obj, {
			scopeId: this.selectedTreeNodeInfo.key
		});

		return obj;
	}
	//#endregion
	/********************* action list *********************/
}