import {action, observable, toJS} from "mobx";
import {WeaLocaleProvider} from "ecCom";
import {message, Button} from "antd";
import {WeaForm} from "comsMobx";
import * as API from "../apis/OAuth2Service";
import {defaultBtns, onCheck, doConfirm, checkNonstandard, setModalInfo} from '../util/IntegrationUtil';
import PopoverButton from '../public/PopoverButton';
const {getLabel} = WeaLocaleProvider;

export class OAuth2Store {
  @observable baseForm = new WeaForm();
  @observable status = {
    hasNonStandard: true,
    rightLoading: true,
    formLoading: true,
    hasRight: true,
    baseInfoFormFields: [],
    baseInfoFormHiddenFields: []
  };

  @action setState = (params = {}) => {
    let status = { ...this.status };
    Object.keys(params).forEach(key => {
        status[key] = params[key];
    });
    this.status = status;
  };

  @action cleanStore = () => {
    this.setState({
      hasNonStandard: true,
      rightLoading: true,
      formLoading: true,
      hasRight: true,
      other_params: [],
      authorize_header: [],
      authorize_params: [],
      access_token_header: [],
      access_token_params: [],
      profile_header: [],
      profile_params: [],
      logout_header: [],
      logout_params: [],
      refresh_token_header: [],
      refresh_token_params: [],
      heart_beat_header: [],
      heart_beat_params: [],
      headerColumns: [{
        title: getLabel('528427','头部标签'),
        dataIndex: "headTag",
        width: "30%",
        com: [{type: "INPUT", key: "headTag", viewAttr: 3}]
      },{
        title: getLabel('33368','内容'),
        dataIndex: "content",
        width: "30%",
        com: [{ type: "INPUT", key: "content" }]
      },{
        title: "",
        dataIndex: "clazz",
        width: "40%",
        com: [{ type: "INPUT", key: "clazz", viewAttr: 1, defaultValue: "" }]
      }],
      paramsColumns: [{
        title: getLabel('20968','参数名'),
        dataIndex: "paramKey",
        width: "30%",
        com: [{type: "INPUT", key: "paramKey", viewAttr: 3}]
      },{
        title: getLabel('17637','参数值'),
        dataIndex: "paramValue",
        width: "40%",
        com: [{ type: "INPUT", key: "paramValue" }]
      },{
        title: "",
        dataIndex: "other",
        width: "30%",
        com: [{ type: "INPUT", key: "other", viewAttr: 1 }]
      }]
    });
  }

  @action doInit = () => {
    this.setState({nonStandLoading: true});
    checkNonstandard({num: "128"}, (result) => {
      this.setState({
        hasNonStandard: result.isOpen,
        nonStandLoading: false
      });
      if(result.isOpen) {
        this.cleanStore();
        this.baseForm = new WeaForm();
        this.getBaseInfoForm();
      }
    })
  }

  @action getBaseInfoForm = (params={}) => {
    this.setState({rightLoading: true, formLoading: true});
    this.baseForm = new WeaForm();
    API.getBaseInfoForm(params).then(result => {
      if(result.status == 1) {
        if(result.ret === "noright") {
          this.setState({hasRight: false});
        }else {
          let dataKey = [];
          result.condition && result.condition.forEach((item, index) => {
            if(["baseInfo", "auth_method", "description"].indexOf(item.key) === -1) {
              dataKey.push(item.key);
            }
          
            this.setState({[`searchGroup_${index}_visible`]: item.defaultshow});
          })

          this.setState({
            dataKey,
            hasRight: true,
            baseInfoFormFields: result.condition,
            baseInfoFormHiddenFields: result.hiddenFields,
            ...result.hiddenFields,
          });
          this.baseForm.initFormFields(result.condition);
        }
        this.setState({rightLoading: false, formLoading: false});
      }
    }).catch(err => {
      this.setState({rightLoading: false, formLoading: false, hasRight: false});
    })
  };

  get menus() {
    const {formLoading} = toJS(this.status);
    let rightMenus = defaultBtns.defaultSaveBtns && defaultBtns.defaultSaveBtns.map(item => {
      return {
        ...item,
        disabled: formLoading,
        onClick: () => this.onMenuClick(item.key)
      }
    });
    rightMenus.push({
      type: "primary",
      key: "BTN_DEPLOY",
      icon: <i className="icon-coms-Preservation" />,
      content: <PopoverButton ecId={`${this && this.props && this.props.ecId || ''}_PopoverButton@cosmq0@integrationAouth2ButtonBTN_DEPLOY`} menuType="1"/>,
      onClick: () => this.onMenuClick("BTN_DEPLOY"),
    });
    let buttons = defaultBtns.defaultSaveBtns && defaultBtns.defaultSaveBtns.map(item => 
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@s122u6@integrationAouth2Button${item.key}`} type={item.type} disabled={formLoading} key={item.key} onClick={() => this.onMenuClick(item.key)}>{item.content}</Button> 
    );
    buttons.push(<PopoverButton ecId={`${this && this.props && this.props.ecId || ''}_PopoverButton@83xzjr@integrationAouth2ButtonBTN_DEPLOY`} 
      showType="button"
      type="primary"
      disabled={formLoading}
      onClick={() => this.onMenuClick("BTN_DEPLOY")}
    />);

    return {
      rightMenus,
      buttons,
      title: getLabel('513942','OAuth2集成'),
      collectParams: {
        favname: getLabel('513942','OAuth2集成'),
        favouritetype: 1,
        objid: 0,
        link: "/wui/engine.html#/integration/OAuth2",
        importantlevel: 1
      }
    }
  }

  onMenuClick = (type) => {
    if(type === "BTN_DEPLOY") {
      let formParams = this.baseForm.getFormParams();
      if((formParams.isuse == '1' && (formParams.pcauth == '1' || formParams.appauth == '1')) || formParams.isuse != '1') {
        doConfirm(getLabel('514734','部署后会自动重启服务，若有失败，请手动重启服务，以确保系统能正常使用！'), this.getBaseInfoFormOperation, {isdeploy: '1'});
      }else{
        doConfirm(getLabel('515161','请开始PC认证或手机认证'));
      }
    }else if(type === "BTN_SAVE") {
      this.getBaseInfoFormOperation();
    }
  }

  @action getBaseInfoFormOperation = (param={}) => {
    let params = this.baseForm ? this.baseForm.getFormParams(): {};
    params = Object.assign({}, params);

    if(params.isuse == '1') {
      if(params.profile_use != '1') {
        window.e9HideFormFieldKeys = ["profile_account_key"];
      }
      onCheck(this.baseForm, () => {
        let flag = true;
        const {dataKey} = this.status;

        for(let i = 0; (i < dataKey.length) && flag; i++) {
          let name = dataKey[i];
          if((i > 2 && params[`${name}_use`] == '1') || (i < 3)) {
            if((this[`${name}_header`] && this[`${name}_header`].doValidate().pass) || i == 0) {
              if(this[`${name}_params`] && this[`${name}_params`].doValidate().pass) {
              }else {
                flag = false;
              }
            }else {
              flag = false;
            }
          }
        }
        if(flag) {
          this.saveOperate(param);
        }
      });
    }else {
      this.saveOperate(param);
    }
  }

  getParams = () => {
    let formParams = this.baseForm.getFormParams(), params={};
    Object.keys(formParams).forEach(key => {
      params[key] = formParams[key] ? formParams[key].trim() : ""
    })
    const {authorize_header, authorize_params, access_token_header, access_token_params, profile_header, profile_params, logout_header, logout_params, refresh_token_header, refresh_token_params, heart_beat_header, heart_beat_params, other_params} = toJS(this.status);
    const {authorize_url, authorize_method, access_token_url, access_token_method, profile_use, profile_url, profile_method, profile_account_type, profile_account_key, profile_account_customsql, logout_use, logout_url, logout_method, refresh_token_use, refresh_token_url, refresh_token_method, heart_beat_use, heart_beat_url, heart_beat_method, heart_beat_ok_flag} = params;
    const authorize_cfg = {authorize_url, authorize_method, authorize_header, authorize_params};
    const access_token_cfg = {access_token_url, access_token_method, access_token_header, access_token_params};
    const profile_cfg = {profile_use, profile_url, profile_method, profile_account_type, profile_account_customsql, profile_account_key, profile_header, profile_params};
    const logout_cfg = {logout_use, logout_url, logout_method, logout_header, logout_params};
    const refresh_token_cfg = {refresh_token_use, refresh_token_url, refresh_token_method, refresh_token_header, refresh_token_params};
    const heart_beat_cfg = {heart_beat_use, heart_beat_url, heart_beat_method, heart_beat_ok_flag, heart_beat_header, heart_beat_params};

    params = Object.assign({}, params, {
      authorize_cfg: JSON.stringify(authorize_cfg),
      access_token_cfg: JSON.stringify(access_token_cfg),
      profile_cfg: JSON.stringify(profile_cfg),
      logout_cfg: JSON.stringify(logout_cfg),
      refresh_token_cfg: JSON.stringify(refresh_token_cfg),
      heart_beat_cfg: JSON.stringify(heart_beat_cfg),
      other_params: typeof(other_params) === "string" ? other_params : JSON.stringify(other_params),
    });
    return params;
  }

  @action saveOperate = (param) => {
    this.setState({formLoading: true});
    let params = Object.assign({}, {operation: "add"}, this.getParams(), param);
    API.getBaseInfoFormOperation(params).then(result => {
      if(result.status == 1 && params.isdeploy != 1) {
        message.success(getLabel('22619','保存成功'));
        this.getBaseInfoForm();
      }
      if(params.isdeploy == 1) {
        let data = {};
        if(result.syncResult) {
          try {
            if(typeof(result.syncResult) === "string") {
              data = JSON.parse(result.syncResult) || {};
            } else if (typeof(result.syncResult) === "object") {
              data = result.syncResult;
            }
          } catch(er) {}
        }
        if(data.status === "failure") {
          if(data.errorNode && data.noValNode) {
            setModalInfo(<div>
              {getLabel('522113','集群部署失败， 有节点异常导致不能进行部署， 请检查异常节点， 并重新进行部署。')}
              <div>{getLabel('522114','配置失败的节点为')}: {data.errorNode}</div>
              <div>{getLabel('522115','验证失败的节点为')}: {data.noValNode}</div>
            </div>);
          } else if(data.errorNode) {
            setModalInfo(<div>
              {getLabel('522113','集群部署失败， 有节点异常导致不能进行部署， 请检查异常节点， 并重新进行部署。')}
              <div>{getLabel('522114','配置失败的节点为')}: {data.errorNode}</div>
            </div>);
          } else if(data.noValNode) {
            setModalInfo(<div>
              {getLabel('522113','集群部署失败， 有节点异常导致不能进行部署， 请检查异常节点， 并重新进行部署。')}
              <div>{getLabel('522115','验证失败的节点为')}: {data.noValNode}</div>
            </div>);
          }
        }
      }
      this.setState({formLoading: false});
    }).catch(err => {
      this.setState({formLoading: false});
    })
  }

  @action doTest = (params={}) => {
    params = Object.assign({}, params, this.getParams());
    this.setState({
      testType: params.type || "",
    });
    
    API.doTest(params).then(result => {
      if('authorize' != params.type) {
        try{
          this.setState({testMessage: JSON.stringify(result, null, '\t')}); 
        }catch(err){
          this.setState({testMessage: `${result}`});
        }
      } else {
        if(result && result.result) {
          window.open(result.result, '_target');
        }
      }
    })
  }
}
