import * as Api from '../apis/salaryItemsSet';
import {
	toJS
} from 'mobx';
import {
	observable,
	action,
	computed,
} from 'mobx';
import {
	WeaCheckbox,
	WeaTableEdit,
} from 'ecCom'
import {
	WeaForm,
	WeaTableNew
} from 'comsMobx';
import {
	message
} from 'antd';
import {
	i18n
} from '../public/i18n';
const {
	TableStore
} = WeaTableNew;

export class HrmSalaryItemsSet {
	@observable main = {
		authorized: false,
		title: i18n.module.wageSetting(),
		btnMenu: [],
		loading: true,
	}
	@observable searchPanel = {
		form: new WeaForm(),
		conditions: [],
		loading: true,
		isPanelShow: false,
		conditionCount: observable.ref(4),
	}
	@observable mainDialog = {
		title: '',
		visible: false,
	}
	@observable subDialog = {
		title: '',
		visible: false,
	}
	@observable mainTable = {
		tableStore: new TableStore(),
		selectedRowKey: '',
		subCompanyId: '',
	}
	@observable formInfo = {
		form: new WeaForm(),
		conditions: [],
		loading: true,
		itemType: '',
		isShow: '',
		sub: {},
		applyscope: '',
		date: '',
		calMode: '',
		itemTypeTips: {},
	}
	@observable leftTree = {
		nodeId: '',
		nodeType: '0',
		nodeName: i18n.module.wageSetting(),
		triggerRefresh: false
	}

	@observable salary = {
		levelSetDatas: [],
		standardDatas: [],
		tableStore: new TableStore(),
		hrmResourceId: [],
		money: [],
	}
	@observable tax = {
		tableEditArray: [],
		cbStatus: [],
		date: '',
	}
	@observable cal = {
		tableEditArray: [],
		cbStatus: [],
		position: {},
		date: '',
	}
	@observable welfareCal = {
		personalPercent: '',
		companyPercent: '',
	}
	@observable calculator = {
		loading: true,
		values: [], //级联组件初始值
		valuesSub: [],
	}
	@observable textArea = {
		pageShowItems: [],
		machineRecItems: [],
		pageShowItemsSub: [],
		machineRecItemsSub: [],
	}
	@observable common = {
		loading: true,
	}

	@computed get menu() {
		let topMenu = this.main.btnMenu.filter(item => item.isTop == '1' || item.isBatch == '1');
		let rightMenu = this.main.btnMenu.filter(item => item);

		return {
			topMenu,
			rightMenu
		}
	}

	@action
	getAuth = () => {
		Api.getAuth().then(cb => {
			const {
				status,
				hasRight
			} = cb;

			if (status == '1') {
				hasRight && this.grantAuth();
				this.main.loading = false;
			} else {
				message.error(cb.message);
			}
		}).catch(error => {
			message.error(error);
		});
	}

	@action
	getButtonsMenu = () => {
		Api.getButtonsMenu().then(cb => {
			const {
				status,
				btnMenu,
			} = cb;

			if (status == '1') {
				this.main.btnMenu = btnMenu;
			} else {
				message.error(cb.message);
			}
		}).catch(error => {
			message.error(error);
		});
	}

	@action
	getTableInfo = () => {
		const {
			tableStore
		} = this.mainTable, {
			nodeType,
			nodeId
		} = this.leftTree, {
			form
		} = this.searchPanel;

		let params = form.getFormParams();

		if (nodeType == '1') {
			params = {
				subcompanyid: nodeId,
				...params
			}
		}

		Api.getTableInfo(params).then(cb => {
			const {
				sessionkey,
				status
			} = cb;

			if (status == '1') {
				sessionkey && tableStore.getDatas(sessionkey, 1);
			} else {
				message.error(cb.message);
			}
		}).catch(error => {
			message.error(error);
		});
	}

	@action
	getFormInfo = () => {
		const {
			visible
		} = this.mainDialog;

		let func;
		let params = {};

		if (!visible) { //高级搜索
			func = 'getSearchItems';
		} else { //弹框内的表单
			const {
				selectedRowKey
			} = this.mainTable;

			func = 'getSalaryForm';

			if (selectedRowKey) {
				params = {
					id: selectedRowKey,
					subcompanyid: this.leftTree.nodeId
				}
			}
		}

		Api[func](params).then(cb => {
			const {
				status,
				formField,
				itemtype,
			} = cb;

			if (status == '1') {
				if (!visible) {
					this.searchPanel.conditions = formField;
					this.searchPanel.form.initFormFields(formField);
				} else {
					this.adjustConditions(formField);
					this.setDefaultItemType(formField);
					this.formInfo.conditions = formField;
					this.formInfo.form.initFormFields(formField);
					if (itemtype) {
						this.formInfo.itemTypeTips = itemtype;
					}
					const {
						nodeId,
						nodeName,
						nodeType,
					} = this.leftTree;

					(nodeType !== '0') && this.formInfo.form.updateFields({
						subcompanyid: {
							value: nodeId,
							valueSpan: nodeName,
							valueObj: [{
								id: nodeId,
								name: nodeName,
							}]
						}
					})

					const {
						selectedRowKey
					} = this.mainTable, {
						itemType
					} = this.formInfo;

					if ((!selectedRowKey && itemType == '1') || selectedRowKey) {
						this.getTableEditDatas();
					} else {
						this.common.loading = false;
					}

				}
				this.stoploading();
			} else {
				message.error(cb.message);
			}
		}).catch(error => {
			message.error(error);
		});
	}

	@action
	adjustConditions = (conditions) => {
		const {
			selectedRowKey
		} = this.mainTable;

		conditions.map(c => {
			c.items.map(item => {
				if (item.conditionType == 'SELECT' && item.value == '') {
					item.value = '1';
				}
				if (item.domkey[0] == 'itemcode') {
					item.otherParams = {
						helpfulTip: i18n.message.codeTip(),
						regExp: /^[0-9a-zA-Z]+$/
					}
				}
				if (item.domkey[0] == 'showorder') {
					item.conditionType = 'INPUTNUMBER';
					item.rules = 'required|integer';
				}
				if (item.viewAttr == 1) {
					item.otherParams = {
						hasBorder: true
					}
				}
			});
		});
	}

	@action
	setDefaultItemType = (conditions) => {
		conditions.map(c => {
			c.items.map(item => {
				const key = item.domkey[0];
				if (key == 'itemtype') {
					this.exportSelectedValue(item.value, 'itemType');
				}
				if (key == 'calMode') {
					this.exportSelectedValue(item.value, 'calMode');
				}
				if (key == 'isshow') {
					this.exportSelectedValue(item.value, 'isShow');
				}
				if (key == 'subcompanyid') {
					this.exportSelectedValue(item.browserConditionParam.replaceDatas, 'sub');
				}
				if (key == 'applyscope') {
					this.exportSelectedValue(item.value, 'applyscope');
				}
			});
		});
	}

	@action
	exportSelectedValue = (val, type) => {
		if (type == 'itemType') this.formInfo.itemType = val; //类型
		if (type == 'calMode') this.formInfo.calMode = val; //计算方式
		if (type == 'isShow') this.formInfo.isShow = val; //是否显示在工资表
		if (type == 'applyscope') this.formInfo.applyscope = val; //应用范围
		if (type == 'sub') { //分部浏览框
			if (val.length == 0) {
				this.formInfo.sub = {
					value: '',
					valueSpan: '',
					valueObj: [{
						id: '',
						name: ''
					}]
				}
			} else {
				this.formInfo.sub = val[0]
			}
		}
	}

	@action
	ignoreVerify = () => {
		window.e9HideFormFieldKeys = []; //清空容器

		const {
			itemType,
			isShow
		} = this.formInfo;

		let hideKey;
		if (itemType == '1') {
			hideKey = ['taxrelateitem', 'directModify', 'calMode', 'zxfjkcxm'];
		}
		if (['3', '11'].includes(itemType)) {
			hideKey = ['directModify', 'calMode'];
		}
		if (itemType === '3') {
			hideKey.push('zxfjkcxm');
		}
		if (itemType == '4') {
			hideKey = ['taxrelateitem', 'calMode', 'zxfjkcxm'];
		}
		if (itemType == '9') {
			hideKey = ['taxrelateitem', 'zxfjkcxm'];
		}

		window.e9HideFormFieldKeys = hideKey;

		if (isShow == '0') {
			window.e9HideFormFieldKeys.push('showorder');
		}
	}

	@action
	getTableEditDatas = () => {
		const {
			form,
			itemType,
		} = this.formInfo, {
			selectedRowKey
		} = this.mainTable, {
			subcompanyid,
			itemtype,
			applyscope
		} = form.getFormParams();

		const params = {
			subcompanyid: subcompanyid,
			itemtype: itemtype,
			applyscope: applyscope,
		}

		if (selectedRowKey) {
			Object.assign(params, {
				id: selectedRowKey
			});
		}

		Api.getTableEditDatas(params).then(cb => {
			const {
				status,
			} = cb;

			this.common.loading = false;

			if (status !== '1') {
				message.error(cb.message);
				return;
			}

			//工资
			if (itemType == '1') {
				const {
					datas0
				} = cb;

				//等级设置
				if (datas0) {
					this.salary.levelSetDatas = datas0;
				}
				//个人基准设置
				this.salary.tableStore.getDatas(cb.sessionkey, 1)
			}
			//税收 税收（累计基数）
			if (['3', '11'].includes(itemType)) {
				const datas = Object.values(cb);
				//过滤出数组类型的数据
				const tables = datas.filter(data => Array.isArray(data));
				//假如没有列表数据，则初始化一个列表。
				if (tables.length == 0) {
					this.addTable('tax');
				} else {
					tables.map((table, index) => {

						this.addTable('tax');

						table.map((row, index) => {
							//当列表行数>1时，新增行的第一列和第二列为空。
							if (index > 0) {
								const config = {
									scopetype: [{
										key: 'scopetype',
										label: '',
										type: 'INPUT',
										viewAttr: 1
									}],
									taxbenchmark: [{
										key: 'scopetype',
										label: '',
										type: 'INPUT',
										viewAttr: 1
									}],
								}
								row.com = config;
								row.scopetype = '';
								row.taxbenchmark = '';
							}
						});
						//将table挂载到tax对象上
						this.tax[`datas${index}`] = table;
						this.tax.date = new Date();
					})
				}
			}
			if (['4', '9'].includes(itemType)) {
				['personalPercent', 'companyPercent'].forEach(v => {
					if (cb[v]) {
						this.welfareCal[v] = cb[v];
					}
				});

				const datas = Object.values(cb);
				//过滤出数组类型的数据
				const tables = datas.filter(data => Array.isArray(data));

				if (tables.length == 0) {
					selectedRowKey && this.addTable('cal');
				} else {
					tables.map((table, index) => {
						this.addTable('cal');

						table.map((row, index) => {
							//添加【设置】图标
							row.com = {
								condition: [
									(<i className='icon-coms-Flow-setting' style={{fontSize: 16, cursor:'pointer',float:'left'}} onClick={() => {this.setPositionInfo({colIndex: 'condition'})} }/>),
									({
										label: '',
										type: 'INPUT',
										editType: '1',
										key: 'condspcal',
										viewAttr: 1,
									})
								],
								formula: [(<i className='icon-coms-Flow-setting' style={{fontSize: 16, cursor:'pointer',float:'left'}} onClick={() =>  {this.setPositionInfo({colIndex: 'formula'})}}/>),
									({
										label: '',
										type: 'INPUT',
										editType: '1',
										key: 'formuladspcal',
										viewAttr: 1,
									})
								]
							}
							//当行数 > 1时，隐藏第一列
							if (index > 0) {
								const config = {
									scopetypecal: [{
										key: 'scopetypecal',
										label: '',
										type: 'INPUT',
										viewAttr: 1
									}],
								}
								Object.assign(row.com, config);
								row.scopetypecal = '';
							}
						})
						this.cal[`datas${index}`] = table;
						this.cal.date = new Date();
					})
				}
			}
		}).catch(error => {
			message.error(error);
		});
	}

	@action
	saveSalary = () => {
		const {
			form
		} = this.formInfo;

		this.ignoreVerify();

		form.validateForm().then(f => {
			if (f.isValid) {
				const {
					levelSetDatas,
				} = this.salary;

				const formParams = form.getFormParams();

				const levelTableDatas = this.jsonTranslation(levelSetDatas);

				const levelen = levelSetDatas.length;

				const {
					hrmResourceId,
					money
				} = this.salary;

				const resourceIds = toJS(hrmResourceId).toString();

				const moneys = money.map(v=>(v==='undefined')?0:v).toString();

				let totalParams = {
					...formParams,
					...levelTableDatas,
					totalje: levelen,
					hrmResourceId: resourceIds,
					money: moneys,
				}

				const {
					selectedRowKey
				} = this.mainTable;

				let func;
				if (selectedRowKey) {
					func = 'editSalaryItems';

					Object.assign(totalParams, {
						id: selectedRowKey
					});
				} else {
					func = 'addSalaryItems';
				}

				this.formInfo.loading = true;

				Api[func](totalParams).then(cb => {
					const {
						status,
						success
					} = cb;

					if (status == '1') {
						if (success) {
							this.stoploading();
							this.common.loading = false;
							this.closeDialog();
							this.getTableInfo();
							message.success(cb.message);
						} else {
							message.warning(cb.message);
						}
					} else {
						message.error(cb.message);
					}
				}).catch(error => {
					message.error(error);
				});

			} else {
				f.showErrors();
				this.setDate({
					date: new Date()
				});
			}
		})
	}

	@action
	saveTaxRevenue = () => {
		const {
			form
		} = this.formInfo;

		this.ignoreVerify();

		form.validateForm().then(f => {
			if (f.isValid) {
				const formParams = form.getFormParams();

				let tableParams = {};
				let singleTableDatasLength = [];
				let tempIndex = 0;

				const {
					tableEditArray
				} = this.tax;

				for (let index = 0; index < tableEditArray.length; index++) {
					const val = tableEditArray[index];

					if (val == '1') break

					const datas = this.tax[`datas${index}`];

					if (!this.verifyScope(datas[0], 'tax')) return

					Object.values(datas[0]).map(value => {
						if (Array.isArray(value)) {
							if (value.length == 1) {
								datas[0].scopetype = value[0];
							} else {
								datas[0].scopetype = value[0];
								datas[0].objId = value[1].value;
							}
						}
					})
					const single = this.jsonTranslation(datas);

					const all = this.deepTranslation(single, tempIndex);

					singleTableDatasLength.push(datas.length);

					Object.assign(tableParams, all);

					tempIndex += 1;

				}

				let totalParams = {
					...formParams,
					...tableParams,
					totalLength: this.tax.tableEditArray.filter(val => val == '0').length,
					singleLenSet: singleTableDatasLength.toString()
				}

				let func;

				const {
					selectedRowKey
				} = this.mainTable;

				if (selectedRowKey) {
					func = 'editSalaryItems';

					Object.assign(totalParams, {
						id: selectedRowKey
					});
				} else {
					func = 'addSalaryItems';
				}

				this.formInfo.loading = true;

				Api[func](totalParams).then(cb => {
					const {
						status,
						success
					} = cb;

					if (status == '1') {
						if (success) {
							this.stoploading();
							this.common.loading = false;
							message.success(cb.message);
							this.closeDialog();
							this.getTableInfo();
						} else {
							message.warning(cb.message);
						}
					} else {
						message.error(cb.message);
					}
				}).catch(error => {
					message.error(error);
				});

			} else {
				f.showErrors();
				this.setDate({
					date: new Date()
				});
			}
		})
	}

	@action
	saveFormulaDatas = () => {
		const {
			form,
			itemType,
		} = this.formInfo;

		this.ignoreVerify();

		form.validateForm().then(f => {
			if (f.isValid) {
				const formParams = form.getFormParams();

				let tableParams = {};
				let singleTableDatasLength = [];
				let tempIndex = 0;

				const tempArray = this.cal.tableEditArray;

				for (let index = 0; index < tempArray.length; index++) {
					const val = tempArray[index];
					//当前遍历到的可编辑列表已删除
					if (val == '1') continue;

					//校验可编辑列表必填项
					if (!this.cal[`ref${index}`].refs.edit.doRequiredCheck().pass) return;

					//获取当前列表的数据
					const datas = this.cal[`datas${index}`];

					//校验列表【范围】列是否填写
					if (!this.verifyScope(datas[0])) {
						return
					};
					//校验公式是否填写
					if (!this.verifyFormula(datas)) {
						return
					};

					Object.values(datas[0]).map(value => {
						if (Array.isArray(value)) {
							if (value.length == 1) {
								datas[0].scopetypecal = value[0];
							} else {
								datas[0].scopetypecal = value[0];
								datas[0].objId = value[1].value;
							}
						}
					})

					//删除datas中key值为com的数据
					datas.map(data => {
						if (Object.keys(data).some(key => key == 'com')) delete data.com;
					})

					//获取单个可编辑列表JSON数据
					const singleTableParams = this.jsonTranslation(datas);

					//在singleTableParams对象key值后面拼接上当前可编辑列表的索引值
					const singleTableParamsPlus = this.deepTranslation(singleTableParams, tempIndex);

					singleTableDatasLength.push(datas.length);

					Object.assign(tableParams, singleTableParamsPlus);

					tempIndex += 1;
				}

				let totalParams = {
					...formParams,
					...tableParams,
					totalLength: this.cal.tableEditArray.filter(val => val == '0').length,
					singleLenSet: singleTableDatasLength.toString()
				}

				if (itemType == '9') {
					const {
						personalPercent,
						companyPercent
					} = this.welfareCal;
					Object.assign(totalParams, {
						personalPercent: personalPercent,
						companyPercent: companyPercent,
					});
				}

				let func;
				if (this.mainTable.selectedRowKey) {
					func = 'editSalaryItems';
					Object.assign(totalParams, {
						id: this.mainTable.selectedRowKey
					});
				} else {
					func = 'addSalaryItems';
				}

				this.formInfo.loading = true;

				Api[func](totalParams).then(cb => {
					const {
						status,
						success
					} = cb;

					if (status == '1') {
						if (success) {
							this.stoploading();
							this.common.loading = false;
							message.success(cb.message);
							this.closeDialog();
							this.getTableInfo();
						} else {
							message.warning(cb.message);
						}
					} else {
						message.error(cb.message);
					}
				}).catch(error => {
					message.error(error);
				});

			} else {
				f.showErrors();
				this.setDate({
					date: new Date()
				});
			}
		})
	}

	//将对象数组转换成JSON格式
	@action jsonTranslation = (datas) => {
		let obj = {};

		datas.map((data, index) => {
			Object.keys(data).map(key => {
				obj[`${key}_${index}`] = data[key]
			})
		});

		return obj
	}

	//接收两个参数：当前列表参数、当前列表索引值
	@action deepTranslation = (obj, index) => {
		let _obj = {};

		Object.keys(obj).map(key => {
			_obj[`${key}_${index}`] = obj[key];
		})

		return _obj;
	}

	@action
	manualVerify = (datas) => {
		for (let i = 0; i < datas.length; i++) {
			const data = datas[i];
			if (i == '0' && data.scopetypecal.length > 1 && data.scopetypecal[1] === undefined) {
				message.warning(i18n.message.hrmResourceRequired());
				return false;
			}
		}
		return true;
	}

	@action
	verifyScope = (data, type) => {
		const arr = (type == 'tax') ? data.scopetype : data.scopetypecal;

		if (arr[0] !== '0' && !arr[1]) {
			message.warning(i18n.message.scopeRequired());
			return false;
		}
		return true;
	}

	@action
	verifyFormula = (datas) => {
		for (let i = 0; i < datas.length; i++) {
			const data = datas[i];

			if (!data.formuladspcal) {
				message.warning(i18n.message.formulaRequired());
				return false;
			}
		}
		return true;
	}

	@action
	deleteTableInfo = () => {
		const {
			selectedRowKey,
			subCompanyId,
			tableStore,
		} = this.mainTable;

		const params = {
			ids: selectedRowKey || tableStore.selectedRowKeys,
			subcompanyid: subCompanyId,
		}

		Api.deleteTableInfo(params).then(cb => {
			const {
				status,
				success,
			} = cb;

			if (status == '1') {
				if (success) {
					message.success(cb.message);
					this.getTableInfo();
				} else {
					message.warning(cb.message)
				}
			} else {
				message.error(error);
			}
			this.resetTableSelectedKey();
		}).catch(error => {
			message.error(error);
		});
	}

	@action
	batchHandle = () => {
		const {
			selectedRowKey,
			subCompanyId
		} = this.mainTable;

		const params = {
			id: selectedRowKey,
			subcompanyid: subCompanyId,
		}

		Api.batchHandle(params).then(cb => {
			const {
				status,
				success,
			} = cb;

			if (status == '1') {
				if (success) {
					message.success(cb.message);
					this.getTableInfo();
				} else {
					message.warning(cb.message)
				}
			} else {
				message.error(error);
			}
			this.resetTableSelectedKey();
		}).catch(error => {
			message.error(error);
		});
	}

	@action
	getCascaderDatas = () => {
		const {
			form,
			itemType,
			calMode,
		} = this.formInfo, {
			position
		} = this.cal, {
			colIndex,
			tableIndex,
		} = position, {
			subcompanyid,
			applyscope
		} = form.getFormParams()

		let func;
		if (colIndex == 'condition') {
			func = 'getConditionCascader'
		} else {
			func = 'getFormulaCascader';
		}

		let params = {
			subcompanyid: subcompanyid,
			applyscope: applyscope,
		}

		const data = this.cal[`datas${tableIndex}`][0];

		const arr = data.scopetypecal;

		Object.assign(params, {
			scopetype: arr[0].toString()
		});

		if (!this.verifyScope(data)) return;

		(arr.length > 1) && Object.assign(params, {
			scopevalue: arr[1].value
		});

		Api[func](params).then(cb => {
			const {
				status,
				compProps,
				showname,
				values,
				character,
			} = cb;

			if (status == '1') {
				this.calculator.compProps = this.handleCompProps(compProps);
				this.calculator.values = values;
				if (itemType == '9' && calMode == '2' && colIndex == 'formula') {
					this.calculator.valuesSub = values;
					this.calculator.compPropsSub = 	this.handleCompProps(compProps,'sub');;
				}
				this.calculator.showname = showname;
				this.calculator.character = character;
				this.stoploading();
			} else {
				message.error(error);
			}
		}).catch(error => {
			message.error(error);
		});
	}


	//为subChildren中的选项绑定click事件
	handleCompProps = (data,type) => {
		const compProps =JSON.parse(JSON.stringify(data));
		Object.values(compProps.subChildren).map(value => {
			if (Array.isArray(value)) {
				value[value.length - 1].options.map(option => {
					const {
						showname,
						key
					} = option;

					option.showname = <span style={{display:"inline-block",width:"100%"}} onClick={e => this.handleClick(e,key,type)} title={showname}>{showname}</span>
				});
			} else {
				if (value.options.length > 0) {
					value.options.map(option => {
						const {
							showname,
							key
						} = option;

						option.showname = <span style={{display:"inline-block",width:"100%"}} onClick={e => this.handleClick(e, key,type)} title={showname}>{showname}</span>
					});
				}
			}
		});
		return compProps;
	}

	handleClick = (e, key,type) => {
		const {
			values,
			valuesSub
		} = this.calculator;

		const lastSelectedKey =  (type != 'sub') ? toJS(values)[values.length - 1] :toJS(valuesSub)[valuesSub.length - 1] ;

		if (key !== lastSelectedKey) {
			return
		} else {
			e.stopPropagation();
			this.changeCascaderValue(toJS(values),type);
		}

	}

	@action
	clickTreeNode = (id, type, name) => {
		this.setTreeNodeInfo(id, type, name);
		this.resetSearchInfo();
		this.subcompanylinkage();
		this.refreshTable();
		this.getTableInfo();
	}

	@action
	setTreeNodeInfo = (id, type, name) => {
		this.leftTree.nodeId = id;
		this.leftTree.nodeType = type;
		this.leftTree.nodeName = name;
	}

	@action
	grantAuth = () => {
		this.main.authorized = true;
	}

	@action
	closeAuth = () => { //关闭权限
		this.main.authorized = false;
	}

	@action
	changeSearchPanelStatus = (bool) => { //改变弹框的状态
		this.searchPanel.isPanelShow = bool;
	}

	@action
	openDialog = (type) => {
		const {
			visible
		} = this.mainDialog, {
			selectedRowKey
		} = this.mainTable;

		if (!visible) {
			this.mainDialog.visible = true;
			this.mainDialog.title = !selectedRowKey ? i18n.label.newSalaryItemsSet() : i18n.label.editSalaryItemsSet();
			this.getFormInfo();

		} else {
			const {
				position
			} = this.cal, {
				tableIndex,
				colIndex,
			} = position, {
				itemType,
				calMode
			} = this.formInfo;

			if (!this.verifyScope(this.cal[`datas${tableIndex}`][0])) return;

			this.subDialog.visible = true;
			this.subDialog.title = (type == 'cd') ? i18n.label.condition() : i18n.label.formula();
			this.subDialog.type = type;

			if ((itemType == '9' && calMode == '2' && colIndex == 'formula')) {
				this.getCascaderDatas();
			}
		}
	}

	@action
	closeDialog = () => {
		const {
			visible
		} = this.subDialog;

		if (visible) {
			this.subDialog.visible = false;
		} else {
			this.mainDialog.visible = false;
			this.mainTable.selectedRowKey = '';
			this.common.loading = true;
		}
	}

	@action
	setSelectedRowInfo = (key, id) => { //设置列表被选中的值（用作编辑和删除的参数）
		this.mainTable.selectedRowKey = key;
		this.mainTable.subCompanyId = id;
	}

	@action
	refreshPage = () => { //刷新页面
		this.resetSearchInfo();
		this.forceLeftTreeRefresh();
		this.getTableInfo();
		this.clickTreeNode('0', '0', i18n.module.wageSetting());
	}

	@action
	resetSearchInfo = () => { //重置搜索条件
		this.searchPanel.isPanelShow = false;
		this.searchPanel.form.resetConditionValue();
	}

	@action
	refreshFormInfo = () => { //重置表单
		this.formInfo.form = new WeaForm();
		this.formInfo.conditions = [];
		this.formInfo.loading = true;
	}

	@action
	refreshTable = () => { //重置列表
		this.mainTable.tableStore = new TableStore();
	}

	@action
	resetTableSelectedKey = () => {
		this.mainTable.selectedRowKey = '';
	}

	@action
	refreshTableEdit = (type) => {
		if (type == 'formula') {
			this.cal.cbStatus = [];
			this.cal.tableEditArray = [];
		}
		if (type == 'tax') {
			this.tax.tableEditArray = [];
			this.cal.cbStatus = [];
		}
	}

	@action
	refreshPercent = () => {
		this.welfareCal.personalPercent = '';
		this.welfareCal.companyPercent = '';
	}

	@action
	refreshCalculator = () => {
		this.calculator.loading = true;
		this.calculator.values = [];
		this.calculator.showname = [];
		this.calculator.character = '';
		this.calculator.compProps = '';
		this.clearPositionInfo();
		this.clearTextArea();
	}

	@action
	clearTextArea = () => {
		this.textArea.pageShowItems = [];
		this.textArea.machineRecItems = [];
	}

	@action
	refreshCalculatorCopy = () => {
		this.textArea.pageShowItemsSub = [];
		this.textArea.machineRecItemsSub = [];
		this.calculator.valuesSub = [];
	}

	@action
	refreshLevelSet = () => {
		this.salary.levelSetDatas = [{
			amount: "",
			jobactivityid: "",
			jobid: "",
			joblevelfrom: "",
			joblevelto: "",
		}];
	}

	@action
	subcompanylinkage = () => {
		const {
			nodeType,
			nodeId,
			nodeName
		} = this.leftTree;

		nodeType == '1' && this.searchPanel.form.updateFields({
			subcompanyid: {
				value: nodeId,
				valueSpan: nodeName,
				valueObj: [{
					id: nodeId,
					name: nodeName,
				}]
			}
		});
	}

	@action
	forceLeftTreeRefresh = () => {
		this.leftTree.triggerRefresh = !this.leftTree.triggerRefresh;
	}

	@action
	setDate = (date) => {
		this.formInfo.date = date;
	}

	@action
	stoploading = () => {
		const {
			visible
		} = this.mainDialog;

		if (!this.mainDialog.visible) {
			this.searchPanel.loading = false;
		} else {
			if (!this.subDialog.visible) {
				this.formInfo.loading = false;
			} else {
				this.calculator.loading = false
			}
		}
	}

	@action
	addTable = (type) => {
		const len = this[type].tableEditArray.length;
		this[type][`datas${len}`] = [];
		this[type].tableEditArray.push('0');
	}

	@action
	setFormulaDatas = (datas, index) => {
		if (datas[0] && !datas[0].com) {
			datas[0].com = {
				condition: [(<i className='icon-coms-Flow-setting' style={{fontSize: 16, cursor:'pointer',float:'left'}} onClick={() => {this.setPositionInfo({colIndex: 'condition'})} }/>)],
				formula: [(<i className='icon-coms-Flow-setting' style={{fontSize: 16, cursor:'pointer',float:'left'}} onClick={() =>  {this.setPositionInfo({colIndex: 'formula'})}}/>)]
			}
		};
		this.cal.date = new Date(); //为了更新模板

		this.cal[`datas${index}`] = datas;
	}

	@action
	changeTableSelectedStatus = (val, index, type) => {
		if (type == 'formula') {
			const {
				cbStatus
			} = this.cal;

			let temp = cbStatus.length > 0 ? cbStatus : [...this.cal.tableEditArray].filter(cb => cb == '0');

			temp[index] = val;
			this.cal.cbStatus = temp;
		}

		if (type == 'tax') {
			const {
				cbStatus
			} = this.tax;

			let temp = cbStatus.length > 0 ? cbStatus : [...this.tax.tableEditArray].filter(cb => cb == '0');

			temp[index] = val;

			this.tax.cbStatus = temp;
		}
	}

	@action
	changeTableEditStatus = (type) => {
		if (type == 'count') {
			const {
				cbStatus
			} = this.cal;
			this.cal.tableEditArray = cbStatus;
			this.cal.cbStatus = [];
		}
		if (type == 'tax') {
			const {
				cbStatus
			} = this.tax;

			this.tax.tableEditArray = cbStatus;
			this.tax.cbStatus = [];
		}

	}

	//该函数将用于页面显示的和用于接口传参的数据存储到对应的容器中。
	//第一个参数：选中的元素，包括工资项名称、运算符号、数字等；
	//第二个参数：标识参数，用来标识元素被PUSH到哪一个容器中
	//其中一个容器的数据用于页面显示，另一个容器则是生成接口所需的参数
	//第三个参数：标识参数，用来区分主次级联组件。
	@action
	pushItem = (item, type, calType) => {
		let tempPsItems = (calType == 'sub') ? 'pageShowItemsSub' : 'pageShowItems',
			tempMacItems = (calType == 'sub') ? 'machineRecItemsSub' : 'machineRecItems';

		if (type) {
			(type == 'page') && this.textArea[tempPsItems].push(item);
			(type == 'machine') && this.textArea[tempMacItems].push(item);
		} else {
			this.textArea[tempPsItems].push(item);
			this.textArea[tempMacItems].push(item);
		}
	}

	@action
	popItem = (type) => {
		if (type == 'sub') {
			this.textArea.pageShowItemsSub.pop();
			this.textArea.machineRecItemsSub.pop();
		} else {
			this.textArea.pageShowItems.pop();
			this.textArea.machineRecItems.pop();
		}
	}

	//改变级联组件选中值
	//第一个参数：级联组件抛出的选中值
	//第二个参数：标识参数，用来标识主次级联组件
	@action
	changeCascaderValue = (cb, type) => {
		const {
			showname,
			values,
			valuesSub,
			character,
		} = this.calculator, {
			position
		} = this.cal;

		//声明一个变量存储级联组件抛出的选中值
		let tempValues = (type == 'sub') ? valuesSub : values;

		//级联组件包含的最后一个组件选中值
		const lastKey = cb[cb.length - 1];

		//条件弹框内的级联组件，当lastKey不存在时，中断执行。
		if (position.colIndex == 'condition' && !lastKey) return;

		//根据下标读取级联组件第一个选中值、第二个选中值。
		//分割符号字符串
		const firstKey = parseInt(cb[0]),
			secondKey = cb[1],
			characterArr = character.split(',');

		let thirdKey;
		if (cb.length > 2) thirdKey = cb[2];

		//获取第一级工资项对应的符号位
		const char = characterArr[firstKey - 1];

		if (cb.length < 3) {
			//读取子工资项的名称
			const showName = showname[firstKey - 1][secondKey];

			//子工资项被选中后，执行代码块里面的逻辑
			if (lastKey) {
				this.pushItem(showName, 'page', type);

				const machineItem = `${char}${secondKey}${char}`
				this.pushItem(machineItem, 'machine', type);
			}

		} else {
			//级联组件第二级组件选中的名称
			const mid = showname[firstKey - 1][0][secondKey];
			//级联组件第三级组件选中的名称
			const last = showname[firstKey - 1][1][thirdKey];

			// (firstKey === 4) => 上月数据
			const showName = (firstKey === 4) ? `${mid}(${last})` : `${last}(${mid})`;

			if (lastKey) {
				this.pushItem(showName, 'page', type);
				//生成机器能够识别的公式
				const v = (firstKey === 4) ? `${secondKey}[${thirdKey}]` : `${thirdKey}(${secondKey})`;

				const machineItem = `${char}${v}${char}`;
				this.pushItem(machineItem, 'machine', type);
			}

		}

		if (type == 'sub') {
			this.calculator.valuesSub = cb;
		} else {
			this.calculator.values = cb;
		}

	}

	//清空容器
	@action
	clearCalculator = (type) => {
		this.textArea.pageShowItemsSub = [];
		this.textArea.machineRecItemsSub = [];
		this.textArea.pageShowItems = [];
		this.textArea.machineRecItems = [];
	}

	@action
	setPositionInfo = (obj) => {
		Object.assign(this.cal.position, obj);

		const {
			colIndex,
			tableIndex
		} = this.cal.position;

		if (colIndex && (tableIndex || tableIndex === 0)) {
			const temp = (colIndex == 'condition') ? 'cd' : 'fl';
			this.openDialog(temp);
		}

	}

	@action
	writeToTable = () => {
		const {
			pageShowItems,
			machineRecItems,
			pageShowItemsSub,
			machineRecItemsSub,
		} = this.textArea, {
			tableIndex,
			rowIndex,
			colIndex
		} = this.cal.position, {
			itemType,
			calMode
		} = this.formInfo;

		const strings = [];

		['pageShowItems', 'machineRecItems', 'pageShowItemsSub', 'machineRecItemsSub'].forEach(v => {
			strings.push(this.textArea[v].join(''));
		});

		//生成公式节点所需的配置项
		const com = {
			label: '',
			type: 'INPUT',
			editType: '1',
			key: (colIndex == 'condition') ? 'condspcal' : 'formuladspcal',
			viewAttr: 1,
		}
		//找到对应的列表
		const table = this.cal[`datas${tableIndex}`];
		//找到对应的行
		const row = table[rowIndex];
		//找到对应的列
		const col = row.com[colIndex];

		//将公式节点附着到对应的列表单元上
		if (col[1]) {
			col[1] = com;
		} else {
			col.push(com);
		}

		if (colIndex == 'condition') {
			row.condspcal = strings[0];
			row.concal = strings[1];
		} else {
			//福利计算&&分别计算
			const isSeparateCal = (itemType == '9' && calMode == '2');
			//复合公式  multiCal用于页面显示 multiCalTrans保存到数据库
			const multiCal = `${strings[0]};${strings[2]}`;
			const multiCalTrans = `${strings[1]};${strings[3]}`;
			//改变列表的配置项
			row.formuladspcal = isSeparateCal ? multiCal : strings[0];
			row.formulacal = isSeparateCal ? multiCalTrans : strings[1];
		}

		this.closeDialog();

		this.cal.date = new Date(); //强行让tableEdit刷新

	}

	@action
	clearPositionInfo = () => {
		this.cal.position.colIndex = '';
		this.cal.position.tableIndex = '';
	}

	@action
	exportRef = (com, type, index) => {
		switch (type) {
			case 'tax':
				this.tax[`ref${index}`] = com;
				break;
			case 'cal':
				this.cal[`ref${index}`] = com;
				break;
		}
	}

	@action
	setLevelSetDatas = (datas) => {
		this.salary.levelSetDatas = datas;
	}

	@action
	setTaxRateDatas = (datas, index) => {
		this.tax[`datas${index}`] = datas;
	}

	@action
	setStandardSet = (datas) => {
		this.salary.standardDatas = datas;
	}

	@action
	setWelfareCalPercent = (val, type) => { //福利计算 - 设置个人、公司百分比
		if (type == 'personal') this.welfareCal.personalPercent = val;
		if (type == 'company') this.welfareCal.companyPercent = val;
	}

	@action
	splitFormula = () => {
		const {
			position
		} = this.cal, {
			tableIndex,
			rowIndex,
			colIndex,
		} = position, {
			itemType,
			calMode
		} = this.formInfo;

		const data = this.cal[`datas${tableIndex}`][rowIndex],
			{
				condspcal,
				concal,
				formuladspcal,
				formulacal
			} = data;

		if (colIndex == 'condition') {
			condspcal && concal && this.furtherSplit(condspcal, concal);
		} else {
			if (formuladspcal && formulacal) {
				if (itemType == '9' && calMode == '2') {
					const tempArray = formulacal.split(';');

					formuladspcal.split(';').map((str, index) => {
						this.furtherSplit(str, tempArray[index], index);

					});
				} else {
					this.furtherSplit(formuladspcal, formulacal);
				}

			}
		}
	}

	@action setPersonalStandardModifyDatas = (data) => {
		const arr = data.split('_');

		const id = arr[0],
			money = arr[1];

		const {
			hrmResourceId
		} = this.salary;

		if (!toJS(hrmResourceId).includes(id)) {
			['hrmResourceId', 'money'].map((v, i) => {
				this.salary[v].push(arr[i]);
			});
		} else {
			this.salary.money[toJS(hrmResourceId).findIndex(hrmId => hrmId === id)] = money;
		}

	}

	@action resetStandardSet = () => {
		['hrmResourceId', 'money', 'tableStore'].map((v, i) => {
			this.salary[v] = (i === 2) ? new TableStore() : [];
		});
	}


}