import {inject, observer} from "mobx-react";
import {toJS} from "mobx";
import {Button} from "antd";
import {
  WeaFormItem, 
  WeaLocaleProvider, 
  WeaRightMenu, 
  WeaSearchGroup, 
  WeaTop,
  WeaNewScroll,
} from "ecCom";
import {WeaSwitch} from "comsMobx";
import NoRight from "../../public/NoRight";
import NonStand from '../../public/NonStand';
import {
  onCheck,
  setModalInfo,
  doConfirm,
} from "../../util/IntegrationUtil";
import AppEditDialog from "./AppEditDialog";
import "../../style/webxml.less";

const getLabel = WeaLocaleProvider.getLabel;

@inject("samlStore")
@observer
class Saml extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedKey: 0,
      visiable:false,
    };
  }

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

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

  /**
   * 按钮的显示和事件
   */
  onMenuClick = (type) => {
    const { 
      samlStore 
    } = this.props, { 
      form,
      getBaseInfoFormOperation,
    } = samlStore;

    if(["BTN_BASE_SAVE", "BTN_TEST"].includes(type)) {
      onCheck(form, () => {
        let params = form.getFormParams();
        if(type === "BTN_TEST") {
          params = Object.assign({}, params, {method: "deploy"});
        }
        if("BTN_TEST" === type) {
          if(params.pcauth == 1 || params.appauth == 1 || params.isuse != 1) {
            doConfirm(
              getLabel('522262','部署后将自动重启服务，若有失败，请手动重启服务，以确保系统能正常使用！'),
              getBaseInfoFormOperation,
              params,
            );
          } else {
            setModalInfo(getLabel(386921,'请开启pc认证或手机认证!'));
          }
        } else {
          getBaseInfoFormOperation(params);
        }
      });
    }
  };

  getBtns = (datas=[], disabled) => {
    const {
      samlStore
    } = this.props, {
      status
    } = samlStore, {
      isConfigured,
      isConfiguredDisabled,
    } = toJS(status);

    return datas && datas.map(data => <Button 
      ecId={`${this && this.props && this.props.ecId || ''}_Button@pi2lh7@integrationSamlButton${data.key}`} 
      disabled={data.key === "BTN_TEST" ? (disabled || (!(isConfigured && isConfiguredDisabled))) : disabled} 
      type={data.type} 
      key={data.key} 
      onClick={() => this.onMenuClick(data.key)}
    >{data.content}</Button>);
  };

  getRightMenu = (datas=[], disabled) => {
    const {
      samlStore
    } = this.props, {
      status
    } = samlStore, {
      isConfigured,
      isConfiguredDisabled,
    } = toJS(status);

    return datas && datas.map(data => {
      return {
        ...data,
        disabled: data.key === "BTN_TEST" ? (disabled || (!(isConfigured && isConfiguredDisabled))) : disabled,
        content: data.content,
        onClick: () => this.onMenuClick(data.key)
      }
    })
  }

  handleConfigLink = (type="") => {
    const {
      samlStore
    } = this.props, {
      getDetailInfoForm,
      getConfigurationResult
    } = samlStore;
    if(type === "test") {
      getConfigurationResult();
    }else {
      getDetailInfoForm();
    }
    samlStore.setState({
      appEditDialogVisible: true,
      editTab: type || 'edit'
    });
  }

  getForm = (form, datas=[]) => {
    const {
      isFormInit
    } = form, {
      samlStore
    } = this.props, {
      status,
      checkIsConfigured,
    } = samlStore, {
      isConfigured
    } = toJS(status);
    const formParams = form.getFormParams();
    let group = [];
    isFormInit && datas && datas.forEach((c, index) => {
      let items = [], center = (datas.length - 1 === index), left = (datas.length - 1 === index) ? "-20px" : 0;
      c && c.items && c.items.forEach(fields => {
        items.push({
          com: (<div style={{marginLeft: left}}>
            <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@0btvku@integrationSamlForm${fields.domkey[0]}`}
              label={fields.label}
              labelCol={{span: `${center ? "0" : fields.labelcol}`}}
              wrapperCol={{span: `${center ? "24" : fields.fieldcol}`}}
              error={form.getError(fields)}
              tipPosition="bottom"
            >
              {
                fields.domkey[0] === "config_link"
                  ? <nobr>
                      <span onClick={() => this.handleConfigLink('edit')} dangerouslySetInnerHTML={{__html: fields.value}} />
                      {
                        isConfigured
                          ? <div style={{display: "inline-block"}}>
                              <span style={{color: "green", margin: "0 10px 0 5px"}}>√</span>
                              <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@1dpxxb@integrationSamlForm${fields.domkey[0]}`} size="small" onClick={() => this.handleConfigLink('test')}>{getLabel('517235','SAML配置检查')}</Button>
                            </div>
                          : null 
                      }
                    </nobr>
                  : <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@jtw1zs@integrationSamlForm${fields.domkey[0]}`} fieldConfig={fields} form={form} formParams={formParams} onChange={() => {
                      if(fields.domkey[0] === "isuse") {
                        checkIsConfigured();
                      }
                    }} />
              }
            </WeaFormItem>
          </div>),
          colSpan: 1,
          hide: form.isHide(fields, (keys, allParams) => {
            let bool = false, key = fields.domkey[0];
            ["cfg_dir", "config_link"].includes(key) && allParams.isuse != '1' && (bool = true);
            fields && fields.showWhere && fields.showWhere.length > 0 && fields.showWhere.forEach(w => {
              if(!bool){
                let show = false;
                for(let val of w.value){
                  if(allParams[w.domkey] == val){
                      show = true;
                      break;
                  }
                }
                bool = !show;
              }
            })
            return bool;
          })
        });
      })
      if(formParams.isuse == '1' || (formParams.isuse != '1' && (index === 0 || index === datas.length - 1))) {
        group.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@f6gk72@integrationSamlForm${index}`} col={1} center={!center} needTigger={true} title={c.title} showGroup={c.defaultshow} items={items}/>)
      }
    });
    return group;
  }

  render() {
    const { 
      samlStore 
    } = this.props, {
      status,
      hasRight, 
      form
    } = samlStore, {
      condition,
      loading,
      collectParams,
      menus,
      buttonStatus,
      nonStandLoading,
      hasNonStandard
    } = toJS(status);

    return (nonStandLoading
      ? null
      : hasNonStandard
        ? loading 
          ? null
          : hasRight
            ? <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@dwtnd2`}
                className={"inte-webxml-rightmenu"}
                datas={this.getRightMenu(menus, buttonStatus)}
                collectParams={collectParams}
              >
                <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@2g5cz3`}
                  title={getLabel('516650','SAML集成')}
                  icon={<i className="icon-coms-integration" />}
                  iconBgcolor="#1a57a0"
                  buttons={this.getBtns(menus, buttonStatus)}
                  showDropIcon={true}
                  dropMenuDatas={this.getRightMenu(menus, buttonStatus)}
                  dropMenuProps={{collectParams}}
                />
                <WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@a2wnsf`} height={"calc(100% - 47px)"}>
                  {this.getForm(form, condition)}
                </WeaNewScroll>
                <AppEditDialog ecId={`${this && this.props && this.props.ecId || ''}_AppEditDialog@w0rszy`}/>
              </WeaRightMenu>
            : <NoRight ecId={`${this && this.props && this.props.ecId || ''}_NoRight@mzymuh`}/>
        : <NonStand ecId={`${this && this.props && this.props.ecId || ''}_NonStand@skk7gu`} />
    );
  }
}

export default Saml;
