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('516737','CAS认证'),
        favouritetype: 1,
        objid: 0,
        link: "wui/engine.html#/integration/authenticationcenter",
        importantlevel: 1
      }
    };
  }

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

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

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

  /**
   * 右键菜单点击事件
   * @param type
   */
  onRightMenuClick = (type) => {
    const { authenticationCenterStore } = this.props;
    const { newForm } = authenticationCenterStore;
    const {BaseInfoFormHiddenFields} = toJS(authenticationCenterStore.status);
    if (type == "BTN_BASE_SAVE") {
      IntegrationUtil.onCheck(newForm,()=>{
        let formParams = newForm.getFormParams();
        let params = Object.assign({}, formParams, {method: 'weaversso'});
        delete params.token_isuse;
        delete params.oauth2_isuse;
        delete params.spnego_isuse;
        delete params.dlgt_isuse;
        let isOpenCas = BaseInfoFormHiddenFields.isOpenCas;

        // 开启需要检测是否通过
        if(params.isuse == "1") {
          authenticationCenterStore.getBaseInfoFormOperation({casserverurl: formParams.loginurl, method: 'test', testBeforeSave: true}, (result) => {
            if(result.success) {
              if(isOpenCas) {
                if(newForm.getFormParams().isuse=="1"){      
                  authenticationCenterStore.confirmModal(`${getLabel(382221 ,'经检测，需要同时开启CAS客户端，保存后将自动重启服务，若有失败，请手动重启服务，以确保系统能正常使用！')}`, authenticationCenterStore.getBaseInfoFormOperation , params);
                }else{
                  authenticationCenterStore.confirmModal(`${getLabel(382222 ,'经检测，需要同时关闭CAS客户端，保存后将自动重启服务，若有失败，请手动重启服务，以确保系统能正常使用！')}`, authenticationCenterStore.getBaseInfoFormOperation , params);
                }
              }else{
                IntegrationUtil.doConfirm(getLabel('512788','保存后将自动重启服务，若有失败，请手动重启服务，以确保系统能正常使用！'), authenticationCenterStore.getBaseInfoFormOperation , params);
              }
            }
          });
        }else {
          if(isOpenCas) {
            if(newForm.getFormParams().isuse=="1"){
              authenticationCenterStore.confirmModal(`${getLabel( 382221 ,'经检测，需要同时开启CAS客户端，保存后将自动重启服务，若有失败，请手动重启服务，以确保系统能正常使用！')}`, authenticationCenterStore.getBaseInfoFormOperation , params);
            }else{
              authenticationCenterStore.confirmModal(`${getLabel( 382222 ,'经检测，需要同时关闭CAS客户端，保存后将自动重启服务，若有失败，请手动重启服务，以确保系统能正常使用！')}`, authenticationCenterStore.getBaseInfoFormOperation , params);
            }
          }else{
            IntegrationUtil.doConfirm(getLabel('512788','保存后将自动重启服务，若有失败，请手动重启服务，以确保系统能正常使用！'), authenticationCenterStore.getBaseInfoFormOperation , params);
          }  
        }
      });
    }else if(type == "BTN_TEST") {
      let loginurl = newForm.getFormParams().loginurl;
      let params = {casserverurl: loginurl, method: 'test'};
      authenticationCenterStore.getBaseInfoFormOperation(params);
    }
  };

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

  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 == 0) {
        let items = [];
        c.items && c.items.map(fields => {
          items.push({
            com:(
              <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@aqdyzp@integrationauthCasForm${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@qdreji@integrationauthCasForm${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) === 'loginurl' && allParams.isuse != '1' && (bool = true);
              getKey(fields) === 'logouturl' && allParams.isuse != '1' && (bool = true);
              getKey(fields) === 'oaadress' && allParams.isuse != '1' && (bool = true);
              return bool;
            })
          });
        });
        group.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@mygvm1@integrationauthCasForm${index}`} center  col={1}  needTigger={false} title={""}  showGroup={c.defaultshow} items={items}/>);
      }
    });
    return group;
  }

  render() {
    const {authenticationCenterStore} = this.props;
    const {hasRight, rightLoading, status: {hasNonStandard, nonStandLoading}} = authenticationCenterStore;
    const {collectParams} = this.state;
    return (
      nonStandLoading
        ? null
        : hasNonStandard
          ? rightLoading 
            ? null
            : hasRight 
              ? <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@utqtt4`}
                  className={"inte-webxml-rightmenu"}
                  datas={this.getRightMenu()}
                  collectParams={collectParams}
                >
                  <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@0ccpm0`}
                    title={getLabel('516737','CAS认证')}
                    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@1tx2rv`}/>
          : <NonStand ecId={`${this && this.props && this.props.ecId || ''}_NonStand@8hfmwi`}/>
    );
  }
}

export default AuthenticationCenter;
