import {
	observable,
	action,
	computed
} from 'mobx';
import {
	WeaHelpfulTip,
	WeaNewScroll,
	WeaTools,
	WeaButtonIcon,
	WeaFormItem,
	WeaBrowser,
	WeaError,
	WeaLocaleProvider
} from 'ecCom';
import {
	WeaTableNew,
	WeaSwitch
} from 'comsMobx';
import {
	Button,
	message
} from 'antd';
import HrmBaseStore from "../../hrmComsPublic/stores/baseStore";
import * as api from '../apis/workflow';
import * as shiftapi from "../apis/shiftManager";
import {
	i18n
} from '../public/i18n';
import {
	indexOf,
	cloneDeep,
	findIndex,
	has
} from 'lodash';
// import {FormInfo} from 'weaHrmComsPublic';
import {FormInfo} from '../../hrmComsPublic/index';
import {addContentPath} from '../util/index.js'
const getLabel = WeaLocaleProvider.getLabel;
const {
	TableStore
} = WeaTableNew;

class HrmWorkflowSetting extends HrmBaseStore {
	constructor() {
		super();
	}
	/********************* unobservable list *********************/
	moduleName;
	descObj = {};
	tips = {};

	orgTreeProps = {
		needSearch: true,
		topPrefix: 'hrmSearch',
		inputLeftDom: `<b>${i18n.label.organization()}</b>`,
		treeNodeClick: this.treeNodeClick,
		params: {
			rightStr: 'StateChangeProcess:Set'
		}
	}

	attendanceOrgTreeProps = {
		...this.orgTreeProps,
		params: {
			rightStr: 'HrmAttendanceProcess:setting'
		}
	}

	tabConfig = {
		tabs: [{
			color: '#000000',
			groupId: 'roleList',
			title: '',
			viewCondition: '1',
			searchType: ['base', 'advanced'],
			searchKey: 'field001',
			doSearch: (params) => this.getTableData(params)
		}],
		keyParam: 'viewCondition',
		activeTabKey: '1'
	}

	editTabConfig = {
		tabs: [{
			color: '#000000',
			groupId: 'info',
			title: '流程概览',
			viewCondition: '1',
		}, {
			color: '#000000',
			groupId: 'field',
			title: '字段对应',
			viewCondition: '2',
		}, {
			color: '#000000',
			groupId: 'actionSetting',
			title: '动作设置',
			viewCondition: '3',
		}],
		keyParam: 'viewCondition',
		activeTabKey: '1'
	}

	get generateFormFields(){
		return [{
			"title": i18n.label.basicSetting(),
			"items": [{
				"colSpan": 2,
				"conditionType": "INPUT",
				"domkey": ["formName"],
				"fieldcol": 12,
				"isQuickSearch": false,
				"label": i18n.label['15451'](),
				"labelcol": 6,
				"precision": 0,
				"rules": "required|string",
				"value": "",
				"viewAttr": 3
			}],
			"defaultshow": true
		}]
	}

	wfFormItemRender = {
		field001: (field, textAreaProps, form, formParams) => {
			return (
				<div className='browser'>
					<WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@c86d2n`} fieldConfig={{...field, ...textAreaProps, addOnClick:(values)=> this.callAddPath(values)}} 
					form={form} formParams={formParams} onChange={this.onWfChange} />
				</div>
			)
		},
		field002: (field, textAreaProps, form, formParams) => {
			return (
				<div>
					<div className='browser'>
						<WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@pyu3m8`} fieldConfig={{...field, ...textAreaProps, helpfulTip: '', addOnClick:(values)=> this.callAddForm(values)}} 
						form={form} formParams={formParams} onChange={this.onWfChange1}/>
					</div>
					<a className='autoGen' onClick={this.createForm}>{i18n.label['83444']()}</a>
					<span className='tips'><WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@yn5em3`} title={field.helpfulTip} /></span>
				</div>
			)
		},
		field004: (field, textAreaProps, form, formParams) => {
			return (
				<div className='browser'><WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@zqiqoj`} fieldConfig={{...field, ...textAreaProps}} form={form} formParams={formParams}/></div>
			)
		},
		field006: (field, textAreaProps, form, formParams) => {
			const fv = formParams.field006;
			const {field006: desc} = this.descObj;
			const {field006: tip} = this.tips;
			const helpfulTip = (tip || {})[fv] || '';
			return (
				<div className='browser'>
					<WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@fy3822`} fieldConfig={{...field, ...textAreaProps, helpfulTip}} form={form} formParams={formParams} onChange={v => this.onField006Change(v)}/>
					{
						desc && <div style={{height: 30, lineHeight: '30px', paddingTop: '10px', color: '#999'}}>{desc[fv]}</div>
					}
				</div>
			)
		},
		usedetail: (field, textAreaProps, form, formParams) => {
			if(['5', '6', '7', '8'].indexOf(formParams.field006) > -1)
				return null;
			return (
				<div className='browser'><WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@el2bom`} fieldConfig={{...field, ...textAreaProps}} form={form} formParams={formParams} onChange={v => this.onField006Change(v)}/></div>
			)
		},
		flow_deduct_card: (field, textAreaProps, form, formParams) => {
			if(['0', '1', '2'].indexOf(formParams.field006) > -1){
				return (
					<div className='browser'><WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@tuuzpf`} fieldConfig={{...field, ...textAreaProps}} form={form} formParams={formParams} /></div>
				)
			}else{
				return null;
			}
			
		}
	}

	editorDialogRightMenu = [];
	@computed get getDialogOpButtons(){
		let buttons = [];
		this.editorDialogRightMenu.length = 0;
		if(this.canAdd){
			switch (this.dialogParams.opType) {
				case '':
					buttons.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@fbuwn3`} type="primary" op="save" onClick={() => this.saveWf()}>{i18n.label.save()}</Button>);
					buttons.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@hmqcyj`} type="primary" op="entry" onClick={() => this.saveWf(true)}>{i18n.label.saveAndSetting()}</Button>);
					break;
				case 'showContent':
					buttons.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@unklha`} type="primary" op="save" onClick={() => this.save()}>{i18n.label.save()}</Button>);
					break;
			}
		}

		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;
	}

	autoGenDialogRightMenu = [];
	getAutoGenDialogOpButtons = () => {
		let buttons = [];
		this.autoGenDialogRightMenu.length = 0;
		buttons.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@jtmprl`} type="primary" op="save" onClick={() => this.dispatchAutoGenForm()}>{i18n.label.save()}</Button>);

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

		this.generateFormDialogParams.moreBtn.datas = this.autoGenDialogRightMenu;
		return buttons;
	}

	wfFormFields;
	selectedSubCompany;
	tableEditDatas;

	needRender = ['fakeInp', 'field005', 'field006'];
	renderCol = {}
	browsers = [];
	/********************* unobservable list *********************/

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

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

	/********************* observable list *********************/
	@observable table = new TableStore();
	@observable checkRuleTable = new TableStore();
	@observable spinning = false;
	@observable canAdd = false;
  	@observable canCreate = false;
	@observable canDel = false;
	
	@computed get topBtnAndMenu(){
		let buttons = [];
		this.canCreate && buttons.push((
			<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@qxdzrk`} type="primary" op="create" onClick={this.create}>
			{i18n.label.create()}
			</Button>
		));
		this.canDel && buttons.push((
			<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@ub6d6k`}
			type="primary"
			op="remove"
			disabled={this.multiRemoveable}
			onClick={() => this.removeWF()}
			>
			{i18n.label.multiRemove()}
			</Button>
		));

		let menus = this.convertToMenus(buttons);
		const obj = {
			buttons,
			menus: [
			...menus,
			...this.getBasicMenus("HRM_KQ_WORKFLOW")
			]
		};
		return obj;
	}

	dialogParams = {
		...this.dialogPropsDef,
		opType: '',
		onCancel: () => {
			this.dialogParams.opType = '';
			this.dialogParams.visible = false;
			this.opId = null;
		}
	}

	@observable generateFormDialogParams = {
		...this.dialogPropsDef,
		onCancel: () => {
			this.generateFormDialogParams.visible = false;
		}
	}

	@observable tableConfig = {
		...this.editTableConfig,
		showTitle: false,
		draggable: false,
		showAdd: false,
		showDelete: false,
		showCopy: false,
		columns: [],
		datas: [],
		selectedData: {},
		getRowSelection: (rowSelection) => {
			return null;
		},
		onChange: (data) => {
			this.tableEditDatas = data;
			this.tableConfig.datas = this.convertData(data, true);
		}
	}

	@observable refreshMainTab = new Date().getTime();
	@observable refreshTab = new Date().getTime();
	/********************* observable list *********************/

	/********************* computed list *********************/
	@computed get multiRemoveable() {
		return this.table.selectedRowKeys.length === 0;
	}
	/********************* computed list *********************/

	/********************* action list *********************/
	clearParams = () => {
		this.selectedSubCompany = null;
		this.opId = null;
	}

	initData = (moduleName) => {
		this.clearParams();
		this.moduleName = moduleName;
		this.containerInitFinished = {
			...this.containerInitFinished,
			init: true
		}
		api.initModuleData(moduleName).then(rs => {
			rs.map((result, index) => {
				if (result.status === '1') {
					switch (index) {
						case 0:
							this.wfFormFields = result.condition;
							this.descObj = result.desc;
							this.tips = result.tips;
							this.setFormData('wfForm', result.condition);
							break;
						case 1:
							this.setFormData('conditionForm', result.conditions);
							if (this.formTarget.conditionForm.isFormInit) {
								this.refreshMainTab = new Date().getTime();
								this.getTableData();
							}
							break;
					}
				}
			})
		})
	}

	@action treeNodeClick = (event, ids, nodeids, nodes) => {
		this.formTarget.conditionForm.resetForm();
		const {
			data: nodeData
		} = event.node.props;
		this.selectedSubCompany = nodeData;
		this.formTarget.conditionForm.updateFields({
			subcompanyid: {
				value: nodeData.id.toString(),
				valueSpan: nodeData.name,
				valueObj: [{
					id: nodeData.id.toString(),
					name: nodeData.name
				}]
			}
		})
		this.getTableData();
	}

	getTableData = (params) => {
		this.table = new TableStore();
		if (params == null)
			params = { ...this.formTarget.conditionForm.getFormParams()
			};
		// this.selectedSubCompany != null && Object.assign(params, {
		// 	subcompanyid: this.selectedSubCompany.id,
		// })
		api.getWorkflowList(this.moduleName, params).then(data => {
			if (data.status === '1'){
				this.canCreate = data.canAdd;
				this.canDel = data.canDel;
				this.table.getDatas(data.sessionkey, 1);
			}else
				message.error(data.message)
		}, error => {})
	}

	getFormData = async (params) => {
		const data = await api.getFormInfo(this.moduleName, params);
		if (data.status === '1') {
			this.canAdd = data.canAdd;
			this.setFormData('wfForm', data.condition);
			this.refreshTab = new Date().getTime();
			this.dialogParams.visible = true;
		} else
			message.error(data.message);
	}

	checkRight = async (params) => {
		const data = await api.getFormInfo(this.moduleName, params);
		if (data.status === '1') {
			this.canAdd = data.canAdd;
		} else
			message.error(data.message);
	}

	@action create = async () => {
		// this.getFormData();
		const f = cloneDeep(this.wfFormFields);
		this.checkRight();
		this.selectedSubCompany != null && f.map(g => {
			g.items.map(item => {
				if (item.domkey[0] === 'field004') {
					item.browserConditionParam.replaceDatas = [{
						id: this.selectedSubCompany.id,
						name: this.selectedSubCompany.name
					}]
				}
			})
		})
		this.setFormData('wfForm', f);
		if (this.formTarget.wfForm.isFormInit) {
			this.dialogParams.title = this.moduleName === 'statechange' ? i18n.label['384621']() : i18n.label['385037']();
			this.dialogParams.style = {
				width: 600,
				height: 520
			}
			this.dialogParams.coms = (
				<WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@mz5bto`} height={'100%'}>
					<FormInfo ecId={`${this && this.props && this.props.ecId || ''}_FormInfo@3p9vap`} menu={this.editorDialogRightMenu} 
							form={this.formTarget.wfForm} 
							formFields={this.formTarget.wfFormFields} 
							itemRender={this.wfFormItemRender}/>
				</WeaNewScroll>
			);
			this.dialogParams.visible = true;
		}
	}

	@action createForm = () => {
		const formParams = this.formTarget.wfForm.getFormParams();
		let typeLabel = this.formTarget.wfForm.fieldMap.field006.label;
		let options = this.formTarget.wfForm.fieldMap.field006.options;
		if (formParams.field006 == null || formParams.field006 === '') {
			message.error(`${i18n.message.plsSelect()}"${typeLabel}"!`)
			return;
		}
		let formTemp = options[findIndex(options, {
			key: formParams.field006
		})].showname;
		let arr = (this.moduleName === 'statechange' ? ['2', '4', '5'] : ['0', '1', '2']);
		// if (indexOf(arr, formParams.field006) < 0) {
		// 	message.error(`"${formTemp}"${i18n.message.autoGenFormFaild()}`)
		// 	return;
		// }

		let content = i18n.confirm.checkGenForm();
		content = content.replace('{param}', `"${formTemp}"`);
		this.confirmInfo({
			content,
			onOk: () => {
				this.setFormData('autoGenForm', this.generateFormFields);
				if (this.formTarget.autoGenForm.isFormInit) {
					this.generateFormDialogParams.title = i18n.label.plsSetFormName();
					this.generateFormDialogParams.style = {
						height: 90
					};
					this.generateFormDialogParams.visible = true;
				}
			}
		});
	}

	@action callAddPath = (values) => {
		const formParams = this.formTarget.wfForm.getFormParams();
		let url = '/spa/workflow/static4engine/engine.html#/main/workflowengine/path/addContent?isRoute=true';
		if (formParams.field002 != null && formParams.field002 != '') {
			url += `&formId=${formParams.field002}`;
		}
		const dialog = WeaTools.createDialog({
			title: i18n.label.createWorkflow(),
			moduleName: 'workflow',
			url:addContentPath(url),
			style: {
				width: 600,
				height: 600
			},
			callback: (datas) => {
				this.formTarget.wfForm.updateFields({
					field001: {
						value: datas.id.toString(),
						valueSpan: datas.name,
						valueObj: [{
							id: datas.id.toString(),
							name: datas.name
						}]
					}
				})
				this.getFormInfoByWorkflow(datas.id);
			},
			onCancel: () => {

			}
		});
		dialog.show();
	}

	@action callAddForm = () => {
		let url = '/spa/workflow/static4engine/engine.html#/main/workflowengine/form/formSet/addForm?isRoute=true';
		const dialog = WeaTools.createDialog({
			title: i18n.label.createForm(),
			moduleName: 'workflow',
			url:addContentPath(url),
			style: {
				width: 600,
				height: 600
			},
			callback: (datas) => {
				this.formTarget.wfForm.updateFields({
					field002: {
						value: datas.id.toString(),
						valueSpan: datas.name,
						valueObj: [{
							id: datas.id.toString(),
							name: datas.name
						}]
					}
				});
				if (datas.inDetail) {
					this.callSetFomDetail(datas.id);
				}
			},
			onCancel: () => {

			}
		});
		dialog.show();
	}

	@action callSetFomDetail = (formId) => {
		let url = `/spa/workflow/static4engine/engine.html#/main/workflowengine/form/formSet/edidForm?formId=${formId}&isBill=1`;
		const dialog = WeaTools.createDialog({
			title: '表单详细设置',
			moduleName: 'workflow',
			url:addContentPath(url),
			style: {
				width: 600,
				height: 600
			},
			callback: (datas) => {},
			onCancel: () => {

			}
		});
		dialog.show();
	}

	dispatchAutoGenForm = () => {
		const formParams = this.formTarget.wfForm.getFormParams();
		let params = {
			field006: formParams.field006,
			usedetail: formParams.usedetail
		}
		this.formTarget.autoGenForm.validateForm().then(f => {
			if (f.isValid) {
				Object.assign(params, this.formTarget.autoGenForm.getFormParams());
				this.selectedSubCompany != null && Object.assign(params, {
					subcompanyid: this.selectedSubCompany.id
				});

				let content = getLabel('522474','是否创建{param0}{params1}表');
				if(['5', '6', '7'].indexOf(formParams.field006) > -1){
					content = content.replace('{param0}', params.formName).replace('{params1}', '');
				}else{
					content = content.replace('{param0}', params.formName).replace('{params1}', (formParams.usedetail == '1' ? getLabel('17463','明细') : getLabel('6074','主')));
				}
				this.confirmInfo({
					content,
					onOk: () => {
						api.createForm(this.moduleName, params).then(data => {
							if (data.status === '1') {
								this.generateFormDialogParams.onCancel();
								this.formTarget.wfForm.updateFields({
									field002: {
										value: data.formId.toString(),
										valueSpan: data.formName,
										valueObj: [{
											id: data.formId.toString(),
											name: data.formName
										}]
									}
								})
							} else {
								message.error(data.message);
							}
						}, error => {});
					}
				});
			} else {
				f.showErrors();
				this.showError = new Date().getTime();
			}
		});
	}

	saveWf = (entry = false) => {
		const params = {}
		this.opId != null && Object.assign(params, {
			id: this.opId
		})
		this.selectedSubCompany != null && Object.assign(params, {
			subcompanyid: this.selectedSubCompany.id
		})
		this.formTarget.wfForm.validateForm().then(f => {
			if (f.isValid) {
				if (this.spinning)
					return;
				this.spinning = true;
				!entry && this.dialogParams.onCancel();
				const formParams = this.formTarget.wfForm.getFormParams();
				Object.assign(params, formParams);
				api.saveWf(this.moduleName, params).then(data => {
					if (data.status === '1') {
						entry && this.doEdit({
							id: data.id
						}, '2', formParams.field006);
						this.table.getDatas(null, 1);
						message.success(i18n.message.saveSuccess());
					} else
						message.error(data.message);
					this.spinning = false;
				}, error => {
					this.spinning = false;
				});
			} else {
				f.showErrors();
				this.showError = new Date().getTime();
			}
		});
	}

	@action setActiveTab = (key) => {
		this.editTabConfig.activeTabKey = key || this.editTabConfig.tabs[0].viewCondition;
		const tabIndex = this.getTabIndex(this.editTabConfig.tabs, key);
		if (tabIndex < 0) return;
		switch (key) {
			case '1':
				this.getFormData({
					id: this.opId,
					subcompanyid: this.selectedSubCompany ? this.selectedSubCompany.id : null
				});
				break;
			case '2':
				this.getField();
				break;
			case '3':
				this.tableEditDatas = null;
				this.getActionSetting();
				break;
			case '4':
				this.getStateProcSetFlowCheckRuleList();
				break;
			default:
				break;
		}
		this.refreshTab = new Date().getTime();
	}

	@action getField = () => {
		this.formTarget.fieldFormFields = [];
		this.spinning = true;
		let params = {
			id: this.opId
		};
		this.selectedSubCompany != null && Object.assign(params, {
			subcompanyid: this.selectedSubCompany.id
		})
		api.getField(this.moduleName, params).then(data => {
			if (data.status === '1') {
				this.setFormData('fieldForm', data.condition);
				// this.refreshTab = new Date().getTime();
			} else {
				message.error(data.message);
			}
			this.spinning = false;
		}, error => {
			this.spinning = false;
		})
	}

	convertColumn = (columns) => {
		columns.map(col => {
			if (indexOf(this.needRender, col.dataIndex) >= 0) {
				col.useRecord = true;
				this.renderCol[col.dataIndex] = col;
			}
		})
		return columns;
	}

	convertData = (datas, onChange) => {
		datas.map((data, i) => {
			data.com = data.com || {};
			data.com['fakeInp'] = [<div><span>{data.fakeInp}</span>{data.fakeInpHelpful && <WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@1o6lwt@${i}`} style={{marginLeft: 5}} title={data.fakeInpHelpful || ''} />}</div>]
			data.com['field005'] = this.renderCol['field005'].com;
			if (data.field005 === '0') {
				data.com['field006'] = this.browsers[0].com;
				data.com['field007'] = [(<div/>)];
			} else {
				data.com['field006'] = this.browsers[1].com;
				delete data.com['field007'];
			}
			// data.com['field006'] = data.field005 === '0' ? this.browsers[0].com : this.browsers[1].com;
			// data.com['field007'] = data.field005 === '0' ? this.browsers[0].com : this.browsers[1].com;
			if (onChange && data.field005 != this.tableConfig.datas[i].field005) {
				data.field006 = '';
				data.field006span = '';
			}
		})
		return datas;
	}

	@action getActionSetting = () => {
		this.spinning = true;
		this.tableConfig.columns.length = 0;
		this.tableConfig.datas.length = 0;
		api.getActionSetting(this.moduleName, {
			id: this.opId
		}).then(data => {
			if (data.status === '1') {
				this.browsers = data.items[0].table.browsers;
				const columns = this.convertColumn(data.items[0].table.columns);
				const datas = this.convertData(data.items[0].table.datas);
				this.tableConfig.columns = columns;
				this.tableConfig.datas = datas;
				this.refreshTab = new Date().getTime();
			} else {
				message.error(data.message);
			}
			this.spinning = false;
		}, error => {
			this.spinning = false
		})
	}

	doEdit = (params, key, field006) => {
		const obj = {
			id: params.id,
			topage: 'content'
		}
		this.moduleName != 'statechange' && Object.assign(obj, {
			field006
		})
		api.getTab(this.moduleName, obj).then(data => {
			if (data.status === '1') {
				this.editTabConfig.tabs.length = 0;
				data.tabs.map((tab, i) => {
					const tabConf = {
						color: '#000000',
						groupId: tab.key,
						title: tab.title,
						viewCondition: (i + 1).toString(),
					}
					this.editTabConfig.tabs.push(tabConf);
				})
				this.opId = params.id;
				this.dialogParams.title = this.moduleName === 'statechange' ? i18n.label.editStateChangeWf() : i18n.label.editStatesSchedule();
				this.dialogParams.opType = 'showContent';
				this.dialogParams.style = {
					width: 700,
					height: 500
				}
				this.setActiveTab(key);
			} else {
				message.error(data.message);
			}
		}, error => {})
	}

	@action save = () => {
		let params = {
			field001: this.opId
		}
		switch (this.editTabConfig.activeTabKey) {
			case '1':
				this.saveWf();
				break;
			case '2':
				this.saveField()
				break;
			case '3':
				this.saveAction()
				break;
			case '4':
				this.dialogParams.onCancel();
				break;
		}
	}

	resetOptionsVal = (domkey) => {
		this.formTarget.fieldForm.updateFields({
			[domkey]: {
				value: ''
			}
		})
	}

	saveField = () => {
		if (this.spinning)
			return;
		this.formTarget.fieldForm.validateForm().then(f => {
			if (f.isValid) {
				this.spinning = true;
				let params = {
					field001: this.opId,
					...this.formTarget.fieldForm.getFormParams()
				}
				this.selectedSubCompany != null && Object.assign(params, {
					subcompanyid: this.selectedSubCompany.id
				})
				api.saveField(this.moduleName, params).then(data => {
					if (data.status === '1') {
						this.dialogParams.onCancel();
						message.success(i18n.message.saveSuccess());
						this.spinning = false;
					} else {
						message.error(data.message);
						this.spinning = false;
					}
				}, error => {
					this.spinning = false;
				})
			} else {
				f.showErrors();
				this.showError = new Date().getTime();
			}
		});
	}

	saveAction = () => {
		if (this.spinning)
			return;
		this.spinning = true;
		let params = {
			field001: this.opId,
			field002: ''
		}
		const datas = this.tableEditDatas != null ? this.tableEditDatas : this.toJS(this.tableConfig.datas);
		datas.map(d => {
			delete d.com;
		})
		params.field002 = JSON.stringify(datas);
		api.saveActionSetting(this.moduleName, params).then(data => {
			if (data.status === '1') {
				this.dialogParams.onCancel();
				message.success(i18n.message.saveSuccess());
				this.spinning = false;
			} else {
				message.error(data.message);
				this.spinning = false;
			}
		}, error => {
			this.spinning = false;
		})
	}

	doChangeStatus = (record) => {
		let content = record.field005 === '1' ? i18n.confirm.forbidden() : i18n.confirm.active();
		let params = {
			id: record.id,
			field005: record.field005 === '1' ? '0' : '1'
		};
		this.confirmInfo({
			content,
			onOk: () => {
				api.changeStatus(this.moduleName, params).then(data => {
					if (data.status === '1') {
						message.success(i18n.message.opSuccess());
						this.table.getDatas();
					} else {
						message.error(data.message);
					}
				}, error => {})
			}
		});
	}

	removeWF = (params) => {
		let content;
		if (params == null) {
			params = {
				ids: this.table.selectedRowKeys
			}
			content = i18n.confirm.removeSelected();
		} else {
			content = i18n.confirm.remove();
		}
		this.confirmInfo({
			content,
			onOk: () => {
				api.removeWf(this.moduleName, params).then(data => {
					if (data.status === '1') {
						message.success(i18n.message.removeSuccess());
						this.table.getDatas(null, 1);
					}
				})
			}
		});
	}

	onWfChange = (ids, names, datas) => {
		if (names.value.length === 0) {
			this.formTarget.wfForm.updateFields({
				field002: {
					value: '',
					valueSpan: '',
					valueObj: [{
						id: '',
						name: ''
					}]
				}
			})
		} else {
			this.getFormInfoByWorkflow(names.value);
		}
	}

	onWfChange1 = (ids, names, datas) => {
		if (names.value.length === 0) {
			this.formTarget.wfForm.updateFields({
				field001: {
					value: '',
					valueSpan: '',
					valueObj: [{
						id: '',
						name: ''
					}]
				}
			})
		}
	}

	getFormInfoByWorkflow = (id) => {
		api.getFormInfoByWorkflow({
			workflowid: id
		}).then(data => {
			if (data.status === '1') {
				const {
					id,
					name
				} = data;
				this.formTarget.wfForm.updateFields({
					field002: {
						value: id || '',
						valueSpan: name || '',
						valueObj: [{
							id: id || '',
							name: name || ''
						}]
					}
				})
			} else {
				message.error(data.message);
			}
		}, error => {})
	}

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

	@action onField006Change = v => {
		const params = {
			field006: v.field006.value
		}
		api.getProcSetTemplet(this.moduleName, params).then(data => {
			if(data.status === '1'){
				this.formTarget.wfForm.updateFields({
					templetfile: data.templetfile,
					templetmobilefile: data.templetmobilefile,
					templetroute: data.templetroute
				})
			}else{
				message.error(data.message);
			}
		}, error => {});
	}

	//#region 校验规则
	@computed
	get tabButtons(){
		this.refreshTab;
		if(this.editTabConfig.activeTabKey != "4")
			return [];
		else{
			const disabled = this.checkRuleTable.selectedRowKeys.length == 0;
			return [
				<WeaButtonIcon ecId={`${this && this.props && this.props.ecId || ''}_WeaButtonIcon@ejer6b`} buttonType="add" type="primary" onClick={() => this.getProcSetCheckRule()} />,
				<WeaButtonIcon ecId={`${this && this.props && this.props.ecId || ''}_WeaButtonIcon@w18emj`} buttonType="del" type="primary" onClick={() => this.deleteCheckRule()} disabled={disabled} />
			]
		}
	}

	@action getStateProcSetFlowCheckRuleList = () => {
		api.getStateProcSetFlowCheckRuleList({attid: this.opId}).then(data => {
			if(data.status == 1){
				this.checkRuleTable = new TableStore();
				this.checkRuleTable.getDatas(data.sessionkey);
			}else{
				message.error(data.message);
			}
		})
	}

	checkRuleEdit = false;
	// kqtype;
	// msglist;
	// fieldMap;
	// related;

	get checkLevelKey(){
		let key = '';
		if(has(this.fieldMap || {}, 'check_level'))
			key = this.fieldMap.check_level;
		return key;
	}

	get checkMsglKey(){
		let key = '';
		if(has(this.fieldMap || {}, 'check_message'))
			key = this.fieldMap.check_message;
		return key;
	}

	duplicateMsg;
	getDuplicateMsg = v => {
		let msg = '';
		if(has(this.duplicateMsg || {}, `check_level_${v}`))
			msg = this.duplicateMsg[`check_level_${v}`];
		return msg;
	}

	get relatedRander(){
		const r = {};
		Object.keys(this.related || {}).map((key, index) => {
			const rela = this.related[key];
			Object.assign(r, {
				[key]: (field, textAreaProps, form, formParams) => {
					let flag = false;
					Object.keys(rela || {}).map(key => {
						const v = rela[key].split(',');
						flag = flag || (has(formParams, key) && v.indexOf(formParams[key]) > -1);
					})
					if(!flag) return null;
					return (
						<WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@yf9x67@${index}`} fieldConfig={{...field, ...textAreaProps}} form={form} formParams={formParams} />
					)
				}
			})
		})
		return r;
	}

	ruleid;
	@observable refreshCheckRuleForm = new Date().getTime();
	@action getProcSetCheckRule = (rule_type_uuid, id) => {
		this.ruleid = id;
		const params = {attid: this.opId};
		rule_type_uuid && Object.assign(params, {rule_type_uuid});
		if(id){
			Object.assign(params, {id});
			this.checkRuleEdit = true;
		}else
			this.checkRuleEdit = false;
		api.getProcSetCheckRule(params).then(data => {
			if(data.status == '1'){
				const {msglist, kqtype, field_map: fieldMap, msg: duplicateMsg, related} = data;
				Object.assign(this, {
					msglist,
					kqtype,
					fieldMap,
					duplicateMsg,
					related
				});
				this.setFormData('checkRuleForm', data.condition);
				Object.assign(this.checkRuleFormItemRender, {
					[this.checkLevelKey]: (field, textAreaProps, form, formParams) => {
						return (
							<WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@zk85q7`} fieldConfig={{...field, ...textAreaProps}} form={form} formParams={formParams} onChange={v => this.setDuplicateMessage(v[this.checkLevelKey].value)}/>
						)
					},
					...this.relatedRander
				});
				Object.assign(this.childrenComponents, {
					[this.checkMsglKey]: () => {
						let coms = [];
						this.msglist && this.msglist.map((msgInfo, index) => {
							coms.push(
								<WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@kzig2r@${index}`}
								label={msgInfo.label}
								labelCol={{ span: 8 }}
								wrapperCol={{ span: 16 }}
								>
									<div className='cust' dangerouslySetInnerHTML={{__html: msgInfo.msg}}></div>
								</WeaFormItem>
							);
						})
						return [
							{
								com: <div>{coms}</div>,
								col: 1
							}
						];
					}
				})
				if (this.formTarget.checkRuleForm.isFormInit){
					if(this.checkRuleDialogVisible)
						this.refreshCheckRuleForm = new Date().getTime();
					else
						this.checkRuleDialogVisible = true;
				}
			}else{
				message.error(data.message);
			}
		})
	}

	@action doEditCheckRule = record => {
		this.getProcSetCheckRule(null, record.id);
	}

	@observable checkRuleDialogVisible = false;
	@computed get checkRuleDialogDialogProps(){
		let buttons = [<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@j9iqpq`} type='primary' op='save' onClick={() => this.saveCheckRule()}>{i18n.label.save()}</Button>];
		return {
		...this.dialogPropsDef,
		title: !this.checkRuleEdit ? i18n.label['516691']() : i18n.label['516692'](),
		style: {
			width: 700,
			height: 405
		},
		onCancel: () => {
			this.checkRuleDialogVisible = false;
		},
		visible: this.checkRuleDialogVisible,
		buttons,
		moreBtn: {datas: this.convertToMenus(buttons)},
		key: new Date().getTime()
		}
	}

	errRef = {};
	checkRuleFormItemRender = {
		rule_type_uuid: (field, textAreaProps, form, formParams) => {
			return (
				<WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@mzpu1p`} fieldConfig={{...field, ...textAreaProps}} form={form} formParams={formParams} onChange={v => this.getProcSetCheckRule(v.rule_type_uuid.value)}/>
			)
		},
		frequency_rule: (field, textAreaProps, form, formParams) => {
			const { fieldMap } = form;
			return (
				<div className='cust'>
					<div className='select'>
						<WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@3sahuy`} fieldConfig={{...field, ...textAreaProps}} form={form} formParams={formParams} onChange={v => this.getProcSetCheckRule(v.rule_type_uuid.value)}/>		
					</div>
					<div className='child'>
						<div className='lbl text-elli' title={fieldMap['frequency_rule_count'].label}>{fieldMap['frequency_rule_count'].label}</div>
						<div className='num'>
							<WeaError ecId={`${this && this.props && this.props.ecId || ''}_WeaError@nmpcb8`} error={`${fieldMap['frequency_rule_count'].label} ${i18n.message.dataEmpty()}`} tipPosition='bottom' ref={dom => this.errRef['frequency_rule_count'] = dom}>
								<WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@8p7hqj`} fieldConfig={{ ...fieldMap['frequency_rule_count'], ...textAreaProps }} form={form} formParams={formParams}/>
							</WeaError>
						</div>
						<div className='lbl text-elli'>{i18n.label['18929']()}</div>
					</div>
				</div>
			)
		},
		frequency_rule_count: (field, textAreaProps, form, formParams) => null,
	}

	childrenComponents = {}

	setHideFormValid = () => {
        window.e9HideFormFieldKeys = [];
		const formParams = this.formTarget.checkRuleForm.getFormParams();
		Object.keys(this.related || {}).map(key => {
			const rela = this.related[key] || {};
			let flag = true;
			Object.keys(rela).map(key => {
				const v = rela[key].split(',');
				if(has(formParams, key) && v.indexOf(formParams[key]) > -1)
					flag = flag && true;
				else
					flag = false;
			})
			!flag && window.e9HideFormFieldKeys.push(key);
		})
	}

	@action saveCheckRule = () => {
		this.setHideFormValid();
		this.formTarget.checkRuleForm.validateForm().then(f => {
			if (f.isValid) {
				const params = this.formTarget.checkRuleForm.getFormParams();
				Object.assign(params, {
					attid: this.opId,
					kqtype: this.kqtype
				})
				this.ruleid && Object.assign(params, {id: this.ruleid});
				api.saveStateProcCheckRule(params).then(data => {
					if (data.status === '1') {
						message.success(i18n.message.opSuccess());
						this.getStateProcSetFlowCheckRuleList();
						this.checkRuleDialogVisible = false;
					} else {
						message.error(data.message);
					}
				}, error => {});
			} else {
				f.showErrors();
				const fields = this.formTarget.checkRuleForm.fieldMap;
				[...Object.keys(fields)].map(k => {
					const e = this.formTarget.checkRuleForm.getError(fields[k]);
					if (e != null && e != "") {
						console && console.debug(e);
						this.errRef[k] && this.errRef[k].showError();
						
					}
				});
				this.showError = new Date().getTime();
			}
		});
	}

	setDuplicateMessage = v => {
		this.formTarget.checkRuleForm.updateFields({
			[this.checkMsglKey]: {
				value: this.getDuplicateMsg(v)
			}
		})
	}

	@action deleteCheckRule = params => {
		let content;
		if (params == null) {
			params = {
				ids: this.checkRuleTable.selectedRowKeys
			}
			content = i18n.confirm.deleteSelected();
		} else {
			content = i18n.confirm.deleteSelected();
		}
		this.confirmInfo({
			content,
			onOk: () => {
				api.delStateProcCheckRule(params).then(data => {
					if (data.status === '1') {
						message.success(i18n.message.removeSuccess());
						this.checkRuleTable.getDatas(null, 1);
					}
				})
			}
		});
	}

	@action getDetachOperatelevel = v => {
		shiftapi.getDetachOperatelevel({subcompanyid: v.field004.value}).then(data => {
		  if(data.status == 1){
			this.canAdd = !(data.operatelevel < 1);
		  }else{
			message.error(data.message);
		  }
		})
	  }
	//#endregion
	/********************* action list *********************/
}

export const hrmWorkflowSetting = new HrmWorkflowSetting();