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

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

export class TriggerStore {
  @observable hasRight = false;
  @observable hasManageDetachableRight=false;
  @observable rightLoading = true;
  @observable tableStore = new TableStore();
  @observable tableStoreLog = new TableStore();
  @observable searchForm = new WeaForm();
  @observable searchFormLog = new WeaForm();
  @observable newForm = new WeaForm();
  @observable newDetailForm = new WeaForm();
  @observable triggerIntervalForm = new WeaForm();
  @observable triggerIntervalFormDt = new WeaForm();
  @observable detailAttachmentSetForm = new WeaForm();
  @observable reloadFlowInfo = false;
  @observable timer = '';
  @observable source = '';
  @observable settingRegisterID = '';
  @observable status = {
    hasNonStandard: true,
    nonStandLoading: true,
  };
    
  @action
  setReloadFlowInfo = (val) => {
    this.reloadFlowInfo = val;
  }

  @action cleanStore = () => {
    this.searchFormLog = new WeaForm();
    this.searchForm = new WeaForm();
    this.newForm = new WeaForm();
    this.newDetailForm = new WeaForm();
    this.triggerIntervalForm = new WeaForm();
    this.triggerIntervalFormDt = new WeaForm();
    this.detailAttachmentSetForm = new WeaForm();
    this.setState({
      transformRulesInstance: {},  //转换规则插件化实例
      advanceHeight: 72,
      collectParams: {
        favname: `${getLabel(33720, "流程触发集成")}`,
        favouritetype: 1,
        objid: 0,
        link: "wui/engine.html#/integration/WorkflowTrigger",
        importantlevel: 1
      },
      tabDatas: [{
        color: "#000000",
        groupid: "flowAll",
        showcount: true,
        title: `${getLabel(32366, "流程触发集成列表")}`,
        viewcondition: 0
      }, {
        color: "#000000",
        groupid: "flowAll",
        showcount: true,
        title: `${getLabel(23112, "触发周期设置")}`,
        viewcondition: 1
      }, {
        color: "#000000",
        groupid: "flowAll",
        showcount: true,
        title: `${getLabel('509133','触发日志')}`,
        viewcondition: 2
      }],
      topTab: [{
        color: "#000000",
        groupid: "flowAll",
        showcount: true,
        title: `${getLabel(81711, "基本信息")}`,
        viewcondition_dt: 0
      }, {
        color: "#000000",
        groupid: "flowAll",
        showcount: true,
        title: `${getLabel(19342, "详细设置")}`,
        viewcondition_dt: 1
      }, {
        color: "#000000",
        groupid: "flowAll",
        showcount: true,
        title: `${getLabel(23136, "触发周期")}`,
        viewcondition_dt: 2
      }],
      selectedKey: 0,
      newDetailFormSelectedKey: 0,
      TriggerConditionInfo: [],
      TriggerConditionInfoLog: [],
      TriggerFormFields: [],
      TriggerFormHiddenFields: [],
      TriggerDetailFormFields: [],
      TriggerDetailFormHiddenFields: [],
      TriggerIntervalFormFields:[],
      TriggerIntervalFormFieldsDt:[],
      isAlertPage: false,
      showSearchAd: false,
      rightMenus: [],
      rightMenusLog: [],
      showNewFormDialog: false,
      showNewDetailFormDialog: false,
      mainFieldListColumnsSet:[],
      mainFieldListColumnsSetData:[],
      resourceOptionList: [],
      hasChangedWorkflowForm: false,
      showAttachmentSetForm: false,
      fieldid: '',
      subcompanyid: "",
    });
  }

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

  @action
  doInit = () => {
    this.setState({
      nonStandLoading: true,
    })
    checkNonstandard({num: "026"}, (result) => {
      this.setState({
        hasNonStandard: result.isOpen,
        nonStandLoading: false,
      })
      if(result.isOpen) {
        checkHasOrganization(hasOrg => {
          this.setState({
            hasOrganization: hasOrg,
          })
        })
        this.cleanStore();
        this.getTriggerCondition({}, this.getTriggerListInfo);
        // this.getTriggerRightMenu();
        // this.getTriggerList();
        // this.getTriggerAddForm();
        // this.getTriggerIntervalSetForm();
        // this.getTriggerLogList();
        // this.getTriggerLogCondition();
        // this.getTriggerLogRightMenu();
      }
    })
  };

  getTriggerLogList = () => {
    this.tableStoreLog = new TableStore();
    let params = Object.assign({}, this.searchFormLog.getFormParams(), {subcompanyid: this.status.subcompanyid});
    API.getTriggerLogList(params).then(result => {
      if (result.sessionkey) {
        this.tableStoreLog.getDatas(result.sessionkey, 1);
      }
    });
  };

  getTriggerLogRightMenu = (params={}) => {
    params = Object.assign({}, params, {subcompanyid: this.status.subcompanyid});
    API.getTriggerLogRightMenu(params).then(result => {
      this.setState({
        rightMenusLog: result.rightMenus || [],
      })
    });
  };

  getTriggerLogListInfo = (params1, params2) => {
    this.tableStoreLog = new TableStore();
    params1 = Object.assign({}, params1, this.searchFormLog.getFormParams(), {subcompanyid: this.status.subcompanyid});
    params2 = Object.assign({}, params2, {subcompanyid: this.status.subcompanyid});
    Promise.all([
      API.getTriggerLogList(params1),
      API.getTriggerLogRightMenu(params2)
    ]).then(([result1, result2]) => {
      if (result1.ret && result1.ret == "noIntegrationdetachable") {
        this.hasManageDetachableRight = false;
      } else {
        this.hasManageDetachableRight = true;
      }
      if (result1.ret && result1.ret == "noright") {
        this.hasRight = false;
      }else {
        this.hasRight = true;
      }
    
      if (result1.sessionkey) {
        this.tableStoreLog.getDatas(result1.sessionkey, 1);
      }
      this.setState({
        rightMenusLog: result2.rightMenus || [],
      })
    })
  }

  getTriggerLogCondition = (params={}, callBack=null) => {
    this.searchFormLog = new WeaForm();
    params = Object.assign({}, params, {subcompanyid: this.status.subcompanyid});
    API.getTriggerLogCondition(params).then(result => {
      if(result.status == 1) {
        this.setState({
          TriggerConditionInfoLog: result.condition || [],
          advanceHeight: getSearchFormHeight(result.condition) || 72,
        })
        this.searchFormLog.initFormFields(result.condition);
      }
      if(isCallBackFunction(callBack)) {
        callBack();
      }
    });
  };

  getTriggerList = () => {
    this.tableStore = new TableStore();
    let formParams = (this.searchForm && this.searchForm.getFormParams()) || {};
    let typename = this.source ? {typename: this.source} : {};
    let params = Object.assign({}, formParams, typename, {subcompanyid: this.status.subcompanyid});
    API.getTriggerList(params).then(result => {
      if (result.ret && result.ret == "noIntegrationdetachable") {
        this.hasManageDetachableRight = false;
      } else {
        this.hasManageDetachableRight = true;
      }
      if (result.ret && result.ret == "noright") {
        this.hasRight = false;
      }else {
        this.hasRight = true;
      }
      this.rightLoading = false;

      if (result.sessionkey) {
        this.tableStore.getDatas(result.sessionkey, 1);
      }
    });
  };

  getTriggerRightMenu = (params={}) => {
    params = Object.assign({}, params, {subcompanyid: this.status.subcompanyid});
    API.getTriggerRightMenu(params).then(result => {
      this.setState({
        rightMenus: result.rightMenus || [],
      });
    });
  };

  getTriggerListInfo = (params1={}, params2={}) => {
    this.tableStore = new TableStore();
    let typename = this.source ? {typename: this.source} : {};
    params1 = Object.assign({}, params1, this.searchForm.getFormParams(), typename, {subcompanyid: this.status.subcompanyid});
    params2 = Object.assign({}, params2, {subcompanyid: this.status.subcompanyid});
    Promise.all([
      API.getTriggerList(params1),
      API.getTriggerRightMenu(params2),
    ]).then(([result1, result2]) => {
      if (result1.ret && result1.ret == "noIntegrationdetachable") {
        this.hasManageDetachableRight = false;
      } else {
        this.hasManageDetachableRight = true;
      }
      if (result1.ret && result1.ret == "noright") {
        this.hasRight = false;
      }else {
        this.hasRight = true;
      }
    
      if (result1.sessionkey) {
        this.tableStore.getDatas(result1.sessionkey, 1);
      }
      this.setState({
        rightMenus: result2.rightMenus || [],
      });
      this.rightLoading = false;
    })
  }

  getTriggerCondition = (params={}, callBack=null) => {
    this.searchForm = new WeaForm();
    params = Object.assign({}, params, {subcompanyid: this.status.subcompanyid});
    API.getTriggerCondition(params).then(result => {
      if(result.status == 1) {
        this.setState({
          TriggerConditionInfo: result.condition || [],
          advanceHeight: getSearchFormHeight(result.condition) || 72,
        })
        this.searchForm.initFormFields(result.condition);
      }
      if(isCallBackFunction(callBack)) {
        callBack();
      }
    });
  };

  setSetRettingRegisterID = (val) => {
      this.settingRegisterID = val;
  }

  getTriggerAddForm = (params={}, callBack=null) => {
    this.newForm = new WeaForm();
    if(!params.viewid || params.viewid == "") {
      params = Object.assign({}, params, {subcompanyid: this.status.subcompanyid});
    }
    API.getTriggerAddForm(params).then(result => {
      result.condition && result.condition.forEach((data, index) => {
        data && data.items && data.items.forEach((item, idx) => {
          if(['successback', 'failback', 'outermainwhere', 'outerdetailwhere0', 'outerdetailwhere1'].includes(item.domkey[0])) {
            result.condition[index].items[idx].maxRows = 4;
          }
        })
      });
      this.setState({
        TriggerFormFields: result.condition || [],
        menus: result.rightMenus || [],
      });
      if(params && (!params.from)){
        this.setState({
          TriggerFormHiddenFields: result.hiddenFields || []
        });
      }
      this.newForm.initFormFields(result.condition);
      if(callBack && typeof(callBack) === "function") {
        callBack();
      }
    });
  };

  // 在获取form表单的时候同时设置jsname
  getTriggerEditDeatilData = (datas=[]) => {
    return datas && datas.map(item => {
      let jsname = '';

      if(item.com) {
        if(item.com.rulesopt && item.com.rulesopt.length) {
          let data = item.com.rulesopt[0];

          if(data && 'SELECT' === data.type.toLocaleUpperCase() && data.options && data.options.length) {
            let option = data.options.find(c => c.key === item.rulesopt);

            if(option) {
              jsname = option.jsname || '';
            }
          }
        }
      }
      return {
        ...item,
        jsname,
      }
    }); 
  }

  @action('获取详情')
  getTriggerEditDetailForm = (params, flag) => {
    this.newDetailForm = new WeaForm();
    API.getTriggerEditDetailForm(params).then(result => {
      let i = 1;
      while(result[`detailFieldListColumnsSet${i}`]) {
        // 获取明细的值
        let detailTableDatas = result[`detailFieldListColumnsSetData${i}`] 
          ? result[`detailFieldListColumnsSetData${i}`].map(item => {
              return {
                ...item,
                detailIndex: i,
              }
            }) 
          : [];

        this.status = {
          ...this.status,
          [`detailFieldListColumnsSet${i}`]: result[`detailFieldListColumnsSet${i}`],
          [`detailFieldListColumnsSetData${i}`]: this.getTriggerEditDeatilData(detailTableDatas),
        }   
        i++;  
      }
      
      this.setState({
        transformRulesInstance: {},
        TriggerDetailFormFields: result.condition,
        TriggerDetailFormHiddenFields: result.hiddenFields,
        mainFieldListColumnsSet: result.mainFieldListColumnsSet,
        mainFieldListColumnsSetData: this.getTriggerEditDeatilData(result.mainFieldListColumnsSetData),
        resourceOptionList: result.resourceOptionList,
      });
      this.newDetailForm.initFormFields(result.condition);
    });
  };

  getTriggerTest = (params) => {
    API.getTriggerTest(params).then(result => {
      /*this.newForm.initFormFields(result.condition);
      this.status = {
          ...this.status,
          TriggerFormFields: result.condition,
          TriggerFormHiddenFields: result.hiddenFields,
      };*/
    });
  };

  getTriggerOperation = (params = {}, callback) => {
    if(["checkShowName", "add", "edit", "adddetail", "INTERVAL_SAVE"].includes(params.operate)) {
      this.setState({loading: true})
    }
    API.getTriggerOperation(params).then(result => {
      if(params.operate === "getDatasource") {
        this.setState({datashowOptions: result.data || []});
      }else if(params.operate === "deleteLog"){
        if(result.status == "1") {
          message.success(getLabel('20461','删除成功'));
          this.setState({showNewFormDialog: false,rowSelectIdsLog:[]});
          this.getTriggerLogList();
        }else {
          message.error(getLabel('20462','删除失败'));
        }
      }else if(params.operate === "delete") {
        if(result.status == "1") {
          message.success(getLabel('20461','删除成功'));
          this.setState({showNewFormDialog: false,rowSelectIds:[]});
          this.getTriggerList();
        }else {
          message.error(getLabel('20462','删除失败'));
        }
      }else if(params.operate === "add") {
        if(result.status == "1") {
          message.success(getLabel('22619','保存成功'));
          this.setState({showNewFormDialog: false,rowSelectIds:[]});
          this.getTriggerList();
        }else {
          message.error(getLabel('22620','保存失败'));
        }   
      }else if(params.operate != 'test' && params.operate != 'checkShowName') {
        this.getTriggerList();
        this.setState({showNewFormDialog: false,rowSelectIds:[]});
      }
      this.setState({loading: false})
      if(!callback) {
        if(result.errmsgTip) {
          if(result.isError) {
            message.error(result.errmsgTip);
          } else {
            message.success(result.errmsgTip);
          }
        }
      }else {
        if(result.status == 1) {
          isFunction(callback)&& callback(result);
        }
      }
    }).catch(err => {
      this.setState({loading: false});
    })
  };

  getTriggerIntervalSetForm = (params) => {
    this.triggerIntervalForm = new WeaForm();
    API.getTriggerIntervalSetForm(params).then(result => {
      if(result.status == 1) {
        this.setState({
          TriggerIntervalFormFields: result.condition || [],
        });
        this.triggerIntervalForm.initFormFields(result.condition);
      }
    });
  };

  getTriggerIntervalSetFormDt = (params) => {
    this.triggerIntervalFormDt = new WeaForm();
    API.getTriggerIntervalSetForm(params).then(result => {
      if(result.status == 1) {
        this.setState({
          TriggerIntervalFormFieldsDt: result.condition || [],
        });
        this.triggerIntervalFormDt.initFormFields(result.condition);
      }
    });
  };

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

  // 检查表单数据是否被修改
  getTriggerCheckWorkflowForm = (params) => {
    API.getTriggerCheckWorkflowForm(params).then(result => {
      if(result.ret) {
        this.setState({hasChangedWorkflowForm: result.hasChangedWorkflowForm});
      }
    })
  }
  // 重新加载表单数据
  getTriggerResetFormFieldMapping = (params={}, func) => {
    API.getTriggerResetFormFieldMapping(params).then(result => {
      this.setReloadFlowInfo(true);
      if(result.status == '1') {
        if(result.hasResetFieldSet) {
          // 加载之前进行保存（保存一般不会出错）
          API.getTriggerOperation({...this.newForm.getFormParams(), operate: 'checkShowName'}).then(result => {
            if(result.status) {
              let formParams = this.newForm.getFormParams();
              API.getTriggerOperation({...this.status.TriggerFormHiddenFields, ...formParams, operate: 'edit'}).then(result => {
                if(result.status) {
                  message.success(getLabel(390587,'流程信息重新加载成功'));
                  // 加载成功后详细设置页面的数据会进行清空操作，所以重新加载页面信息
                  this.getTriggerEditDetailForm(params);
                  typeof(func) === "function" && func();
                }
              })
            }
          })
        }else {
          message.error(getLabel('390588',"流程信息重新加载失败"));
        }
      }else {
        message.error(getLabel('390588',"流程信息重新加载失败"));
      }
    })
  }

  // 附件的设置
  getTriggerEditDetailAttachmentSetForm = (params) => {
    API.getTriggerEditDetailAttachmentSetForm(params).then(result => {
      if(result.status == '1') {
        this.detailAttachmentSetForm = new WeaForm();
        this.setState({showAttachmentSetForm: true});
        this.detailAttachmentSetForm.setCondition(result.condition);
      }
    })
  }
}
