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

const getLabel = WeaLocaleProvider.getLabel;

export default class Cas {
  @observable hasRight=false;
  @observable rightLoading= true;
  @observable newBaseForm = new WeaForm(); // 新建表单store
  @observable telForm = new WeaForm(); // 新建表单store

  @observable tableEdit = null;
  @observable loading = false;
  @observable
  status = {
    hasNonStandard: true,
    nonStandLoading: true,
    newBaseFormFields: [], // 新建表单
    res: {},
    tableDatas: [],
    tableColumns: [],
    testVisible: false,
    userAgent: []
  }

  doInit = () => {
    this.setState({
      nonStandLoading: true
    })
    checkNonstandard({num: "090"}, (result) => {
      this.setState({
        hasNonStandard: result.isOpen,
        nonStandLoading: false
      })
      if(result.isOpen) {
        this.getForm();
      }
    })
  }

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

  save = (para) => {
    let params = this.newBaseForm.getFormParams();
    params.list = JSON.stringify(this.status.tableDatas);
    if (para && para == 1) {
      params.saveType = 1;
    }
    delete params.desc;
    if(params.isuse == "0") {
      params.list = JSON.stringify(this.status.orgTableDatas); 
      this.saveFunc(params);
    }else {
      if(params.accounttype === "7" && (!params.customsql)) {
        this.newBaseForm.showError("accounttype", getLabel('507426','"Ecology账号规则" 未填写'));
        return;
      }
      this.newBaseForm.validateForm().then(f=>{
        if(f.isValid){
        // if(f.isValid && this.tableEdit.doValidate().pass){
          this.saveFunc(params);
        }else{
          f.showErrors();
        }
      });
    } 
  };

  @action saveFunc = (params) => {
    this.loading = true;
    API.save(params).then(result => {
      if(result.status == "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>);
          }
        } else {
          if (result.msg) {
            Modal.info({
              title: getLabel(15172,'系统提示'),
              content: result.msg,
              okText: getLabel(826,'确定'),
              onOk: () => this.doInit()
            });
          }
        }
      }else {
        message.error(getLabel('22620','保存失败'));
      }
      this.loading = false;
    }).catch(err => {
      this.loading = false;
    })
  }

  handleCondition = (condition) => {
    let userAgent = [];
    condition && condition.forEach(c => {
      c && c.items && c.items.forEach(fields => {
        if(["strgy_ua_val"].includes(fields.domkey[0])) {
          userAgent.push(fields);
        }
      })
    })
    this.setState({userAgent});
  }

  getForm = params => {
    this.loading = true;
    API.getForm(params).then(res => {
      if(res.status&&res.status=="false"){
        this.hasRight=false;
      }else{
        this.hasRight=true;
      }
      this.rightLoading = false;
      this.newBaseForm = new WeaForm();
      this.newBaseForm.initFormFields(res.condition);
      this.handleCondition(res.condition);
      this.status = {
        ...this.status,
        newBaseFormFields: res.condition,
        res: res,
        tableDatas: res.datas,
        orgTableDatas: res.datas,
        tableColumns: res.columns,
      };
      this.loading = false;
    }).catch(err => {
      this.loading = false;
    })
  }

  getTelForm = () => {
    API.getForm({
      operation: 'test',
    }).then(res => {
      this.status.testVisible = true;
      this.telForm = new WeaForm();
      res.condition[0].items[0].value = '';
      res.condition[0].items[1].value = '';
      this.telForm.setCondition(res.condition);
      const params = this.telForm.getFormParams();
    });
  }

  telTest = () => {
    const params = this.telForm.getFormParams();
    const baseParams = this.newBaseForm.getFormParams();
    if (baseParams.appauthAddress) {
      this.telForm.validateForm().then(f=>{
        if(f.isValid){
          params.operation = 'testResetAPI';
          API.save(params).then(res => {
            if (res.msgid) {
              Modal.info({
                title: getLabel(15172,'系统提示'),
                content: res.msgid,
                okText: getLabel(826,'确定'),
                onOk() {},
              });
            }
          });
        }else{
          f.showErrors();
        }
      });
    } else {
      Modal.info({
        title: getLabel(15172,'系统提示'),
        content: "CAS ServerRest API" + getLabel(110,'地址') + getLabel(385284,'为空') + "!",
        okText: getLabel(826,'确定'),
        onOk() {},
      });
    }
  }

  testCas = () => {
    const baseParams = this.newBaseForm.getFormParams();
    baseParams.operation = 'testCas';
    API.save(baseParams).then(res => {
      if (res.msgid) {
        Modal.info({
          title: getLabel(15172,'系统提示'),
          content: res.msgid,
          okText: getLabel(826,'确定'),
          onOk() {},
        });
      }
    }, () => {
      Modal.info({
        title: getLabel(15172,'系统提示'),
        content: getLabel(32296,'测试不通过，请检查设置'),
        okText: getLabel(826,'确定'),
        onOk() {},
      });
    });
  }
}
