import { Model, routerRedux } from "dva";
import _ from 'lodash';
import { PageState } from '@/types/common';
import { message } from 'antd';
import { formatMessage } from 'umi-plugin-locale';
import { validPwd } from '@/utils/validate';
import { changeLgpwd } from './service';

export interface LgpwdModelState {
  origin: string;
  newPwd: string;
  confirm: string;
  submitting: boolean;
}

const initState: LgpwdModelState = {
  origin: '',
  newPwd: '',
  confirm: '',
  submitting: false,
};

const model: Model = {
  namespace: 'lgpwd',

  state: initState,

  effects: {
    *load(_, { put, call }) {
      yield put({
        type: 'onUpdateState',
        origin: '',
        newPwd: '',
        confirm: '',
        submitting: false,
      });
    },

    *submit(_, { put, call, select }) {
      const {
        origin,
        newPwd,
        confirm,
        submitting,
      } = (yield select((state: any) => state.lgpwd)) as LgpwdModelState;
      if (submitting) return;
      if (!origin) return message.warn(formatMessage({ id: 'lgpwd.originPrompt' }))
      if (!validPwd(newPwd)) return message.warn(formatMessage({ id: 'check.msgPwd' }));
      if (confirm !== newPwd) return message.warn(formatMessage({ id: 'check.msgConfirm' }));
      yield put({ type: 'onUpdateState', submitting: true });
      try {
        yield call(changeLgpwd, newPwd, origin);
        yield put({ type: 'user/logout' });
        message.success(formatMessage({ id: 'lgpwd.success' }));
      } catch (e) {
        message.error(e.message);
      } finally {
        yield put({ type: 'onUpdateState', submitting: false })
      }
    },
  },

  reducers: {
    onUpdateState(state, payload) {
      return {
        ...state,
        ...payload,
      };
    },
  },
};

export default model;
