import React from 'react'
import Modal from 'antd/lib/Modal';
import MSG from '../../utils/msgsub';
import { ActionProps } from '../../../Action';
import { RendererEnv } from '../../../../env';

interface LoginAmazonPageProps {
  env: RendererEnv;
  action: ActionProps;
  ctx: any;
}

class LoginAmazonPage extends React.Component<LoginAmazonPageProps, {}> {

  state = {

  }

  handleParams = () => {

    const { action, ctx, env } = this.props;

    const { schemaApi } = action;

    const iHeight: number = 800;
    // https://sellercentral.amazon.com/apps/authorize/consent?state=loginAmazonKey&application_id=amzn1.sp.solution.237e541c-022e-42db-b5c2-9e6700a457b3&version=betahttps://saasdev.fastlion.cn/saas_dev/schema-app.html

    const iWidth: number = (document?.documentElement?.clientHeight || document?.body?.clientHeight) - 30;

    const iTop: number = (window.screen.height - iHeight) / 2;

    const iLeft: number = (window.screen.width - iWidth - 10) / 2;

    const config: string = `toolbar=no,menubar=no,scrollbars=auto,resizeable=no,location=no,status=no,height=${iHeight},width=${iWidth}top=${iTop},left=${iLeft}`;

    env?.fetcher(schemaApi as any, ctx).then((res: any) => {
      if (res?.ok && res?.status === 0) {
        let sellerUrl: string = res?.data?.sellerUrl ? res?.data?.sellerUrl : '';
        let _redirectUri: string = `redirect_uri=` + location.origin + location.pathname;
        let _applicationId: string = `application_id=${res?.data?.applicationId ? res?.data?.applicationId : ''}`;
        let state: string = JSON.stringify({ ...ctx, api: res?.data?.api, _hash: location.hash });
        let stateKey: string = 'loginAmazonKey';
        localStorage.setItem(stateKey, state);
        const _sellerUrl: string = sellerUrl + '?' + `state=${stateKey}` + '&' + _applicationId + '&' + 'version=beta' + '&' + _redirectUri;
        window._opener = window.open(_sellerUrl, "_blank", config);
      } else {
        MSG._error('系统异常，授权信息确认失败，清稍候再试', env?.getModalContainer);
        return
      }
    })
  }

  componentDidMount() {
    const { env } = this.props;
    try {
      if (!window?._opener || window?._opener?.closed) {
        this.handleParams()
      }
      // else if (window.origin === window?._opener?.origin) {
      //   window._opener.focus()
      // }
      else {
        window._opener.focus()
      }
    } catch (err) {
      MSG._info('已有被打开的授权窗口,请先关闭该窗口或完成授权', env?.getModalContainer)
    }
  }

  render() {
    return null
  }
}


const LionLoginAmazon = (action: any, ctx: any, env: any) => {
  const modal = Modal.info({
    className: "lion-wrapper-export",
    getContainer: env?.getModalContainer as any,
    mask: false,
    maskClosable: true
  })

  modal.update({
    content: <LoginAmazonPage env={env} action={action} ctx={ctx} />
  })
}
export {
  LionLoginAmazon
}
