import {
	observable,
	action,
	computed
} from 'mobx';
import {
	WeaSwitch,
	WeaTools
} from 'comsMobx';
import {
    WeaLocaleProvider,
} from 'ecCom';
import {
	Button,
	message
} from 'antd';
import * as api from '../apis/secondaryVerify';
import HrmBaseStore from './baseStore';
import {
	i18n
} from '../public/i18n';
import Resend from '../components/secondaryVerifyCom/Resend';
import {addContentPath} from '../util/index.js'
const getLabel = WeaLocaleProvider.getLabel;

export class HrmSecondaryVerifyCom extends HrmBaseStore {
	/********************* unobservable list *********************/
	dialogId;
	secondAuthType;
	verifyType;//10: 动态密码 20: 动态令牌 30: 二次密码密码 40: CA扫码登录
	checkCAAuthTimer;
	loginkey;

	get topBtnAndMenu(){
		let btns = [
			<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@dbq9d7@1`} type='primary' op='save' onClick={this.doSecondAuth}>{i18n.button.ok()}</Button>,
		];
		// let menus = [];
		// btns.map((btn, index) => {
		// 	const {
		// 		props
		// 	} = btn;
		// 	menus.push({
		// 		key: index.toString(),
		// 		content: props.children,
		// 		icon: <i className={this.menuIconCollection[props.op]}/>,
		// 		onClick: props.onClick
		// 	});
		// })
		return {
			btns,
			// menus: [...menus, ...this.getBasicMenus()]
		}
	}

	t = -1;

	get notSetSecondary(){
		let label = getLabel('514970','您还未设置二次验证密码，点击{param}');
		label = label.replace('{param}', `<a href=${addContentPath('/wui/index.html#/main/hrm/password?tabKey=2')} target='_blank'>${getLabel('30747','设置')}</a>`);
		return label;
	}

	itemRender = {
		authCode: (field, textAreaProps, form, formParams) => {
			return (
				<div>
					{
						this.verifyType != 40 && 
						<div style={{width: 300}}>
							<div style={{float: 'left', width: 200}}>
								<WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@6zstuu`} fieldConfig={{...field, ...textAreaProps}} 
									form={form} formParams={formParams} />
							</div> 
							{
								this.verifyType == 10  &&
								<Resend ecId={`${this && this.props && this.props.ecId || ''}_Resend@dvoaed`} store={this} />
							}
						</div>
					}
					{
						this.verifyType == 30 && this.notSetting &&
						<div style={{clear: 'both', paddingTop: 10}} dangerouslySetInnerHTML={{__html: this.notSetSecondary}}>
							{/* 您还未设置二次验证密码，点击<a href='/wui/index.html#/main/hrm/password?tabKey=2' target='_blank'>设置</a> */}
						</div>
					}
				</div>
			)
		}
	}

	childrenComponents = {
		// authCode: () => {
		//   return [
		// 	{
		// 	  com: <div className="times">123123</div>,
		// 	  col: 1
		// 	}
		//   ];
		// }
	};
	/********************* unobservable list *********************/

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

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

	/********************* observable list *********************/
	@observable spinning = false;
	@observable sendBtnLabel = '';
	@observable showTimeout = false;
	@observable notSetting = false;
	@observable _qrCode = {};

	@computed get qrCode(){
		return this.toJS(this._qrCode);
	}

	set qrCode(qrCode){
		this._qrCode = qrCode;
	}
	/********************* observable list *********************/

	/********************* computed list *********************/
	/********************* computed list *********************/

	/********************* action list *********************/
	@action init = (dialogId, authType) => {
		this.dialogId = dialogId;
		authType && this.getSecondAuthForm(authType);
	}

	//是否在免密时间内
	@action getSecondAuthFreeTime = () => {
		api.getSecondAuthFreeTime().then(data => {
			console && console.debug('getSecondAuthFreeTime', data);
		});
	}

	//获取二次验证表单
	@action getSecondAuthForm = authType => {
		if(this.spinning)
			return;
		this.spinning = true;
		api.getSecondAuthForm({secondAuthType: authType}).then(data => {
			if(data.status == '1'){
				this.verifyType = data.authType;
				if(this.verifyType == -1){

				}else if(this.verifyType != 40){
					const fields = [{title: '', defaultshow: true, items: data.conditions}];
					this.setFormData('verifyForm', fields);
					if(this.verifyType == 10){
						this.getSecDynamicPassword(true);
					}
					this.notSetting = data.notSetting || false;
				}else{
					this.qrCode = data.qrcode;
					this.loginkey = data.loginkey;
					this.startCheckCAAuthTimer();
				}
			}else{
				message.error(data.message);
			}
			this.spinning = false;
		});
	}

	@action startCheckCAAuthTimer = () => {
		this.checkCAAuthTimer && clearInterval(this.checkCAAuthTimer);
		this.checkCAAuthTimer = setInterval(() => {
			api.doSecondAuth({authType: this.verifyType, authCode: this.loginkey || ''}).then(data => {
				if(data.api_status){
					clearInterval(this.checkCAAuthTimer);
					this.closeDialog('success');
				}
			})
		}, 1000);
	}

	//二次验证
	@action doSecondAuth = () => {
		if(this.spinning || this.verifyType == 40)
			return;
		this.spinning = true;

		this.formTarget.verifyForm.validateForm().then(f => {
			if (f.isValid) {
				const formData = this.formTarget.verifyForm.getFormParams();
				const params = {
					authType: this.verifyType,
					authCode: formData.authCode
				}
				api.doSecondAuth(params).then(data => {
					if(data.status == '1'){
						if(!data.api_status){
							f.showError('authCode', data.api_errormsg);
						}else{
							this.closeDialog('success');
						}
					}else{
						message.error(data.message );
					}
					this.spinning = false;
				});
			} else {
				this.spinning = false;
				f.showErrors();
				this.showError = new Date().getTime();
			}
		});
	}

	//获取动态密码
	@action getSecDynamicPassword = (init = false) => {
		if(init || this.showTimeout){
			api.getSecDynamicPassword().then(data => {
				if(data.status == '1'){
					this.initTimer(data.validSecond);
				}else{
					message.error(data.message);
				}
			});
		}
	}

	@action closeDialog = flag => {
		let dialog = null;
		if(this.dialogId){
			dialog = window.top.getParentDialog();//WeaTools.getDialog(this.dialogId);
		}
		if(dialog){
			dialog.callback && dialog.callback(flag);
			dialog.close();
		}
	}

	@action initTimer = seconds => {
		this.t = seconds;
		this.sendBtnLabel = `${this.t}s`;
		this.showTimeout = false;
		this.checkTimer = setInterval(() => {
			this.sendBtnLabel = `${(--this.t).toString()}s`;
			if(this.t === 0){
				this.showTimeout = true;
				this.sendBtnLabel = i18n.button.resend();
				clearInterval(this.checkTimer);
			}
		}, 1000);
	}

	@action doCancel = () => {
		this.closeDialog('failed');
	}

	@action resend = () => {
		this.getSecondAuthForm(40);
	}

	@action clearTimer = () => this.checkCAAuthTimer && clearInterval(this.checkCAAuthTimer);
	/********************* action list *********************/
}

export const hrmSecondaryVerifyCom = new HrmSecondaryVerifyCom();