import * as mobx from 'mobx';
import * as Api from '../apis/decentralizationAdminSet';

import {
	observable,
	action,
	computed,
	extendObservable
} from 'mobx';

import {
	WeaForm,
	WeaTableNew
} from 'comsMobx';

import {
	message
} from 'antd'

import {
	i18n
} from '../public/i18n';

const {
	TableStore
} = WeaTableNew;
import {
	RSAEcrypt
} from "../util/RSAUtil";
import {
	checkWeakPass
} from "../util/PASSUtil.js";

const toJS = mobx.toJS;
export class HrmDecentralizationAdminSet {
	@observable title = i18n.module.decentAdminSetting();
	@observable btnMenu = [];
	@observable authorized = false;
	@observable loading = true;
	@observable date = '';
	@observable tableStore = new TableStore();
	@observable isPanelShow = false;
	@observable date = '';
	@observable searchPanel = {
		condition: [],
		form: new WeaForm(),
		value: '',
		loading: true,
		conditionCount: 3,
	}
	@observable editor = {
		visible: false,
		form: new WeaForm(),
		condition: [],
		loading: true,
	}
	@observable securitySet = {
		visible: false,
		form: new WeaForm(),
		condition: [],
		title: i18n.module.securitySetting(),
		loading: true,
		verifyTypeSelectedValue: '',
		useTypeSelectedValue: '',
		checkboxValue: '',
		loginId: '',
	}

	@observable isSecondaryVerifyUsed = false;
	@observable isSecondaryVerifySetted = false;

	@observable hasValidateType = false;
	@observable openRSA = "0";

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

		return {
			topMenu,
			rightMenu
		}
	}

	@computed get encryptedPass(){
		const {password} = this.editor.form.getFormParams();

		return password;
	}

	@action
	getRight = () => {
		this.loading = true;
		Api.getRight().then(rs => {
			let {
				api_status,
				btnMenu = [],
				hasRight
			} = rs;

			if (api_status) {
				if (hasRight) {
					this.authorized = true;
					this.btnMenu = btnMenu;
					this.getTableInfo();
				}
				this.loading = false;
			} else {
				message.error(rs.message);
			}
		}).catch(error => {
			message.error(error);
		});
	}

	getTableInfo = () => {
		let params = this.searchPanel.form.isFormInit ? this.searchPanel.form.getFormParams() : {
			lastname: this.searchPanel.value
		};
		this.tableStore = new TableStore();
		Api.getTableInfo(params).then(rs => {
			let {
				api_status,
				sessionkey
			} = rs;

			if (api_status) {
				sessionkey && this.tableStore.getDatas(sessionkey, 1);
			} else {
				message.error(rs.message);
			}
		}).catch(error => {
			message.error(error);
		});
	}

	getEditorForm = () => {
		this.editor.loading = true;
		let type = this.editor.formType;
		let params = type == 'new' ? {} : {
			id: this.selectedRowsKeys
		}
		Api.getEditorForm(params).then(rs => {
			const {
				api_status,
				conditions,
				minpasslen,
				passwordComplexity,
				tip1,
				tip2,
				openRSA,
			} = rs;

			if (api_status) {
				if (conditions) {
					conditions[0].items.map(item => {
						if (item.viewAttr == 1) {
							item.hasBorder = true;
						}
					});
					this.editor.form.initFormFields(conditions);
					this.editor.condition = conditions;
					extendObservable(this.editor, {
						minPassLen: minpasslen,
						passwordComplexity: passwordComplexity,
						passLenTip: tip1,
						passwordComplexityTip: tip2,
					});
				}
				this.editor.loading = false;
				this.openRSA = openRSA;
			} else {
				message.error(rs.message);
			}
		}).catch(error => {
			message.error(error);
		});
	}

	deleteTableRows = () => {
		let params = {
			ids: this.selectedRowsKeys
		};
		Api.deleteTableRows(params).then(rs => {
			let {
				api_status,
				sign
			} = rs;

			if (api_status) {
				if (sign == '1') {
					message.success(rs.message);
					this.getTableInfo();
				} else {
					message.warning(rs.message)
				}
			} else {
				message.error(rs.message);
			}
		}).catch(error => {
			message.error(error);
		});
	}

	addAdminInfo = () => {
		this.editor.form.validateForm().then(f => {
			if (f.isValid) {
				if (!this.validatePassword(this.editor.form.getFormParams().password)) {
					return;
				}
				let params = {
					...this.editor.form.getFormParams()
				};
				RSAEcrypt(this.openRSA,params.password).then(password =>{
					checkWeakPass(password,()=>{
						params.password = password;
						Api.addAdminInfo(params).then(rs => {
							let {
								api_status,
								sign
							} = rs;

							if (api_status) {
								if (sign == '1') {
									message.success(rs.message);
									this.getTableInfo();
									this.setEditorDialogVisible(false);
								} else {
									message.warning(rs.message);
								}
							} else {
								message.error(rs.message);
							}
						})
					})
				});
				
			} else {
				f.showErrors();
				this.setDate({
					date: new Date()
				});
			}
		});
	}

	editAdminInfo = () => {
		this.editor.form.validateForm().then(f => {
			if (f.isValid) {
				const {password} = this.editor.form.getFormParams();
				if ( !this.validatePassword(password)  || (password !== this.encryptedPass)) {
					return;
				}
				let params = {
					...this.editor.form.getFormParams(),
					id: this.selectedRowsKeys
				}
				RSAEcrypt(this.openRSA, params.password).then(password => {
					checkWeakPass(password,()=>{
						params.password = password;
						Api.editAdminInfo(params).then(rs => {
							let {
								api_status,
								sign
							} = rs;

							if (api_status) {
								if (sign == '1') {
									message.success(rs.message);
									this.getTableInfo();
									this.setEditorDialogVisible(false);
								} else {
									message.warning(rs.message);
								}
							} else {
								message.error(rs.message);
							}
						})
					} );
				});
				
			} else {
				f.showErrors();
				this.setDate({
					date: new Date()
				});
			}
		});
	}

	validatePassword = (password) => {
		const {
			minPassLen,
			passLenTip,
			passwordComplexityTip
		} = this.editor;

		if (password.length < minPassLen) {
			message.warning(passLenTip);
			return false;
		}
		if (!this.verifyPasswordComplexity(password)) {
			message.warning(passwordComplexityTip);
			return false;
		}
		return true;

	}

	verifyPasswordComplexity = (password) => {
		const {
			passwordComplexity
		} = this.editor;
 
		const judge = (regExps) => {
            return regExps.every(regExp => regExp.test(password))
		}
		
		if (passwordComplexity == '1') {
			const regExps = [/[a-z]+/, /[A-Z]+/, /\d+/];
            if (!judge(regExps)) {
                return false;
            }
		}
		if (passwordComplexity == '2') {
			const regExps = [/[a-zA-Z_]+/, /\W+/, /\d+/];
            if (!judge(regExps)) {
                return false;
            }
		}
        if (passwordComplexity == '3') {
            const regExps = [/[a-zA-Z_]+/, /\d+/];
            if (!judge(regExps)) {
                return false;
            }
        }
		return true;
	}

	setEditorDialogVisible = (bool, type) => {
		this.editor.visible = bool
		if (bool) {
			extendObservable(this.editor, {
				formType: type,
				title: type == 'new' ? i18n.label.newSysadmin() : i18n.label.editSysadmin(),
			});
			this.getEditorForm();
		} else {
			this.editor.form = new WeaForm();
		}
	}

	getSecuritySetForm = () => {
		this.securitySet.loading = true;
		let params = {
			id: this.selectedRowsKeys
		};
		Api.getSecuritySetForm(params).then(rs => {
			let {
				api_status,
				conditions,
			} = rs;

			if (api_status) {
				if (conditions) {
					let items = conditions[0].items,
						len = items.length;

					items.map(item => {
						let key = item.domkey[0];
						if (key == 'selectdate') {
							item.otherParams = {
								startValue: new Date()
							}
						}
					});

					items.unshift(items.splice(len - 1, 1)[0]);
					this.usestateOption = this.getUsestateOption(conditions)
					this.securitySet.condition = conditions;

					this.handleConditions(conditions);
				}
				this.securitySet.loading = false;
			} else {
				message.error(rs.message);
			}
		}).catch(error => {
			message.error(error);
		});
	}

	getUsestateOption = (conditions) => {
		let options;
		 conditions.map(c => c.items.map(item => {
              if (item.domkey[0] == 'usbstate') {
                 options = item.options
              }
          }))
		 return options
	}

	handleCondition = () => {
		const {form,condition} = this.securitySet;
		const {userUsbType} =form.getFormParams();
		condition.map(c => c.items.map(item => {
          if (item.domkey[0] == 'usbstate') {
              item.options = (userUsbType == '6') ? this.usestateOption.slice(0,2):this.usestateOption
          }
      }))
	}

	getSearchCondition = () => {
		this.searchPanel.loading = true;
		Api.getSearchCondition().then(rs => {
			let {
				api_status,
				conditions,
			} = rs;

			if (api_status) {
				if (conditions) {
					this.searchPanel.condition = conditions;
					this.searchPanel.form.initFormFields(conditions);
				}
				this.searchPanel.loading = false;
			} else {
				message.error(rs.message);
			}
		}).catch(error => {
			message.error(error);
		});
	}

	//收集需要检验的表单元素的key值
	collectViewAtrr3key = (conditions) => {
		let keys = [];
		conditions[0] && conditions[0].items.forEach(item => {
			const {
				viewAttr,
				domkey
			} = item;
			if (viewAttr === 3) {
				let key;
				if (domkey.length > 1) {
					key = domkey.join('__');
				}else{
					key = domkey[0];
				}
				keys.push(key);
			}
		})
		return keys
	}

	securitySave = () => {

		window.e9HideFormFieldKeys = [];

		const {form,condition}= this.securitySet;

		const {userUsbType,needauto} = form.getFormParams();

		const viewAttr3keys = this.collectViewAtrr3key(condition);

		if(userUsbType === '6'){
			window.e9HideFormFieldKeys = viewAttr3keys;
		}
		if (userUsbType === '4') {//动态密码
			window.e9HideFormFieldKeys = viewAttr3keys.filter(key=>key!=='mobile')
		}
		if (userUsbType === '3') {//动态令牌
			window.e9HideFormFieldKeys = viewAttr3keys.filter(key=>key!=='tokenKey')
		}
		if (userUsbType === '7'){
			window.e9HideFormFieldKeys = viewAttr3keys;
		}
		if (userUsbType === '901'&&needauto=='0'){
			window.e9HideFormFieldKeys = viewAttr3keys

		}if (userUsbType === '901'&&needauto=='1'){
			window.e9HideFormFieldKeys = viewAttr3keys.filter(key=>key!=='selectdate')   
		}

		this.securitySet.form.validateForm().then(f => {
			if (f.isValid) {
				let userUsbType = this.securitySet.form.getFormParams().userUsbType;
				if (userUsbType == '4') {
					let mobile = this.securitySet.form.getFormParams().mobile;
					if (!this.verifyMobile(mobile)) return;
				}
				if (userUsbType == '3') {
					let tokenKey = this.securitySet.form.getFormParams().tokenKey;
					if (!this.verifyTokenKey(tokenKey)) return;
				}
				let params = {
					...this.securitySet.form.getFormParams(),
					id: this.selectedRowsKeys
				};
				Api.securitySave(params).then(rs => {
					let {
						api_status,
						sign
					} = rs;

					if (api_status) {
						if (sign) {
							sign == '1' ? message.success(rs.message) && this.setSecuritySetDialogVisible(false) : message.warning(rs.message);
						}
					} else {
						message.error(rs.message);
					}
				});
			} else {
				f.showErrors();
				this.setDate({
					date: new Date()
				});
			}
		});
	}

	//获取二次验证密码信息：是否设置、是否启用
	getSecondaryVerifyPwdInfo = () => {
		Api.isUseSecondaryPwd({
			id: this.selectedRowsKeys,
		}).then(cb => {
			const {
				isSetted, //是否设置
				isUse, //是否启用
			} = cb;

			this.isSecondaryVerifySetted = isSetted;
			this.isSecondaryVerifyUsed = isUse;
		});
	}

	//保存二次验证密码设置
	saveSecondaryPasswordSetting = (useSecondaryPwd) => {
		Api.saveUseSecondaryPwd({
			id: this.selectedRowsKeys,
			useSecondaryPwd, //useSecondaryPwd:true -> 启用 false -> 停用
		}).then(cb => {
			const {
				sign
			} = cb;

			if (sign !== '1') {
				message.warning(cb.message);
				return
			}

			// this.isSecondaryVerifyUsed = useSecondaryPwd;
			this.getSecondaryVerifyPwdInfo();
		});
	}


	verifyMobile = (mobile) => {
		let reg = /^1\d{10}$/;
		if (!reg.test(mobile)) {
			message.warning("请输入正确手机号！")
			return false;
		}
		return true
	}

	verifyTokenKey = (tokenKey) => {
		let reg = /^\d{10}$/;
		if (!reg.test(tokenKey)) {
			message.warning("请输入10位数字令牌序列号！")
			return false;
		}
		return true
	}


	handleConditions = (conditions) => {
		conditions.map(c => {
			c.items.map(item => {
				let key = item.domkey[0],
					val = item.value;
				if (key == 'userUsbType') {
					this.setVerifyTypeSelectedValue(key, item.value);
					this.hasValidateType = item.options.length > 1 ? true : false;
				}
				key == 'usbstate' && this.setUseTypeSelectedValue(item.value);
				key == 'needauto' && this.setCheckboxValue(item.value);

			});
		});

		this.addRules(this.securitySet.verifyTypeSelectedValue);
	}

	setSecuritySetDialogVisible = (bool) => {
		this.securitySet.visible = bool;
		if (bool) {
			this.getSecuritySetForm();
			this.getSecondaryVerifyPwdInfo();
		} else {
			this.securitySet.form = new WeaForm();
		}
	}

	setVerifyTypeSelectedValue = (key, val, idy) => {
		this.securitySet.verifyTypeSelectedValue = val;
		if (idy) {
			this.changeConditon(key, val);
			['usbstate', 'needauto'].map(key => this.useTypeAndCheckboxReset(key));
			this.addRules(val);
		}
	}

	setUseTypeSelectedValue = (val, key, idy) => {
		this.securitySet.useTypeSelectedValue = val;
		if (idy) {
			this.changeConditon(key, val);
			this.useTypeAndCheckboxReset('needauto');
			this.addRules(this.securitySet.verifyTypeSelectedValue);
		}
	}

	setCheckboxValue = (val, key, idy) => {
		this.securitySet.checkboxValue = val;
		if (idy) {
			this.changeConditon(key, val);
			this.addRules(this.securitySet.verifyTypeSelectedValue);
		}
	}

	changeConditon = (key, val) => {
		let c = this.securitySet.condition;
		c.map(cd => {
			cd.items.map(item => {
				if (item.domkey[0] == key) {
					item.value = val;
				}
			});
		});
	}

	useTypeAndCheckboxReset = (key) => {
		let c = this.securitySet.condition;
		c.map(cd => {
			cd.items.map(item => {
				if (item.domkey[0] == key) {
					item.value = '0';
				}
			});
		});
		key == 'usbstate' && this.setUseTypeSelectedValue('0');
		key == 'needauto' && this.setCheckboxValue('0');
	}

	addRules = (val) => {
		let c = this.securitySet.condition;
		let cb = this.securitySet.checkboxValue;

		c.map(cd => {
			cd.items.map(item => {
				let key = item.domkey[0];
				if (!val) {
					this.deleteRules();
				}
				if (val == '4' && cb == '0' && key == 'mobile') {
					if (!item.rules) {
						item.rules = 'required|string';
					}
					['serial', 'tokenKey', 'selectdate'].map(key => this.deleteRules(key));
				}
				if (val == '4' && cb == '1' && (key == 'mobile' || key == 'selectdate')) {
					if (!item.rules) {
						item.rules = 'required|string';
					}
					['serial', 'tokenKey'].map(key => this.deleteRules(key));
				}
				if (val == '2' && cb == '0' && key == 'serial') {
					if (!item.rules) {
						item.rules = 'required|string';
					}
					['mobile', 'tokenKey', 'selectdate'].map(key => this.deleteRules(key));
				}
				if (val == '2' && cb == '1' && (key == 'serial' || key == 'selectdate')) {
					if (!item.rules) {
						item.rules = 'required|string';
					}
					['mobile', 'tokenKey'].map(key => this.deleteRules(key));
				}
				if (val == '3' && cb == '0' && key == 'tokenKey') {
					if (!item.rules) {
						item.rules = 'required|string';
					}
					['mobile', 'serial', 'selectdate'].map(key => this.deleteRules(key));
				}
				if (val == '3' && cb == '1' && (key == 'tokenKey' || key == 'selectdate')) {
					if (!item.rules) {
						item.rules = 'required|string';
					}
					['mobile', 'serial'].map(key => this.deleteRules(key));
				}
			});
		});
		this.securitySet.form = new WeaForm();
		this.securitySet.form.initFormFields(c);
		this.handleCondition();
	}

	deleteRules = (key) => {
		let c = this.securitySet.condition;
		c.map(cd => {
			cd.items.map(item => {
				let k = item.domkey[0];
				if (!key || k == key) {
					if (item.rules) {
						delete item.rules
					}
				}
			});
		});
		// this.securitySet.form = new WeaForm();
		// this.securitySet.form.initFormFields(c);

	}

	setSelectedRowsKeys = (id) => {
		extendObservable(this, {
			selectedRowsKeys: id
		});
	}

	setPanelStatus = (bool) => {
		this.isPanelShow = bool;
	}

	updateFields = (val) => {
		this.searchPanel.form.updateFields({
			lastname: {
				value: val
			}
		});
	}

	setBaseValueOfSearch = (val) => {
		this.searchPanel.value = val;
	}

	setLoginId = (id) => {
		this.securitySet.loginId = id;
	}

	setDate = (date) => {
		this.date = date;
	}

	mobxDatasReset = () => {
		this.searchPanel.form = new WeaForm();
		if (this.searchPanel.value) {
			this.searchPanel.value = '';
		}
		if (this.searchPanel.condition.length > 0) {
			this.searchPanel.condition = [];
		}
		if (this.isPanelShow) {
			this.isPanelShow = false;
		}
	}

}
