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

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

export class AuthenticationCenterStore {
    @observable hasRight= true;
    @observable shareFormRole = [];
    @observable shareFormPost = [];
    @observable shareFormDepFields = [];
    @observable shareFormSubFields = [];

    @observable tableStore = new TableStore();//注册应用列表
    @observable tableStore2 = new TableStore();//字段映射列表
    @observable tableStore3 = new TableStore();//运行日志列表

    @observable searchForm = new WeaForm();
    @observable addShareForm = new WeaForm();
    @observable searchForm2 = new WeaForm();
    @observable newForm = new WeaForm();

    @observable appCenterForm = new WeaForm();
    @observable registerAppEditForm = new WeaForm();
    @observable registerAppEditFormOrg = new WeaForm();
    @observable registerAppDataMappingEditForm = new WeaForm();
    @observable registerAppDataMappingImportForm = new WeaForm();
    @observable logStore = new LogStore();
    @observable rightLoading = true;
    @observable logoItems = [];

    @observable
    status = {
      selectedKey: 0,
      BaseInfoFormFields: [],
      BaseInfoFormHiddenFields: [],
      showSearchAd: false,
      rightMenus: [],
      rightMenus2: [],
      condition2:[],
      rowSelectIds2: [],
      showNewFormDialog: false,
      appEditFormDialogVisible: false,
      appEditFormDetailDialogVisible: false,
      appEditFormDetailDataMappingDialogVisible: false,
      appEditFormDetailDataMappingImportDialogVisible: false,
      appEditFormDetailDataMappingImportResultDialogVisible: false,
      advancedSearchHeight:120,
      resultTableHeader:[],
      resultTableData:[],
    };
    operateDataMappingIndex = '';

    // 共享范围
    @action getRegisterAppShareForm = (params={}) => {
      API.getRegisterAppShareForm(params).then(result => {
        if(result.status == 1) {
          if(["addShare", "delShare"].includes(params.operate)) {
            this.setState({
              rowSelectedKeys: [],
              showAddShare: false
            });
            if(params.operate === "delShare") {
              message.success(getLabel(0, "删除成功"));
            }else {
              message.success(getLabel(0, "保存成功"));
            }
            this.getRegisterAppShareList({sysid: params.sysid});
          }else if(params.operate === "getAddShareForm") {
            this.addShareForm = new WeaForm();
            this.addShareForm.initFormFields(result.condition);
            this.setState({
              addShareCondition: result.condition || [],
            })
            this.shareFormRole = [];
            this.shareFormPost = [];
            this.shareFormDepFields = [];
            this.shareFormSubFields = [];
            const {condition=[]} = result;
            condition && condition[0] && condition[0].items && condition[0].items.forEach(item => {
              const key = item.domkey[0];
              this.handleShareCondition({
                key,
                item,
              })
            });
          }
        }
      })
    }

    // 共享范围列表
    @action
    getRegisterAppShareList = (params={}) => {
      this.tableStore3 = new TableStore();
      API.getRegisterAppShareList(params).then(result => {
        if(result.status == '1') {
          if(result.sessionkey) {
            this.tableStore3.getDatas(result.sessionkey, 1);
          }
        }
      })
    }

    handleShareCondition = (params) => {
      const {
          key,
          item,
      } = params;

      if (['sharevalue2', 'rolelevel'].includes(key)) {
        this.shareFormRole.push(item);
      }
      if (['jobtitlelevel', 'jobtitlesharevalue2', 'jobtitlesharevalue3'].includes(key)) {
        this.shareFormPost.push(item);
      }
      if (['has_child', 'sharevalue1'].includes(key)) {
        if(key === "has_child") {
          this.shareFormDepFields.push(item);
        } else {
          this.shareFormDepFields.unshift(item);
        }
      }
      if (['has_child', 'sharevalue6'].includes(key)) {
        if(key === "has_child") {
          this.shareFormSubFields.push(item);
        } else {
          this.shareFormSubFields.unshift(item);
        }
      }
    }

    setOperateDataMappingIndex = (val) => {
      this.operateDataMappingIndex = val;
    }

    @action clearStore = () => {
      this.rightLoading = true;
      this.appCenterForm = new WeaForm();
      this.hasRight = true;
      this.shareFormRole = [];
      this.shareFormPost = [];
      this.shareFormDepFields = [];
      this.shareFormSubFields = [];
      this.setState({
        showAddShare: false,
        addShareCondition: [],
        rowSelectedKeys: [],
        shareList: [],
        shareColumn: [],
        baseInfoSecondNavSelectedKey: 0,
        selectedKey: 0,
        BaseInfoFormFields: [],
        BaseInfoFormHiddenFields: [],
        showSearchAd: false,
        rightMenus: [],
        rightMenus2: [],
        condition2:[],
        rowSelectIds2: [],
        showNewFormDialog: false,
        appEditFormDialogVisible: false,
        appEditFormDetailDialogVisible: false,
        appEditFormDetailDataMappingDialogVisible: false,
        appEditFormDetailDataMappingImportDialogVisible: false,
        appEditFormDetailDataMappingImportResultDialogVisible: false,
        advancedSearchHeight:120,
        resultTableHeader:[],
        resultTableData:[],
        appCenterCondition: [],
        spnegoDescription: "",
      })
    }

    @action
    doInit = (type) => {
      if(type === "cas" || type === "oauth2") {
        this.setState({nonStandLoading: true});
        checkNonstandard({num: "100"}, (result) => {
          this.setState({
            hasNonStandard: result.isOpen,
            nonStandLoading: false
          })
          if(result.isOpen) {
            this.clearStore();
            this.getBaseInfoForm();
          }
        })
      }else {
        this.clearStore();
        this.getBaseInfoForm();
      }
    };

    @action doAppCenterInit = () => {
      this.clearStore();
      this.getBaseInfoForm();
      this.getRegisterAppRightMenu();
      this.getRegisterAppCondition(() => {
        this.getRegisterAppList();
      });
    }

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

    getBaseInfoForm = (params) => {
      this.newForm = new WeaForm();
      API.getBaseInfoForm(params).then(result => {
        if(result.ret && result.ret == "noright"){
          this.hasRight=false;
        }else{
          this.hasRight=true;
        }
        let spnegoDescription = "";

        result.condition && result.condition.forEach(c => {
          c && c.items && c.items.forEach(item => {
            if(item.domkey[0] === "spnego_desc_") {
              spnegoDescription = item.value;
            }
          })
        })

        this.setState({
          BaseInfoFormFields: result.condition,
          BaseInfoFormHiddenFields: result.hiddenFields,
          spnegoDescription,
        })
        this.newForm.initFormFields(result.condition);
        this.rightLoading = false;
      });
    };

    getBaseInfoFormOperation = (params,callback) => {
      API.getBaseInfoFormOperation(params).then(result => {
        if(params.method === "weaversso") {
          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(!callback) {
              if(result.errmsgTip) {
                message.success(result.errmsgTip);
                this.getBaseInfoForm();
              }
            } 
          }
        } else {
          if(params.method == 'test'||params.method == 'oauth2_test') {
            if(result.success) {
              if(!params.testBeforeSave) {
                setModalInfo(getLabel(32297, '测试通过'));
              }
            }else {
              setModalInfo(getLabel(388228, '测试不通过，请检查设置!'));
            }
          }
          if(!callback) {
            if(result.errmsgTip) {
              message.success(result.errmsgTip);
            }
          } 
        }
        isFunction(callback)&& callback(result);
      });
    };

    getRegisterAppList = (params={}) => {
      params = Object.assign({}, this.appCenterForm.getFormParams(), params);
      API.getRegisterAppList(params).then(result => {
        if(result.ret && result.ret == "noright"){
          this.hasRight=false;
        }else{
          this.hasRight=true;
          if(result.sessionkey) {
            this.tableStore.getDatas(result.sessionkey,1);
          }else {
            this.status = { ...this.status, isAlertPage: true };
          }
          this.rightLoading = false;
        }
      });
    };

    getRegisterAppRightMenu = (params) => {
      API.getRegisterAppRightMenu(params).then(result => {
        this.status = { ...this.status, rightMenus: result.rightMenus };
      });
    };

    @action getRegisterAppListInfo = () => {
      Promise.all([
        API.getBaseInfoForm()
      ]).then(([result]) => {
        if(!result.ret) {
          this.status = {
            ...this.status,
            BaseInfoFormFields: result.condition,
            BaseInfoFormHiddenFields: result.hiddenFields,
          };
          this.newForm = new WeaForm();
          this.newForm.initFormFields(result.condition);
          this.getRegisterAppRightMenu();
          this.getRegisterAppList();
        } 
      })
    }

    getRegisterAppEditForm = (params={}) => {
      this.registerAppEditForm = new WeaForm();
      this.registerAppEditFormOrg = new WeaForm();
      this.logoItems = [];
      API.getRegisterAppEditForm(params).then(result => {
        if(result.status == 1) {
          if(result.condition && result.condition[0] && result.condition[0].items) {
            result.condition[0].items.forEach((item, index) => {
              if(item.domkey[0] === 'allow_ip') {
                result.condition[0].items[index] = {
                  ...result.condition[0].items[index],
                  maxRows: 4,
                  minRows: 4,
                }
              } else if (item.domkey[0] === "logo_height" || item.domkey[0] === "logo_width") {
                this.logoItems.push(item);
              } else if(item.domkey[0] === "logo_pic") {
                this.setState({urllinkimagid: item.value || ""});
              }
            })
          }
          this.registerAppEditFormOrg.initFormFields(result.condition);
          this.registerAppEditForm.initFormFields(result.condition);
          this.setState({
            registerAppEditFormCodition: result.condition || [],
            registerAppEditFormHiddenFields: result.hiddenFields || [],
            showPic: true,
          });
        }
      });
    };

  getRegisterAppOperation = (params,callback, isClose=true) => {
    API.getRegisterAppOperation(params).then(result => {
      this.status.appEditFormDialogVisible = false;
      if(isClose) {
        this.status.appEditFormDetailDialogVisible = false;
      }
      this.tableStore.reloadCurrent();
      if(!callback) {
        if(result.status == '1' && params.operation == 'delete') {
          message.success(getLabel('20461','删除成功'));
        }else if(result.status == '1') {
          message.success(getLabel('22619', '保存成功'));
        }
      }
      isFunction(callback)&& callback(result);
    });
  };

  getRegisterAppDataMappingEditForm = (params) => {
    API.getRegisterAppDataMappingEditForm(params).then(result => {
      result.condition && result.condition[0] && result.condition[0].items && (result.condition[0].items[4].rules = "required");
      this.registerAppDataMappingEditForm = new WeaForm();
      this.registerAppDataMappingEditForm.setCondition(result.condition);

      if(params&&params.id) {
        this.registerAppDataMappingId = params.id;
      }else{
        this.registerAppDataMappingId = '';
      }
    });
  };

  getRegisterAppDataMappingImportForm = (params) => {
    API.getRegisterAppDataMappingImportForm(params).then(result => {
      this.registerAppDataMappingImportForm = new WeaForm();
      this.registerAppDataMappingImportForm.setCondition(result.condition);
    });
  };

  // 数据映射方法封装
  @action
  getRegisterAppDataMappingInfo = (params={}) => {
    this.tableStore2 = new TableStore();
    params = Object.assign({}, this.searchForm2.getFormParams(), params);

    Promise.all([
      API.getRegisterAppDataMappingRightMenu(params),
      API.getRegisterAppDataMappingList(params)
    ]).then(([result1, result2]) => {
      this.setState({
        rightMenus2: result1.rightMenus || [],
      })
      if (result2.sessionkey) {
        this.tableStore2.getDatas(result2.sessionkey, 1);
      }
    })
  }

  getRegisterAppDataMappingList = (params) => {
    this.tableStore2 = new TableStore();
    let p = (this.searchForm2 && this.searchForm2.getFormParams()) || {};
    if(params&&params.id){
      p.id = params.id;
    }
    API.getRegisterAppDataMappingList(p).then(result => {
      if (result.sessionkey) {
        this.tableStore2.getDatas(result.sessionkey,1);
      } else {
        this.status = { ...this.status, isAlertPage: true };
      }
    });
  };

  getRegisterAppDataMappingRightMenu = (params={}) => {
    API.getRegisterAppDataMappingRightMenu(params).then(result => {
      this.setState({
        rightMenus2: result.rightMenus || [],
      })
    });
  };

  @action
  getRegisterAppDataMappingCondition = (params={}, callBack) => {
    this.searchForm2 = new WeaForm();
    API.getRegisterAppDataMappingCondition(params).then(result => {
      if(result.status == "1") {
        this.setState({
          condition2: result.condition || [],
        })
        this.searchForm2.initFormFields(result.condition);

        if(callBack && typeof(callBack) === "function") {
          callBack();
        }
      }
    });
  };

  getRegisterAppDataMappingOperation = (params,callback) => {
    API.getRegisterAppDataMappingOperation(params).then(result => {
      if(params&&params.operation!='getUserInfo'){
        this.status.appEditFormDetailDataMappingDialogVisible = false;
        this.getRegisterAppDataMappingList({id: this.status.registerAppId});
        if(!callback) {
          if(result.status == '1' && params.operation == 'delete') {
            message.success(getLabel('20461','删除成功'));
          }else {
            message.success(getLabel('22619', '保存成功'));
          }
        }
      }
      isFunction(callback)&& callback(result);
    });
  };

  getRegisterAppLoginLogList = (params) => {
    API.getRegisterAppLoginLogList(params).then(result => {
      if (result.sessionkey) {
        this.tableStore3 = new TableStore();
        this.tableStore3.getDatas(result.sessionkey,1);
      } else {
        this.status = { ...this.status, isAlertPage: true };
      }
    });
  };

  getRegisterAppLoginLogCondition = (params) => {
    API.getRegisterAppLoginLogCondition(params).then(result => {
    });
  };

  //确认
  confirmModal = (content, func, val) => {
      //确认信息， 方法， 方法参数
      Modal.confirm({
          title: `${getLabel(131329,'信息确认')}`,
          content: content,
          okText: `${getLabel(16631,'确定')}`,
          cancelText:`${getLabel( 201 ,'取消')}`,
          onOk: () => func(val),
      })
  };

  getRegisterAppCondition = (callBack=null) => {
    this.appCenterForm = new WeaForm();
    API.getRegisterAppCondition().then(result => {
      if(result.status == 1) {
        this.appCenterForm.initFormFields(result.condition);
        this.setState({
          appCenterCondition: result.condition || [],
          advanceHeight: getSearchFormHeight(result.condition), 
        })
        if(callBack && typeof(callBack) === "function") {
          callBack();
        }
      }
    })
  }
}
