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

const {getLabel} = WeaLocaleProvider;

@inject("delegateClientStore")
@observer
class DelegateClient extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      collectParams: {
        favname: getLabel('528480','Delegate集成'),
        favouritetype: 1,
        objid: 0,
        link: "wui/engine.html#/integration/delegate_client",
        importantlevel: 1
      }
    };
  }

  componentDidMount() {
    this.props.delegateClientStore.doInit();
  }

  componentWillUnmount() {
    this.props.delegateClientStore.cleanStore();
  }

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

  /**
   * 获取右键菜单
   * @returns {Array}
   */
  getRightMenu() {
    const {
      formLoading
    } = this.props.delegateClientStore.status;

    return [{
      key: "BTN_SAVE",
      icon: <i className="icon-coms-Preservation" />,
      content: getLabel(30986, '保存'),
      disabled: formLoading,
      onClick: () => this.onMenuClick("BTN_SAVE")
    }, {
      key: "test",
      icon: <i className="icon-coms-Approval" />,
      content: getLabel('514733','部署'),
      disabled: formLoading,
      onClick: () => this.onMenuClick("test")
    }]
  }

  /**
   * 获取顶部按钮
   * @returns {Array}
   */
  getBtns = () => {
    const {
      formLoading
    } = this.props.delegateClientStore.status;

    return [
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@jlw5f8@delegateClientBtnSave`} type="primary" key="BTN_SAVE" disabled={formLoading} onClick={() => this.onMenuClick('BTN_SAVE')}>{getLabel(30986, '保存')}</Button>,
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@p1biy2@delegateClientBtnTest`} type="primary" key="test" disabled={formLoading} onClick={() => this.onMenuClick('test')}>{getLabel('514733','部署')}</Button>
    ]
  };

  /**
   * 右键菜单点击事件
   * @param type
   */
  onMenuClick = (type) => {
    const { 
      delegateClientStore,
    } = this.props, { 
      baseForm,
      hiddenFields={},
    } = delegateClientStore;
    
    if (['BTN_SAVE', 'test'].includes(type)) {
      const formParams = baseForm.getFormParams();
      let params = Object.assign({}, formParams, toJS(hiddenFields));
      // 提取保存的公共方法
      let saveMethod = () => {
        if('test' === type) {
          doConfirm(
            getLabel('514734','部署后会自动重启服务，若有失败，请手动重启服务，以确保系统能正常使用！'),
            delegateClientStore.getBaseInfoFormOperation,
            params,
          )
        } else {
          delegateClientStore.getBaseInfoFormOperation(params);
        }
      };

      if('test' === type) {
        params = Object.assign({}, params, {isdeploy: '1'});
      }

      if(formParams.isuse != '1') {
        saveMethod();
      } else {
        onCheck(baseForm, () => {
          if(formParams.isuse == '1' && formParams.ec_isuse != '1' && formParams.em_isuse != '1') {
            doConfirm(getLabel('528310','请开启pc认证或移动端认证!'));
            return;
          }

          saveMethod();
        });
      }
    }
  };

  /**
   * 渲染form表单
   */
  getBaseInfoForm = (form, datas=[]) => {
    const {
      isFormInit,
    } = form;
    let group = [];

    isFormInit && datas && datas.forEach((c, index) =>{
      let items = [];

      if(form.getFormParams().isuse == '1' || ('1' != form.getFormParams().isuse && 'baseInfo' === c.key)) {
        c.items && c.items.forEach(fields => {
          let key = fields.domkey[0];
          items.push({
            com:(
              <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@untyu8@${key}`}
                label={`${fields.label}`}
                labelCol={{span: `${fields.labelcol}`}}
                wrapperCol={{span: `${fields.fieldcol}`}}
                error={form.getError(fields)}
                tipPosition="bottom"
              >
                <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@8kycvi@${key}`} fieldConfig={fields} form={form} />
              </WeaFormItem>
            ),
            colSpan:1,
            hide: form.isHide(fields, (keys, allParams) => {
              let bool = false;
              'customsql' === key && allParams.accounttype != '7' && (bool = true);
              return bool;
            })
          });
        });
        group.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@czy0m6@${index}`} center col={1} needTigger={true} title={c.title} showGroup={c.defaultshow} items={items}/>);
      }
    });

    return group;
  }

  render() {
    const {
      delegateClientStore,
    } = this.props, {
      status, 
      baseForm,
    } = delegateClientStore, {
      hasRight,
      loading,
      condition,
    } = status, {
      collectParams,
    } = this.state;

    return (
      loading 
        ? null 
        : hasRight
          ? <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@5z4r24`}
              datas={this.getRightMenu()}
              collectParams={collectParams}
            >
              <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@u9f1vg`}
                title={getLabel('528480','Delegate集成')}
                icon={<i className="icon-coms-integration" />}
                iconBgcolor="#1a57a0"
                buttons={this.getBtns()}
                showDropIcon={true}
                dropMenuDatas={this.getRightMenu()}
                dropMenuProps={{collectParams}}
              />
              <WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@j1gtn2`} height={"calc(100% - 50px)"}>
                {this.getBaseInfoForm(baseForm, condition)}
              </WeaNewScroll>
            </WeaRightMenu>
          : <NoRight ecId={`${this && this.props && this.props.ecId || ''}_NoRight@7th6yc`}/>
    );
  }
}

export default DelegateClient;
