import Request from '@ywfe/request';
import {configs} from '@/generated/config';
import {
  useGetUserLogout,
  usePostUserUpdatepasswd,
  usePostUserLogin,
  UserLoginInput,
  UserLoginData,
  usePostUserSendmtcode,
  UserSendmtcodeInput,
  usePostUserUpdatepasswdbymtcode,
  UserUpdatepasswdbymtcodeInput,
  useGetProjectList
} from '@/generated/api';
import {useAuthStore} from './useStore';

interface ChangePasswordProps {
  oldPasswd: string;
  newPasswd: string;
}

export const useModel = () => {
  const [state, dispatch] = useAuthStore();
  const { getUserLogoutData } = useGetUserLogout();
  const { postUserUpdatepasswdData } = usePostUserUpdatepasswd();
  const { postUserLoginData } = usePostUserLogin();
  const { postUserSendmtcodeData } = usePostUserSendmtcode();
  const { postUserUpdatepasswdbymtcodeData } = usePostUserUpdatepasswdbymtcode();

  const login = async (values: UserLoginInput): Promise<UserLoginData> => {
    const res = await postUserLoginData({
      ...values,
      projectId: 'PROAUTH',
    });
    if (res) {
      dispatch({
        type: "login",
        payload: {
          data: {
            userName: res.userName,
            token: res.userToken,
          },
        },
      });
    }
    return res || {};
  };

  const loginout = async (): Promise<boolean> => {
    const res = await getUserLogoutData();
    if (res) {
      dispatch({
        type: "logout",
        payload: {
          data: {},
        },
      });
    }
    return res ? true : false;
  };

  const changePassword = async ({
    oldPasswd,
    newPasswd,
  }: ChangePasswordProps): Promise<boolean> => {
    const res = await postUserUpdatepasswdData({
      oldPasswd,
      newPasswd,
    });
    if (res) {
      dispatch({
        type: 'change password',
        payload: {
          data: {},
        },
      });
    }
    return res ? true : false;
  };

  const updatePasswordByMtCode = async ({telephone, passWd, mtCode}: UserUpdatepasswdbymtcodeInput) => {
    const res = await postUserUpdatepasswdbymtcodeData({
      telephone,
      passWd,
      mtCode
    });
    if(res){
      dispatch({
        type: 'change password',
        payload: {
          data: {},
        },
      });
    }
    return res ? true : false;
  }

  const switchAuthType = (authType: string) => {
    dispatch({
      type: "switch auth type",
      payload: {
        data: {
          authType
        },
      },
    });
  }

  const sendCode = async (data: UserSendmtcodeInput) => {
    const res = await postUserSendmtcodeData(data)
    return res;
  }

  const getDingCode = async () => {
    const projectId = "DING_TALK";
    let env;
    if(typeof window === 'undefined'){
      env = (process.env.REACT_APP_ENV === 'prod' ? 'prod': process.env.REACT_APP_ENV) || 'dev';
    } else {
      env = window.localStorage.getItem('env') || (process.env.REACT_APP_ENV === 'prod' ? 'prod': process.env.REACT_APP_ENV) || 'dev';
      const dingCbUrl = configs[projectId][env]['DING_CB_URL'];
      const dingAppId = configs[projectId][env]['DING_APPID'];

      const pageUrl = window.location.href
      const urlParams = pageUrl.indexOf('?') !== -1 ? pageUrl.slice(pageUrl.indexOf('?'),) : ''
      const url = encodeURIComponent(`${dingCbUrl}${urlParams}`);
      const gotoUrl = `https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=${dingAppId}&response_type=code&scope=snsapi_login&state=STATE&redirect_uri=${url}`
      // @ts-ignore
      window.DDLogin && window.DDLogin({
        id: 'login_container', // 这里需要你在自己的页面定义一个HTML标签并设置id，例如<div id="login_container"></div>或<span id="login_container"></span>
        goto: encodeURIComponent(gotoUrl), // 请参考注释里的方式
        style: 'border:none;background-color:#FFFFFF;margin-top:-40px;text-align: center;',
        width: '240',
        height: '250',
      });

      const handleMessage = (event:any) => {
        const { origin } = event;
        if (origin === 'https://login.dingtalk.com') { // 判断是否来自ddLogin扫码事件。
          const loginTmpCode = event.data;
          // 获取到loginTmpCode后就可以在这里构造跳转链接进行跳转了
          window.location.href = `${gotoUrl}&loginTmpCode=${loginTmpCode}`
        }
      };
      if (typeof window.addEventListener !== 'undefined') {
        window.addEventListener('message', handleMessage, false);
        // @ts-ignore
      } else if (typeof window.attachEvent !== 'undefined') {
        // @ts-ignore
        window.attachEvent('onmessage', handleMessage);
      }
    }
  }

  const getUserName = () => {
    let userName = ''
    if(typeof window !== 'undefined'){
      userName = state.userName || window.localStorage.getItem('userName') || '';
    } else {
      userName = state.userName || '';
    }
    return userName
  }

  return {
    login,
    loginout,
    changePassword,
    updatePasswordByMtCode,
    switchAuthType,
    sendCode,
    getDingCode,
    userName: getUserName()
  };
};
