  import {
    action, 
    observable
  } from "mobx";
  import * as API from "../apis/Exchange";
  import {
    message
  } from "antd";
  import {
    WeaForm, 
    WeaTableNew,
    WeaLogView
  } from "comsMobx";
  import {
    WeaLocaleProvider
  } from "ecCom";
  import {
    getSearchFormHeight,
    checkNonstandard,
  } from "../util/IntegrationUtil.js";
  
  const {LogStore} = WeaLogView;
  const {getLabel} = WeaLocaleProvider;
  const {TableStore } = WeaTableNew;
  
  export class Exchange {
    @observable hasRight= true;
    @observable tableStore = new TableStore();
    @observable authStore = new TableStore();
    @observable form = new WeaForm();
    @observable shareForm = new WeaForm();
    @observable loginURLForm = new WeaForm();
    @observable configForm = new WeaForm();
    @observable searchForm = new WeaForm();
    @observable logStore = new LogStore();
    @observable status = {
        hasNonStandard: true,
        nonStandLoading: false,
        loginURLhasRight: true,
        loginURLLoading: true,
        urlMenus: [{
          key: "BTN_SAVE",
          type: "primary",
          icon: <i className="icon-coms-Preservation" />,
          content: getLabel(30986, '保存')  
        }],
        urlCollectParams: {
          favname: getLabel('517412','Exchange集成'),
          favouritetype: 1,
          objid: 0,
          link: "wui/engine.html#/integration/UserLoginURL",
          importantlevel: 1
        }
    };
  
    @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.shareForm = new WeaForm();
      this.configForm = new WeaForm();
      this.searchForm = new WeaForm();
      this.loginURLForm = new WeaForm();
      this.setState({
        role: [],
        post: [],
        shareFormCondition: [],
        dataRangeMenus: [],
        showSyncDataRange: false,
        loginURLhasRight: true,
        loginURLLoading: true,
        urlMenus: [{
          key: "BTN_SAVE",
          type: "primary",
          icon: <i className="icon-coms-Preservation" />,
          content: getLabel(30986, '保存')  
        }],
        urlCollectParams: {
          favname: getLabel('517412','Exchange集成'),
          favouritetype: 1,
          objid: 0,
          link: "wui/engine.html#/integration/UserLoginURL",
          importantlevel: 1
        },
        loginURLCondition: [],
        advancedHeight: 72,
        searchCondition: [],
        configCondition: [],
        condition: [],
        sp_urls: [],
        buttonStatus: false,
        loading: true,
        selectedKey: "0",
        tabDatas: [{
          viewcondition: "0",
          title: getLabel(1361, "基本信息"),
        }, {
          viewcondition: "1",
          title: getLabel(125928, "同步日志"),
        }],
        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('517409','保存并更新配置')
        }, {
          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('517412','Exchange集成'),
          favouritetype: 1,
          objid: 0,
          link: "wui/engine.html#/integration/Exchange",
          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: "132"}, (result) => {
        this.setState({
          hasNonStandard: result.isOpen,
          nonStandLoading: false
        })
        if(result.isOpen) {
          this.cleanStore();
          this.getBaseInfo();
        }
      })
    };

    @action getBaseInfo = () => {
      this.form = new WeaForm();
      Promise.all([
        API.getBaseMenus(),
        API.getBaseInfoForm(),
      ]).then(([result1, result2]) => {
        if(result1.status == 1 && result2.status == 1) {
          if(result1.errmsg == "noright" || result2.errmsg == "noright") {
            this.hasRight = false;
          }else {
            this.setState({
              menus: result1.btnMenu || [],
              condition: result2.condition || []
            });
            this.form.initFormFields(result2.condition);  
            this.hasRight = true;
          }
        }else {
          this.hasRight = false;
        }
        this.setState({loading: false});
      })
    }

    @action getBaseMenus = (params={}) => {
      API.getBaseMenus(params).then(result => {
        if(result.status == '1') {
          this.setState({
            menus: result.btnMenu || []
          })
        }
      })
    }
  
    @action getBaseInfoForm = (params={}) => {
      this.form = new WeaForm();
      API.getBaseInfoForm(params).then(result => {
        if(result.status && result.errmsg == "noright") {
          this.hasRight = false;
        }else {
          this.hasRight=true;
          this.setState({
            condition: result.condition || []
          });
          this.form.initFormFields(result.condition);
        }
        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 = () => {
      API.getConfigurationResult().then(result => {
        if(result.status == 1) {
          this.setState({
            testResultDatas: result.resultList || [],
            testResultColumns: [{
              title: getLabel(516678, "检查项"),
              dataIndex: "item"
            }, {
              title: getLabel(516679, "检查内容"),
              dataIndex: "content"
            }, {
              title: getLabel(516680, "检查结果"),
              dataIndex: "result"
            }]
          })
        }
      })
    }
  
    @action getBaseInfoFormOperation = (params={}, callback) => {
      this.setState({
        buttonStatus: true
      })
      API.getBaseInfoFormOperation(params).then(result => {
        if(result.status == 1) {
          if('checkCron' === params.operate) {
            if(result.msg) {
              message.error(result.msg);
            } else {
              if(callback && typeof callback === "function") {
                callback();
              }
            }
          } else {
            message.success(result.msg);
            if(params.operate === "save") {
              this.getBaseInfoForm();
            }
          }
        }
        this.setState({
          buttonStatus: false
        })
      });
    };

    @action getExchangeLogInfo = () => {
      this.searchForm = new WeaForm();
      this.tableStore = new TableStore();
      Promise.all([
        API.getExchangeLogList(),
        API.getExchangeCondition(),
      ]).then(([result1, result2]) => {
        if(result1.sessionkey) {
          this.tableStore.getDatas(result1.sessionkey, 1);
        }
        if(result2.status) {
          this.searchForm.initFormFields(result2.condition);
          this.setState({
            advancedHeight: getSearchFormHeight(result2.condition),
            searchCondition: result2.condition || []
          })
        }
      })
    }

    @action getExchangeLogList = (params={}) => {
      this.tableStore = new TableStore();
      API.getExchangeLogList(params).then(result => {
        if(result.sessionkey) {
          this.tableStore.getDatas(result.sessionkey, 1);
        }
      })
    }
  
    @action getDetailInfoFormOperation = (params={}, saveCallBack=null) => {
      API.getDetailInfoFormOperation(params).then(result => {
        if(result.status == "1") {
          if(saveCallBack && typeof(saveCallBack) === "function") {
            saveCallBack();
          }
        }
      })
    }

    // 用户登录名设置
    @action doLoginURLInit = (params={}) => {
      this.loginURLForm = new WeaForm();
      API.doSaveUserAndPwd(params).then(result => {
        if(result.status == 1) {
          if(result.errmsg == "noright") {
            this.setState({
              loginURLhasRight: false
            })
          }else {
            this.loginURLForm.initFormFields(result.condition);
            this.setState({
              loginURLCondition: result.condition || [],
              loginURLhasRight: true
            })
          }
        }else {
          this.setState({
            loginURLhasRight: false
          })
        }
        this.setState({
          loginURLLoading: false
        })
      })
    }

    @action doOperationlimit = (params={}, saveCallBack=null) => {
      API.doOperationlimit(params).then(result => {
        if(result.status == 1) {
          if (params.operate === "getButtons") {
            this.setState({
              dataRangeMenus: result.rightMenus || []
            });
          }else if (params.operate === "SaveUserAndPwd") {
            message.success(result.msg);
          }else if(["delShare", "addShare"].includes(params.operate)) {
            message.success(result.msg);
            this.setState({
              showShareForm: false
            });
            this.getExchangelimitsList();
          }else if(params.operate === "getAddShareForm") {
            const {condition=[]} = result;
            let role = [], post = [];
            this.shareForm = new WeaForm();
            this.shareForm.initFormFields(condition);        
            condition && condition[0] && condition[0].items && condition[0].items.forEach(item => {
              const key = item.domkey[0];
              if (['sharevalue2', 'rolelevel'].includes(key)) {
                role.push(item);
              }
              if (['jobtitlelevel', 'jobtitlesharevalue2', 'jobtitlesharevalue3'].includes(key)) {
                post.push(item);
              }
            });
            this.setState({
              shareFormCondition: condition || [],
              role,
              post
            });
          }
        }
        if(saveCallBack && typeof(saveCallBack) === "function") {
          saveCallBack(result);
        }
      })
    }

    @action getExchangelimitsList = (params={}) => {
      this.setState({authLoading: true});
      this.authStore = new TableStore();
      API.getExchangelimitsList(params).then(result => {
        if(result.status == 1) {
          this.authStore.getDatas(result.sessionkey, 1);
          this.setState({authLoading: false});
        }
      })
    }
  }
  