import { observable, action, toJS, computed, useStrict, runInAction } from "mobx";
import API from "../apis/coremail";
import { WeaTableNew, WeaForm, WeaLogView } from "comsMobx";
import { doFormReset } from "../util/index.js";
import {message, Modal} from "antd";
const getLabel = WeaLocaleProvider.getLabel;

import {WeaLocaleProvider} from "ecCom";
import {checkTableFieldValueUnique} from "../apis/CommonService";
import {checkNonstandard} from '../util/IntegrationUtil';

const { TableStore } = WeaTableNew;

class CoreMail {
  @observable pageForm = new WeaForm();
  @observable pageFormConditions = [];

  @observable logFormTable = new TableStore();
  @observable tableStore = new TableStore();

  @observable logSearchForm = new WeaForm();
  @observable listSearchForm = new WeaForm();
  @observable newForm = new WeaForm();
  @observable logSearchFormConditions = [];
  @observable tabConditons = [];
  @observable hasRight = false;
  @observable operateIndex = '';
  @observable flag = false;
  @observable timer;
  @observable selectedListIndex='';
  @observable
  status = {
    loading: false,
    tabSelected: 0,
    searchShow: false,
    searchValue: "",
    rightLoading: true,
    coremailRightMenu: [],
    listSearchCondition: [],
    coremailDialogVisible: false,
    newFormCondition: [],
  }

  @observable
  buttons = {
    base: [],
    baseRight: []
  }

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

  initPage = () => {
    this.setState({
      nonStandLoading: true
    })
    checkNonstandard({num: "093"}, (result) => {
      this.setState({
        hasNonStandard: result.isOpen,
        nonStandLoading: false
      })
      if(result.isOpen) {
        this.getDatas();
        this.getCoreMailList();
        this.getCoreMailRightMenu();
        this.getCoreMailCondition();
        this.getFields();
        this.baseGetRightMenu();
        this.getCondition();
        this.status.tabSelected=0;
        this.status.searchShow = false;
      }
    })
  }


  @observable initialList = [];
  @observable showInitDia = false;
  constructor() {
    this.initalCoremailData = this.initalCoremailData.bind(this);
    this.getInitializeData = this.getInitializeData.bind(this);
  }
  @observable initBtnDisabled = false;

  @action getInitializeData(_selectedIndex){
    this.selectedListIndex = _selectedIndex;
    /*const {selectedRowKeys} = this.tableStore;
    _selectedIndex = _selectedIndex != undefined ? _selectedIndex : selectedRowKeys;*/
    //let ids = _selectedIndex.join(',');
    API.getCoreMailOperation({operate: 'showProcess', coremailids: _selectedIndex}).then(data => {
      let dataList = data.result;
      if (dataList && dataList.length > 0) {
        this.initialList = dataList;
        let isSync = true;
        //遍历查看是否经初始化完成
        dataList.map(item => {//未完成
          if(item.subSyncProcess!=''&&item.deptSyncProcess!=''&&item.deptSyncProcess!='') {
            if ((Number(item.subSyncProcess) < 100 && Number(item.subSyncProcess) >= 0) || (Number(item.hrSyncProcess) < 100 && Number(item.hrSyncProcess) >= 0) || (Number(item.deptSyncProcess) < 100 && Number(item.deptSyncProcess) >= 0)) {
              isSync = false;
            }
          }
        });
        if(isSync){//同步完成
          this.initalCoremailData();
        }else{
          this.showInitDia = true;
          this.initProcess(_selectedIndex);
        }
      } else {
        this.initalCoremailData();
      }
    })
  }

  @action initalCoremailData() {
    const {selectedRowKeys} = this.tableStore;
    let ids = selectedRowKeys.join(',');
    if(ids==''){
      ids = this.selectedListIndex;
    }
    //先获取同步状态
    Modal.confirm({
      title: getLabel(131329, '信息确认'),
      content: '确认要同步数据吗？',
      onOk: () => {
        this.showInitDia = true;
        this.initialList = [];
        //可以同步
        let param = {operate: 'init', coremailids: ids};
        API.getCoreMailOperation(param).then((data) => {
          if (data) {
            if (data.status === '1') {//初始化成功，开始获取进度
              if(data.isError){//出现异常
                this.oncancelInit();
                message.error(data.errmsgTip);
              }else{
                this.initProcess(ids);
              }
            } else {
              this.oncancelInit();
              message.error(data.errmsgTip);
            }
          } else {
            this.oncancelInit();
            message.error(getLabel('127315','同步异常') );
          }
        })
      },
      onCancel: () => {
        this.initBtnDisabled = false;
      },
      okText: getLabel(33703, '确认'),
      cancelText: getLabel(31129, '取消')
    });
  }

  //定时获取进度
  @action initProcess =(ids)=> {
    this.clearTimer();
    this.initBtnDisabled = true;
    this.timer = setInterval(() => {
      this.initStatus(ids, this);
    }, 15);
  }


  //进度
  @action initStatus=(ids,obj)=> {
    if(this.initBtnDisabled==false){
      obj.initialList = [];
    }
    let p1 = new Promise((resolve, reject) => {
          API.getCoreMailOperation({operate: 'showProcess', coremailids: ids}).then(data => {
            let dataList = data.result;
            if (dataList && dataList.length > 0) {
              this.initialList = dataList;
              let isSync = true;
              //遍历查看是否经初始化完成
              dataList.map(item => {//未完成
                if(item.subSyncProcess!=''&&item.deptSyncProcess!=''&&item.deptSyncProcess!='') {
                  if ((Number(item.subSyncProcess) < 100 && Number(item.subSyncProcess) >= 0) || (Number(item.hrSyncProcess) < 100 && Number(item.hrSyncProcess) >= 0) || (Number(item.deptSyncProcess) < 100 && Number(item.deptSyncProcess) >= 0)) {
                    isSync  = false;
                  }
                }
              });
              if(isSync){//同步完成
                reject();
              }
            } else {
              reject();
            }
          })
        }
    ).catch(function (reason) {
      obj.clearTimer();
      obj.initBtnDisabled = false;
    })
  }

  @action clearTimer(){
    if(this.timer) {
      clearInterval(this.timer);
    }
  }

  @action getInitalDialog=(selectedIndex)=> {
    this.getInitializeData(selectedIndex);

  }

  @action oncancelInit=()=>{
    this.clearTimer();
    this.showInitDia=false;
  }

  @action
  setStatus = (key, value) => {
    this.status[key] = value;
  }

  @action
  getFields = (params) => {
    this.setStatus("loading", true);
    API.getFields(params).then(res => {
      this.loading = false;
      runInAction(() => {
        this.setStatus("loading", false);
        if(res.data) {
          this.pageForm.initFormFields(res.data.fields);
          this.pageFormConditions = res.data.fields;
        }
      })
    })
  }

  baseGetRightMenu = (params) => {
    this.setStatus("loading", true);
    API.baseGetRightMenu(params).then(res => {
      runInAction(() => {
        this.setStatus("loading", false);
        if(res.data) {
          this.tabConditons = res.data.top && res.data.top.tab ? res.data.top.tab.datas : [];
          this.buttons.base = res.data.button;
          this.buttons.baseRight = res.data.rightMenus;
        }
      })
    })
  }

  save = (params) => {
    this.setStatus("loading", true);
    API.save(params).then(res => {
      runInAction(() => {
        this.setStatus("loading", false);
        if (res.status === "true" && res.error !== "") {
          message.success(res.error);
        }
      })
    })
  }

  init = (params) => {
    this.setStatus("loading", true);
    API.init(params).then(res => {
      runInAction(() => {
        this.setStatus("loading", false);
      })
    })
  }

  test = (params) => {
    this.setStatus("loading", true);
    API.test(params).then(res => {
      runInAction(() => {
        this.setStatus("loading", false);
      })
    })
  }

  getDatas = (params, isOnChange = false) => {
    this.setStatus("loading", true);
    let newParams = params || this.logSearchForm && this.logSearchForm.getFormParams() || {};
    API.getDatas(newParams).then(res => {
      this.setStatus('rightLoading', false);
      if(!res.status) {
        this.hasRight = false;
      }else {
        this.hasRight = true;
        runInAction(() => {
          this.setStatus("loading", false);
          if (res.data && res.data.sessionkey) {
            const params = {};
            params.logType = res.data.logType;
            params.logSmallType = res.data.logSmallType;
            isOnChange
              ? this.logFormTable.getDatas(res.data.sessionkey, 1)
              : this.logFormTable.getDatas(res.data.sessionkey);
          }
        })
      }
    })
  }

  getCondition = params => {
    this.setStatus("loading", true);
    API.getCondition(params).then(res => {
      runInAction(() => {
        this.setStatus("loading", false);
        if(res.data) {
          res.data.condition && this.logSearchForm.initFormFields(res.data.condition);
          this.logSearchFormConditions = res.data.condition || [];
        }
      })
    })
  }

  // 集成列表
  @action getCoreMailList = (params) => {
    params = params || {};
    this.setStatus('rightLoading', true);
    API.getCoreMailList(params).then(result => {
      if(result.status) {
        this.setStatus('rightLoading', false);
        if(result.sessionkey) {
          this.tableStore.getDatas(result.sessionkey, 1);
        }
      }
    })
  }

  @action getCoreMailRightMenu = () => {
    API.getCoreMailRightMenu().then(result => {
      this.setStatus('coremailRightMenu', result.rightMenus || []);
    })
  }

  @action getCoremailMailAddForm = (params) => {
    const {operateIndex} = this.status;
    params = params || {};
    params = Object.assign({}, params, {coremailid: operateIndex});
    this.flag = false;
    API.getCoremailMailAddForm(params).then(result => {
      if(result.status) {
        this.newForm = new WeaForm();
        this.newForm.initFormFields(result.condition);
        this.setStatus('newFormCondition', result.condition);
        this.flag = true;
      }
    })
  }

  @action getCoreMailSaveOperation = () => {
    const {operateIndex} = this.status;
    let params = Object.assign({}, this.newForm.getFormParams(), {coremailid: operateIndex});
    let checkParams = {
      tableName: 'coremailsetting',
      fieldName: 'coremailsys',
      fieldValue:  this.newForm.getFormParams().coremailsys.replace(/^(\s*)|(\s*)$/g, ''),
      idName: 'id',
      idValue: operateIndex
    };
    checkTableFieldValueUnique(checkParams).then(data => {
      if(data && data.isNotUnique && operateIndex=='') {
        this.newForm.showError('coremailsys',getLabel('387654','标识已存在'));
      }else {
        API.getCoreMailSaveOperation(params).then(result => {
          if(result.status) {
            this.setStatus('coremailDialogVisible', false);
            this.getCoreMailList();
            message.success(getLabel('22619','保存成功') );
          }else {
            message.error(getLabel('22620','保存失败') );
          }
        })
      }
    })

  }

  @action getCoreMailDelete = (params) => {
    params = params || {};
    API.getCoreMailDelete(params).then(result => {
      if(result.status) {
        message.success(result.msg);
        this.getCoreMailList();
      }else {
        message.error(result.msg);
      }
    })
  }

  @action testCoreMail=(params={})=>{
    let _params = params;
    if(params.coremailid===''){
      _params = Object.assign({},this.newForm.getFormParams(),params);
    }
    API.getCoreMailOperation(_params).then(result=>{
      if(result.result==='1') {
        message.success(getLabel('506670','测试成功') );
        if(params.coremailid!=''){
          this.getCoreMailList();
        }
      }else {
        message.error(getLabel('503908','测试失败') );
      }
    })
  }
  
  @action getCoreMailCondition = (params) => {
    params = params || {};
    this.listSearchForm = new WeaForm();
    API.getCoreMailCondition(params).then(result => {
      if(result.status) {
        this.listSearchForm.initFormFields(result.condition);
        this.setStatus('listSearchCondition', result.condition);
      }
    })
  }




}
export default CoreMail;