import {
	observable,
	action,
	computed
} from 'mobx';
import {
	WeaLocaleProvider
} from 'ecCom';
import {
	message,
	Button
} from 'antd';
import {
	DialogStore,
	FormStore
} from './domain/index.js'
import {
	RSAEcrypt
} from "../util/RSAUtil";
import * as api from '../apis/finance.js';
const getLabel = WeaLocaleProvider.getLabel;

export default class FinanceExpand {
	constructor(callback) {
		this.callback = callback;
	}

	@observable dialogStore = new DialogStore();
	@observable formStore = new FormStore(api);

	@observable isNeedSecondPwdVerify = true;
	@observable isNeedSecondPwdSet = false;

	@observable loading = true;

	@computed get dialogButtons() {
		const {
			loading
		} = this.formStore;
		return (
			[<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@2nm1e2@1`} type='primary' onClick={this.confirm} disabled={loading}>{getLabel(826,'确定')}</Button>]
		)
	}

	confirm = () => {
		const {
			validateForm,
			form
		} = this.formStore;

		validateForm(form).then(isValid => {
			if (isValid) {
				this.getPasswordSetting().then(() => {
					const params = this.formStore.form.getFormParams();
					RSAEcrypt(this.openRSA, params).then(RSAParam => {
						this.checkSecondPasword(RSAParam).then(isPass => {
							if (isPass === '1') {
								this.dialogStore.closeDialog();
								this.isNeedSecondPwdVerify = false;

								this.callback && this.callback();
							}
						});
					})
				})
			}
		})
	}

	checkSecondPasword = (params) => {
		const {
			form
		} = this.formStore;
		return api.checkSecondPasword(params).then(datas => {
			const {
				status,
				message
			} = datas;
			if (status === '-1') {
				form.showError('secondpassword',message)
			}
			return status;
		});
	}

	fetchSecondPwdVerifyInfo = () => {
		this.loading = true;

		return api.isNeedSecondPwdVerify().then(datas => {
			const {
				isNeedSecondPwdVerify
			} = datas;
			this.isNeedSecondPwdVerify = isNeedSecondPwdVerify;
			this.loading = false;
			return isNeedSecondPwdVerify;
		})
	}

	getPasswordSetting = () => {
		return new Promise( (resolve,reject) => {
			api.getPasswordSetting({id:""}).then(res => {
				if (res) {
					this.openRSA = res.openRSA;
					resolve();
				}else{
					reject();
				}
			})
		})
	}

	openDialog = () => {
		const dialogConfig = {
			style: {
				width: 500,
				height: 140,
			},
			title: getLabel(501195, '身份验证'),
			buttons: this.dialogButtons,
		}


		const formConfig = {
			searchGroupProps: {
				col: 1,
			}
		}

		this.dialogStore.setDialogConfig(dialogConfig).openDialog();
		this.formStore.setFormConfig(formConfig).fetchForm({},(datas)=>{
			this.isNeedSecondPwdSet =!datas.settedSecondPassword;
		});
	}

	resetParams = () => {
		this.isNeedSecondPwdVerify = true;
	}

}