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

export interface FundpwdModelState {
  pageState: PageState;
  originVisible: boolean;

  origin: string;
  newPwd: string;
  confirm: string;
  submitting: boolean;
}

const initState: FundpwdModelState = {
  pageState: PageState.Pending,
  originVisible: false,

  origin: '',
  newPwd: '',
  confirm: '',
  submitting: false,
};

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

  state: initState,

  effects: {
    *load(_, { put, call }) {
      yield put({ type: 'onUpdateState', pageState: PageState.Pending });
      try {
        const settled = yield call(checkFundPwd);
        yield put({
          type: 'onUpdateState',
          pageState: PageState.Success,
          originVisible: settled,
          origin: '',
          newPwd: '',
          confirm: '',
          submitting: false,
        });
      } catch (e) {
        yield put({
          type: 'onUpdateState',
          pageState: PageState.Failure,
        });
      }
    },

    *submit(_, { put, call, select }) {
      const {
        originVisible,
        origin,
        newPwd,
        confirm,
        submitting,
      } = (yield select((state: any) => state.fundpwd)) as FundpwdModelState;
      if (submitting) return;
      if (originVisible && !origin) return message.warn(formatMessage({ id: 'fundpwd.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(changeFundPwd, newPwd, originVisible ? origin : undefined);
        yield put(routerRedux.goBack());
        message.success(formatMessage({ id: 'fundpwd.success' }));
      } catch (e) {
        message.error(e.message);
      } finally {
        yield put({ type: 'onUpdateState', submitting: false })
      }
    },
  },

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

export default model;
