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

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

export class WhiteListStore {
  @observable tableStore = new TableStore();
  @observable tableStore2 = new TableStore();
  @observable searchForm = new WeaForm();
  @observable detailSearchForm = new WeaForm();
  @observable newForm = new WeaForm();
  @observable logStore = new LogStore();
  @observable status = {
    selectedKey: 0,
    hasRight: false,
    loading: true,
    rightMenus: [],
    operateIndex: "",
    newFormCondition: [],
    hiddenFields: [],
    addOrEditDialogVisible: false,
    searchFormCondition: [],
    detailList: false,
    whiteListLoading: false,
    detailSearchFormCondition: [],
    selectids: []
  };

  @action doInit = () => {
    this.setState({
      selectedKey: 0,
      loading: true,
      operateIndex: "",
      addOrEditDialogVisible: false,
      detailList: false,
      whiteListLoading: false,
      selectids: [],
      buttonLoading: false,
      advanceHeight: 0
    })
    this.getRegisterFilterInfo();
  };

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

  @action getRegisterFilterInfo = (params={}) => {
    this.setState({loading: true});
    Promise.all([
      API.getRegisterFilterList(params),
      API.getRegisterFilterRightMenu(),
      API.getRegisterFilterCondition()
    ]).then(([result1, result2, result3]) => {
      if(result1.status == 1 && result2.status == 1 && result3.status == 1) {
        if(result1.ret === "noright") {
          this.setState({
            hasRight: false,
            loading: false
          });
        }else {
          if(result1.sessionkey) {
            this.tableStore = new TableStore();
            this.tableStore.getDatas(result1.sessionkey, 1);
          }
          let advanceHeight = 0;
          if(result3.condition) {
            this.searchForm = new WeaForm();
            this.searchForm.initFormFields(result3.condition);
            advanceHeight = getSearchFormHeight(result3.condition);
          }
          this.setState({
            rightMenus: result2.rightMenus || [],
            searchFormCondition: result3.condition || [],
            advanceHeight,
            loading: false,
            hasRight: true
          })
        }
      }
    }).catch(err => {
      this.setState({
        loading: false,
        hasRight: false
      })
    })
  };

  @action getRegisterFilterList = (params={}) => {
    this.setState({dialogLoading: true});
    params = Object.assign({}, params, this.searchForm.getFormParams());
    API.getRegisterFilterList(params).then(result => {
      if(result.status == 1 && result.sessionkey) {
        this.tableStore = new TableStore();
        this.tableStore.getDatas(result.sessionkey, 1);
      }
      this.setState({dialogLoading: false});
    }).catch(err => {
      this.setState({dialogLoading: false});
      console.log(err);
    })
  };

  @action getRegisterFilterForm = (params={}) => {
    this.setState({dialogLoading: true, buttonLoading: true});
    API.getRegisterFilterForm(params).then(result => {
      if(result.status == 1) {
        if(result.condition && result.condition[0] && result.condition[0].items) {
          let index = result.condition[0].items.findIndex(v => v.domkey[0] === "desc");
          result.condition[0].items[index].maxRows = '4';
          result.condition[0].items[index].minRows = '4';
        }
        this.newForm = new WeaForm();
        this.newForm.initFormFields(result.condition);
        this.setState({
          newFormCondition: result.condition || [],
          hiddenFields: result.hiddenFields || {}
        });
      }
      this.setState({dialogLoading: false, buttonLoading: false});
    }).catch(err => {
      this.setState({dialogLoading: false, buttonLoading: false});
    })
  }

  @action getFilterFormInfo = (params={}, params1={}) => {
    this.setState({dialogLoading: true, buttonLoading: true});
    Promise.all([
      API.getRegisterFilterForm(params),
      API.getWhiteList(params1),
      API.getRegisterFilterSelectedWhiteList(params1)
    ]).then(([result1, result2, result3]) => {
      if(result1.status == 1 && result2.status == 1 && result3.status == 1) {
        if(result1.condition && result1.condition[0] && result1.condition[0].items) {
          let index = result1.condition[0].items.findIndex(v => v.domkey[0] === "desc");
          result1.condition[0].items[index].maxRows = '4';
          result1.condition[0].items[index].minRows = '4';
        }
        this.newForm = new WeaForm();
        this.newForm.initFormFields(result1.condition);
        if(result2.sessionkey) {
          this.tableStore2 = new TableStore();
          this.tableStore2.getDatas(result2.sessionkey);
        }
        let selectids = [];
        if(result3.selectedIds) {
          try{
            selectids = JSON.parse(result3.selectedIds);
          }catch(err) {
            selectids = [];
          }
        }
        this.setState({
          newFormCondition: result1.condition || [],
          hiddenFields: result1.hiddenFields || {},
          selectids
        });
      }
      this.setState({dialogLoading: false, buttonLoading: false});
    }).catch(err => {
      this.setState({dialogLoading: false, buttonLoading: false});
    })
  };

  @action getRegisterFilterFormOperation = (params={}, callback=null) => {
    this.setState({buttonLoading: true});
    API.getRegisterFilterFormOperation(params).then(result => {
      if(result.status == 1) {
        const {id=""} = result;
        if(["add", "edit"].includes(params.operation)) {
          if(params.type === "BTN_SAVE_DETAIL") {
            this.setState({
              addOrEditDialogVisible: true,
              operateIndex: id
            });
          }else {
            this.setState({addOrEditDialogVisible: false});
          }
          message.success(getLabel('22619','保存成功'));
        }else if(params.operation === "delete") {
          message.success(getLabel('20461','删除成功'));
        }
        this.getRegisterFilterList();
        if(callback && typeof(callback) === "function") {
          callback({id}, {filter_id: id, isview: "2"});
        }
      }
      this.setState({buttonLoading: false});
    }).catch(err => {
      this.setState({buttonLoading: false});
    })
  };

  @action getWhiteListInfo = (params={}) => {
    this.setState({loading: true});
    Promise.all([
      API.getWhiteList(params),
      API.getWhiteListRightMenu(),
      API.getBaseInfoCondition()
    ]).then(([result1, result2, result3]) => {
      if(result1.status == 1 && result2.status == 1 && result3.status == 1) {
        if(result1.sessionkey) {
          this.tableStore = new TableStore();
          this.tableStore.getDatas(result1.sessionkey, 1);
        }
        let advanceHeight = 0;
        if(result3.condition) {
          this.searchForm = new WeaForm();
          this.searchForm.initFormFields(result3.condition);
          advanceHeight = getSearchFormHeight(result3.condition);
        }
        this.setState({
          advanceHeight,
          rightMenus: result2.rightMenus || [],
          searchFormCondition: result3.condition || []
        })
      };
      this.setState({loading: false});
    }).catch(err => {
      this.setState({loading: false});
    })
  };

  @action getWhiteList = (params={}) => {
    const {selectedKey} = this.status;
    this.setState({dialogLoading: true});
    if(selectedKey == 1) {
      params = Object.assign({}, params, this.searchForm.getFormParams());
    }else if(selectedKey == 0) {
      params = Object.assign({}, params, this.detailSearchForm.getFormParams());
    }
    API.getWhiteList(params).then(result => {
      if(selectedKey == 0 && result.status == 1 && result.sessionkey) {
        this.tableStore2 = new TableStore();
        this.tableStore2.getDatas(result.sessionkey, 1);
      }else if(selectedKey == 1 && result.status == 1 && result.sessionkey) {
        this.tableStore = new TableStore();
        this.tableStore.getDatas(result.sessionkey, 1);
      }
      this.setState({dialogLoading: false});
    }).catch(err => {
      this.setState({dialogLoading: false});
      console.log(err);
    })
  };

  @action getBaseInfoCondition = (params={}) => {
    API.getBaseInfoCondition().then(result => {
      if(result.status == 1) {
        this.detailSearchForm = new WeaForm();
        this.detailSearchForm.initFormFields(result.condition);
        this.setState({
          detailSearchFormCondition: result.condition || []
        })
      }
    })
  }

  @action getBaseInfoForm = (params) => {
    this.setState({dialogLoading: true, buttonLoading: true});
    API.getBaseInfoForm(params).then(result => {
      if(result.status == 1) {
        if(result.condition && result.condition[0] && result.condition[0].items) {
          let index = result.condition[0].items.findIndex(v => v.domkey[0] === "desc");
          result.condition[0].items[index].maxRows = '4';
          result.condition[0].items[index].minRows = '4';
        }
        this.newForm = new WeaForm();
        this.newForm.initFormFields(result.condition);
        this.setState({
          newFormCondition: result.condition || [],
          hiddenFields: result.hiddenFields || {}
        });
      } 
      this.setState({dialogLoading: false, buttonLoading: false});  
    }).catch(err => {
      this.setState({dialogLoading: false, buttonLoading: false});  
    })
  };

  @action getBaseInfoFormOperation = (params={}, callback=null) => {
    this.setState({buttonLoading: true});
    API.getBaseInfoFormOperation(params).then(result => {
      if(result.status == 1) {
        if(["add", "edit"].includes(params.operation)) {
          this.setState({addOrEditDialogVisible: false});
          message.success(getLabel('22619','保存成功'));
        }else if(params.operation === "delete") {
          message.success(getLabel('20461','删除成功'));
        }
        this.getWhiteList();
        if(callback && typeof(callback) === "function") {
          callback();
        }
      }
      this.setState({buttonLoading: false});
    }).catch(err => {
      this.setState({buttonLoading: false});
    })
  };

  @action getWhiteListMappingOperation = (params={}) => {
    this.setState({whiteListLoading: true});
    API.getWhiteListMappingOperation(params).then(result => {
      if(result.status) {
        if(params.operation === "delete") {
          message.success(getLabel('513640','地址删除成功'));
        }else if(params.operation === "add") {
          message.success(getLabel('513641','地址添加成功'));
        }
        this.getRegisterFilterSelectedWhiteList(params);
        this.tableStore2.reloadCurrent();
      }
      this.setState({whiteListLoading: false});
    }).catch(err => {
      this.setState({whiteListLoading: false});
    })
  };

  @action getRegisterFilterSelectedWhiteList = (params) => {
    this.setState({whiteListLoading: true});
    API.getRegisterFilterSelectedWhiteList(params).then(result => {
      let selectids = [];
      if(result.selectedIds && result.status == 1) {
        try{
          selectids = JSON.parse(result.selectedIds);
        }catch(err) {
          selectids = []
        }
      }
      this.setState({
        whiteListLoading: false,
        selectids
      });
    }).catch(err => {
      this.setState({
        whiteListLoading: false,
        selectids: []
      });
    })
  }
  
  @action getRegisterFilterisValid = (params={}, func) => {
    API.getRegisterFilterisValid(params).then(result => {
      if(result.isValid == "true") {
        func && typeof func === "function" && func();
      }else {
        this.newForm.showError("clazz", getLabel('513784','过滤器类路径无效'));
      }
    })
  }

  /**
   * cas,webseal获取id后查询白名单数据
   */
  @action getRegisterFilterId = (params={}, saveCallBack) => {
    API.getRegisterFilterId(params).then(result => {
      if(result.status == 1) {
        let filter_id = result.id;
        Promise.all([
          API.getRegisterFilterSelectedWhiteList({filter_id, isview: "2"}),
          API.getWhiteList({filter_id, isview: "2"})
        ]).then(([result1, result2]) => {
          if(result1.status == 1 && result2.status == 1) {
            let selectids = [];
            if(result1.selectedIds) {
              try{
                selectids = JSON.parse(result1.selectedIds);
              }catch(err) {
                selectids = [];
              }
            }
            this.setState({
              selectids,
              operateIndex: filter_id
            });
            if(result2.sessionkey) {
              this.tableStore2 = new TableStore();
              this.tableStore2.getDatas(result2.sessionkey, 1);
            }
            saveCallBack && typeof saveCallBack === "function" && saveCallBack();
          }
        })
      }
    })
  }
}
