import {
  action, 
  observable, 
  toJS
} from "mobx";
import * as API from "../apis/SamlService";
import {
  message, 
} from "antd";
import {
  WeaForm, 
  WeaTableNew,
  WeaLogView
} from "comsMobx";
import {
  WeaLocaleProvider
} from "ecCom";
import {
  checkNonstandard,
  setModalInfo,
} from '../util/IntegrationUtil';

const { TableStore } = WeaTableNew;
const {LogStore} = WeaLogView;
const {getLabel} = WeaLocaleProvider;

export class SamlStore {
  @observable hasRight= true;
  @observable tableStore = new TableStore();
  @observable form = new WeaForm();
  @observable configForm = new WeaForm();
  @observable logStore = new LogStore();
  @observable status = {};

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

  @action cleanStore = () => {
    this.form = new WeaForm();
    this.configForm = new WeaForm();
    this.setState({
      isConfiguredDisabled: false,
      isConfigured: false,
      configCondition: [],
      sp_urls: [],
      buttonStatus: false,
      condition: [],
      loading: true,
      menus:  [{
        key: "BTN_BASE_SAVE",
        type: "primary",
        icon: <i className="icon-coms-Preservation" />,
        content: getLabel(30986, '保存')
      }, {
        key: 'BTN_TEST',
        type: "primary",
        icon: <i className='icon-coms-currency-Task' />,
        content: getLabel(514733, '部署')
      }],
      dialogMenus: [{
        key: "BTN_SAVE",
        type: "primary",
        icon: <i className="icon-coms-Preservation" />,
        content: getLabel(30986, '保存')
      }, {
        key: "BTN_SAVE_CONFIG",
        type: "primary",
        icon: <i className="icon-coms-Preservation" />,
        content: getLabel('521875','保存并生成配置')
      }, {
        key: 'BTN_TEST',
        type: "primary",
        icon: <i className='icon-coms-currency-Task' />,
        content: getLabel('516693','配置检查')
      }],
      testMenus: [{
        key: "BTN_EDIT",
        type: "primary",
        icon: <i className="icon-coms-Preservation" />,
        content: getLabel('516657','OIOSAML配置')
      }],
      collectParams: {
        favname: getLabel(12345, "SAML集成"),
        favouritetype: 1,
        objid: 0,
        link: "wui/engine.html#/integration/Saml",
        importantlevel: 1
      }
    })
  }

  @action cleanDialog = () => {
    this.configForm = new WeaForm();
    this.setState({
      editTab: "",
      appEditDialogVisible: false,
      configCondition: [],
      sp_urls: [],
      buttonStatus: false,
      testResultDatas: [],
    })
  }

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

  @action getBaseInfoForm = (params={}) => {
    this.form = new WeaForm();
    API.getBaseInfoForm(params).then(result => {
      if(result.errmsg && result.errmsg === "noright") {
        this.hasRight = false;
      }else {
        this.hasRight=true;
        this.setState({
          condition: result.condition || [],
          hiddenFields: result.hiddenFields,
          isConfigured: result.isConfigured,
        });
        this.form.initFormFields(result.condition);
        if(result.isConfigured) {
          this.checkIsConfigured();
        }
      }
      this.setState({loading: false});
    }).catch(err => {
      this.setState({loading: false});
    })
  };


  // 详细配置
  @action getDetailInfoForm = () => {
    this.configForm = new WeaForm();
    API.getDetailInfoForm().then(result => {
      if(result.status == "1") {
        this.configForm.initFormFields(result.condition);
        this.setState({
          configCondition: result.condition || [],
          sp_urls: result.sp_urls || [],
          hiddenFields: result.hiddenFields,
          sp_urls_columns: [{
            title: getLabel(516661, "页面信息"),
            dataIndex: "title"
          }, {
            title: "URL",
            dataIndex: "url"
          }]
        })
      }
    })
  }

  @action getConfigurationResult = (callBack=null) => {
    API.getConfigurationResult().then(result => {
      if(result.status == 1) {
        this.setState({
          testResultDatas: result.resultList || [],
          testResultColumns: [{
            title: getLabel('512978','检查项'),
            dataIndex: "item"
          }, {
            title: getLabel(516679, "检查内容"),
            dataIndex: "content"
          }, {
            title: getLabel(516680, "检查结果"),
            dataIndex: "result"
          }]
        })
        if(callBack && typeof(callBack) === "function") {
          callBack(result.resultList);
        }
      }
    })
  }

  @action getBaseInfoFormOperation = (params={}) => {
    this.setState({
      buttonStatus: true
    })
    API.getBaseInfoFormOperation(params).then(result => {
      this.setState({
        buttonStatus: false
      })
      if(result.status == '1') {
        if(params.method == "deploy") {
          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>);
            }
          } else {
            message.success(getLabel('522155','部署成功'));
          }
        }else {
          message.success(getLabel('22619','保存成功'));
        }
        // 页面的刷新
        this.getBaseInfoForm();
      }
    });
  };

  @action getDetailInfoFormOperation = (params={}, saveCallBack=null) => {
    API.getDetailInfoFormOperation(params).then(result => {
      if(result.status == "1") {
        message.success(getLabel(22619, "保存成功"));
        this.getConfigurationResult((list) => {
          let flag = true;
          list && list.forEach(item => {
            flag = flag && item.result;
          });
          if(this.form.getFormParams().isuse == '1') {
            if(flag) {
              this.setState({isConfiguredDisabled: true});
            } else {
              this.setState({isConfiguredDisabled: false});
            }
          } else {
            this.setState({isConfiguredDisabled: true});
          }
        });
        if(saveCallBack && typeof(saveCallBack) === "function") {
          saveCallBack();
        }
      }
      if(result.error_code_msg) {
        message.error(result.error_code_msg);
      }
    })
  }

  @action
  checkIsConfigured = () => {
    this.getConfigurationResult((list) => {
      let flag = true;
      list && list.forEach(item => {
        flag = flag && item.result;
      });
      if(this.form.getFormParams().isuse == '1') {
        if(flag) {
          this.setState({isConfiguredDisabled: true});
        }else {
          this.setState({isConfiguredDisabled: false});
        }
      } else {
        this.setState({isConfiguredDisabled: true});
      }
    });
  }
}
