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

const getLabel = WeaLocaleProvider.getLabel;

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

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

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

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

  /**
   * 获取右键菜单
   * @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 [
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@y4h5b9@integrationauthDelegateButtonSaveBtn`} type="primary" onClick={() => this.onRightMenuClick('BTN_BASE_SAVE')}>{getLabel(30986, '保存')}</Button>,
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@y4h5b9@integrationauthDelegateButtonTestBtn`} type="primary" onClick={() => this.onRightMenuClick('BTN_TEST')}>{getLabel(25496, '测试')}</Button>
    ]
  };

  /**
   * 右键菜单点击事件
   * @param type
   */
  onRightMenuClick = (type) => {
    const { authenticationCenterStore } = this.props;
    const { newForm } = authenticationCenterStore;
    
    IntegrationUtil.onCheck(newForm, () => {
      let params = newForm.getFormParams();
      delete params.isuse;
      delete params.token_isuse;
      delete params.oauth2_isuse;
      delete params.spnego_isuse;

      if (type == "BTN_BASE_SAVE") {
        params.method = 'weaversso';

        if(params.dlgt_isuse == "1") {
          authenticationCenterStore.getBaseInfoFormOperation({casserverurl: params.loginurl || "", method: 'test', testBeforeSave: true}, (result) => {
            if(result.success) {
              if(params.dlgt_ec_isuse == '1') {
                IntegrationUtil.doConfirm(
                  getLabel('529602','经检测，需要同时开启Delegate集成（会重新生成Delegate集成配置），保存后将自动重启服务，若有失败，请手动重启服务，以确保系统能正常使用！'),
                  authenticationCenterStore.getBaseInfoFormOperation,
                  params,
                )
              } else {
                authenticationCenterStore.getBaseInfoFormOperation(params);
              }
            }
          });
        } else {
          if(params.dlgt_ec_isuse == '1') {
            IntegrationUtil.doConfirm(
              getLabel('529601','经检测，需要同时关闭Delegate集成，保存后将自动重启服务，若有失败，请手动重启服务，以确保系统能正常使用！'),
              authenticationCenterStore.getBaseInfoFormOperation,
              params
            )
          } else {
            authenticationCenterStore.getBaseInfoFormOperation(params);
          }
        }
      } else if ("BTN_TEST" === type) {
        params = {
          method: 'test',
          casserverurl: params.loginurl || "",
        };
        authenticationCenterStore.getBaseInfoFormOperation(params);
      }
    });
  };

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

    isFormInit && BaseInfoFormFields && BaseInfoFormFields.forEach(c =>{
      if(['delegate', 'desc'].includes(c.key)) {
        let items = [];
        c.items && c.items.forEach(fields => {
          items.push({
            com:(<div style={{margin: 'desc' == c.key ? "0 -20px" : "0 0"}}>
              <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@p0mz2x@integrationauthDelegateForm${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@a6y53g@integrationauthDelegateForm${fields.domkey[0]}`} fieldConfig={fields} form={newForm} />
              </WeaFormItem>
            </div>),
            colSpan:1,
            hide: newForm.isHide(fields, (keys, allParams) => {
              let bool = false;
              !["delegate_desc_", "dlgt_isuse"].includes(fields.domkey[0]) && allParams.dlgt_isuse != '1' && (bool = true);
              return bool;
            })
          });
        });
        group.push(<WeaSearchGroup 
          ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@ib3tkg@integrationauthDelegateFormSearchs4`} 
          center={'desc' != c.key} 
          col={1} 
          needTigger={true} 
          title={c.title} 
          showGroup={c.defaultshow} 
          items={items}
        />
        );
      }
    });
    return group;
  }

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

    return (
      rightLoading 
        ? null 
        : hasRight
          ? <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@g45iys`}
              datas={this.getRightMenu()}
              collectParams={collectParams}
            >
              <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@93q1do`}
                title={getLabel('521345','Delegate认证')}
                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@hf3e3y`}/>
    );
  }
}

export default AuthenticationDelegate;
