import {inject, observer} from "mobx-react";
import {toJS} from "mobx";
import {Button} from "antd";
import {WeaFormItem, WeaLocaleProvider, WeaRightMenu, WeaSearchGroup, WeaTop, WeaTools} from "ecCom";
import {WeaSwitch} from "comsMobx";
import NoRight from "../../public/NoRight";
import NonStand from "../../public/NonStand";
import * as IntegrationUtil from "../../util/IntegrationUtil";
import PopoverButton from '../../public/PopoverButton';
import "../../style/webxml.less";

const { getKey } = WeaTools;
const getLabel = WeaLocaleProvider.getLabel;

@inject("authenticationCenterStore")
@observer
class AuthenticationCenter extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      visiable:false,
      collectParams: {
        favname: getLabel('518323','OAuth2认证'),
        favouritetype: 1,
        objid: 0,
        link: "wui/engine.html#/integration/oauth2_server",
        importantlevel: 1
      }
    };
  }

  componentDidMount() {
    const { authenticationCenterStore } = this.props;
    authenticationCenterStore.doInit("oauth2");
  }

  componentWillUnmount() {
    this.props.authenticationCenterStore.clearStore();
  }

  componentWillReceiveProps(nextProps) {
    const { authenticationCenterStore } = this.props;
    if (this.props.location.key !== nextProps.location.key) {
      authenticationCenterStore.doInit("oauth2");
    }
  }

  /**
   * 获取右键菜单
   * @returns {Array}
   */
  getRightMenu = () => {
    return [{
      key: "BTN_BASE_SAVE",
      icon: <i className="icon-coms-Preservation" />,
      content: getLabel(30986, '保存'),
      onClick: () => this.onRightMenuClick("BTN_BASE_SAVE")
    }
    , {
      key: 'BTN_TEST',
      icon: <i className='icon-coms-currency-Task' />,
      content: `${getLabel(25496, '测试')}`,
      onClick: () => this.onRightMenuClick('BTN_TEST')
    }
   ]
  }

  /**
   * 获取顶部按钮
   * @returns {Array}
   */
  getBtns = () => {
    return [
      <PopoverButton ecId={`${this && this.props && this.props.ecId || ''}_PopoverButton@9zafap@integrationauthOauth2ButtonSaveBtn`} 
        content={getLabel(30986, '保存')}
        type="primary"
        onClick={() => this.onRightMenuClick("BTN_BASE_SAVE")}
      />,
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@juyi6s@integrationauthOauth2ButtonTestBtn`} type="primary" onClick={() => this.onRightMenuClick('BTN_TEST')}>{getLabel(25496,'测试')}</Button>
    ]
  };

  /**
   * 右键菜单点击事件
   * @param type
   */
  onRightMenuClick = (type) => {
    const { authenticationCenterStore } = this.props;
    const { newForm } = authenticationCenterStore;
  
    if (type == "BTN_BASE_SAVE") {
      IntegrationUtil.onCheck(newForm,()=>{
        let params = Object.assign({}, newForm.getFormParams(), {method: 'weaversso'});
        delete params.isuse;
        delete params.token_isuse;
        delete params.spnego_isuse;
        delete params.dlgt_isuse;
        if(params.oauth2_isuse == "1") {
          authenticationCenterStore.getBaseInfoFormOperation({oauth2_heartbeat_url: params.oauth2_heartbeat_url, method: 'oauth2_test', testBeforeSave: true}, (result) => {
            if(result.success) {
              if(params.oauth2_client_isuse == '1') {
                IntegrationUtil.doConfirm(
                  getLabel('521937','经检测，需要同时开启OAuth2集成（会重新生成OAuth2集成配置），保存后将自动重启服务，若有失败，请手动重启服务，以确保系统能正常使用！'),
                  authenticationCenterStore.getBaseInfoFormOperation,
                  params,
                )
              } else {
                authenticationCenterStore.getBaseInfoFormOperation(params);
              }
            }
          });
        }else {
          if(params.oauth2_client_isuse == '1') {
            IntegrationUtil.doConfirm(
              getLabel('521939','经检测，需要同时关闭OAuth2集成，保存后将自动重启服务，若有失败，请手动重启服务，以确保系统能正常使用！'),
              authenticationCenterStore.getBaseInfoFormOperation,
              params
            )
          } else {
            authenticationCenterStore.getBaseInfoFormOperation(params);
          }
        }
      });
    }else if(type == "BTN_TEST") {
      let loginurl = newForm.getFormParams().oauth2_heartbeat_url;
      let params = {oauth2_heartbeat_url: loginurl, method: 'oauth2_test'};
      authenticationCenterStore.getBaseInfoFormOperation(params);
    }
  };

  getBaseInfoForm = () => {
    const {authenticationCenterStore} = this.props;
    const {newForm, status} = authenticationCenterStore;
    const {BaseInfoFormFields} = toJS(status);
    const {isFormInit} = newForm;
    let group = [];
    const formParams = newForm.getFormParams();

    isFormInit && BaseInfoFormFields && BaseInfoFormFields.map((c, index) =>{
      if(index == 2) {
        let items = [];
        c.items && c.items.map(fields => {
          items.push({
            com:(
              <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@0w4975@integrationauthOauth2Form${fields.domkey[0]}`}
                  label={`${fields.label}`}
                  labelCol={{span: `${fields.labelcol}`}}
                  wrapperCol={{span: `${fields.fieldcol}`}}
                  error={newForm.getError(fields)}
                  tipPosition="bottom"
              >
                  <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@tve9nr@integrationauthOauth2Form${fields.domkey[0]}`} fieldConfig={fields} form={newForm} formParams={formParams}  onChange={v=> {}} />
              </WeaFormItem>),
            colSpan:1,
            hide: newForm.isHide(fields, (keys, allParams) => {
              let bool = false;
              getKey(fields) != 'oauth2_isuse' && allParams.oauth2_isuse != '1' && (bool = true);
              return bool;
            })
          });
        });
        group.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@j8uqi9@integrationauthOauth2Form${index}`} center  col={1}  needTigger={false} title={""}  showGroup={c.defaultshow} items={items}/>);
      }
    });
    return group;
  }

  render() {
    const {authenticationCenterStore} = this.props;
    const {hasRight, rightLoading, status} = authenticationCenterStore;
    const {hasNonStandard, nonStandLoading} = toJS(status);
    const {collectParams} = this.state;

    return (nonStandLoading
      ? null
      : hasNonStandard
        ? rightLoading 
          ? null 
          : hasRight
            ? <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@sse454`}
                className={"inte-webxml-rightmenu"}
                datas={this.getRightMenu()}
                collectParams={collectParams}
              >
                <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@lk5y0e`}
                  title={getLabel('518323','OAuth2认证')}
                  icon={<i className="icon-coms-integration" />}
                  iconBgcolor="#1a57a0"
                  buttons={this.getBtns()}
                  showDropIcon={true}
                  dropMenuDatas={this.getRightMenu()}
                  dropMenuProps={{collectParams}}
                >
                  {this.getBaseInfoForm()}
                </WeaTop>
              </WeaRightMenu>
            : <NoRight ecId={`${this && this.props && this.props.ecId || ''}_NoRight@0xibbm`}/>
        : <NonStand ecId={`${this && this.props && this.props.ecId || ''}_NonStand@vs9ghk`} />
    );
  }
}

export default AuthenticationCenter;
