import { observable, action } from "mobx";
import { WeaTableNew, WeaForm, WeaLogView } from "comsMobx";
import { doFormReset } from "../util/index.js";
import API from "../apis/Schedule";
import { message } from 'antd'
import { WeaLocaleProvider } from 'ecCom';
import {
  checkHasOrganization,
  isCallBackFunction,
} from '../util/IntegrationUtil';
const getLabel = WeaLocaleProvider.getLabel;
const { TableStore } = WeaTableNew;
const {LogStore} = WeaLogView;

class Schedule {
  @observable hasRight = false;
  @observable hasManageDetachableRight = false;
  @observable taskList = new TableStore();
  @observable runLogTableStore = new TableStore();
  @observable sysLogTableStore = new TableStore();
  @observable triggerTableStore = new TableStore();
  @observable dropMenuDatas = [];
  @observable searchAd = new WeaForm();
  @observable systemLogForm = new WeaForm();
  @observable monitorForm = new WeaForm();
  @observable searchAdConditions = [];
  @observable loading = false;
  @observable systemLog = new LogStore();
  @observable systemLogView = false;
  @observable
  createTask = {
    show: false,
    form: new WeaForm(),
    conditions: [],
    isEdit: false,
    editData: {
      runstatus: "",
      cronexpr: "",
      id: "",
    },
    menus: [],
  };
  @observable systemAndRunLog = {
    show: false,
    type: 0, // 0 system 1 run
    systemSearchAdvance: new WeaForm(),
    systemSearchAdvanceCondition: [],
    systemTable: new TableStore(),
    runSearchAdvance: new WeaForm(),
    runSearchAdvanceCondition: [],
    runTable: new TableStore(),
  }
  @observable detailTitle = '';
  @observable detailKey = '';
  @observable detailVisible = false;
  @observable showParams = false;
  @observable detailRecord = {};
  @observable zhangChenFields = {};

  @observable
  status = {
    selectedKey: 0,
    showSearchAd: false,
    rightMenus: [],
    rightMenus2: [],
    rightMenus3: [],

    condition:[],
    condition2:[],
    condition3:[],

    rowSelectIds: [],
    showNewFormDialog: false,
    advancedSearchHeight:160,
    monitorFormCondition: [],
    systemLogFormCondition: [],
    record: [],    
  };

  @observable refTableEdit = null;
  @observable tableEdit = [];
  @observable tableEditDatas = [];
  recordId = '';
  @observable rightLoading = true;
  @observable flag = false;

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

  @action setDetailTitle = (val) => {
    this.detailTitle= val;
  }

  @action updateDetailkey = (val) => {
    this.detailKey = val;
  }

  @action setDetailVisible = (val) => {
    this.detailVisible = val;
  }

  @action setShowParams = (val) => {
    this.showParams = val;
  }

  @action setDetailRecord = (val) => {
    this.detailRecord = val;
  }

  zhangChenGetDatas = (id) => {
    API.getdata({ id }).then(res => {
      this.zhangChenFields = res;
    });
  }

  @action getDetailTable = () => {
    this.viewdetailColumns = [];
    this.viewdetailDatas = [];
    this.viewdetailTitles = [];
    this.detailRecord && this.detailRecord.mainId && 
      API.viewDetail({
        belongMainId: this.detailRecord.mainId,
        id: this.detailRecord.randomFieldId,
      }).then(result => {
        this.viewdetailColumns = result.columns;
        this.viewdetailDatas = result.datas;
        this.viewdetailTitles = result.title;
        API.trans({ id: this.detailRecord.randomFieldId })
          .then(transRes => {
            if (transRes.status && transRes.info) {
              this.setDetailRecord(transRes.info);
            }
            this.setDetailVisible(true);
          })
          .catch(e => {
            this.setDetailVisible(true);
          });
      })
    !this.detailRecord.mainId &&
      API.trans({ id: this.detailRecord.randomFieldId })
        .then(transRes => {
          if (transRes.status && transRes.info) {
            this.setDetailRecord(transRes.info);
          }
          this.setDetailVisible(true);
        })
        .catch(e => {
          this.setDetailVisible(true);
        });
  }

  @action("clean store")
  cleanStore = () => {
    this.hasManageDetachableRight = false;
    this.hasRight = false;
    this.rightLoading = true;
    this.searchAd = new WeaForm();
    this.systemLogForm = new WeaForm();
    this.monitorForm = new WeaForm();
    this.searchAdConditions = [];
    this.setState({
      selectedKey: 0,
      showSearchAd: false,
      rightMenus: [],
      rightMenus2: [],
      rightMenus3: [],
      condition:[],
      condition2:[],
      condition3:[],
      rowSelectIds: [],
      advancedSearchHeight:160,
      subcompanyid: "", 
      systemLogFormCondition: [],
      monitorFormCondition: [],
    });
    this.systemAndRunLog = {
      show: false,
      type: 0, // 0 system 1 run
      systemSearchAdvance: new WeaForm(),
      systemSearchAdvanceCondition: [],
      systemTable: new TableStore(),
      runSearchAdvance: new WeaForm(),
      runSearchAdvanceCondition: [],
      runTable: new TableStore(),
    };
    this.createTask = {
      show: false,
      form: new WeaForm(),
      conditions: [],
      isEdit: false,
      editData: {
        runstatus: "",
        cronexpr: "",
        id: "",
      },
      menus: [],
    };
  }

  @action
  doInit = () => {
    this.cleanStore();
    checkHasOrganization((result) => {
      this.setState({
        hasOrganization: result,
      })
    });
    this.getSearchAd(this.getListInfo);
  };
  setRecordId = (val) => {
    this.recordId = val;
  }

  initAddForm = (params={}) => {
    if(!(params && params.id)) {
      params = Object.assign({}, params, {subcompanyid: this.status.subcompanyid});
    }
    this.createTask.menus = [];
    this.getForm(params);
    this.getFormRightMenus(params);
  };

  getFormRightMenus = (params={}) => {
    this.loading = true;
    API.getFormRightMenus(params).then(res => {
      this.createTask.menus = res.rightMenus || [];
      this.loading = false;
    })
  }

  getForm = (params={}) => {
    this.loading = true;
    this.flag = false;
    API.getForm(params).then(res => {
      this.loading = false;
      if(res.status == '1') {
        this.createTask.form = new WeaForm();
        res.condition[0] && res.condition[0].items.find(v => v.domkey[0] === "cronexpr") && (!res.condition[0].items.find(v => v.domkey[0] === "cronexpr").value) && (res.condition[0].items.find(v => v.domkey[0] === "cronexpr").value = '0 0 * * * ?')
        if(res.condition[0] && res.condition[0].items.find(v => v.domkey[0] === "desc_")) {
          res.condition[0].items.find(v => v.domkey[0] === "desc_").maxRows = 4;
          res.condition[0].items.find(v => v.domkey[0] === "desc_").minRows = 4;
        }
        this.createTask.form.initFormFields(res.condition);
        this.createTask.conditions = (res.condition || []);
        this.tableEdit = res.WeaTableEdit_ScheduleParam_Page;
        this.tableEditDatas = res.WeaTableEdit_ScheduleParam_Data || [];
        this.flag = true;
      }
    })
  }

  getSearchAd = (func) => {
    this.searchAd = new WeaForm();
    this.searchAdConditions = [];
    API.getListConditions({subcompanyid: this.status.subcompanyid}).then(res => {
      if(res.status == '1') {
        this.searchAd.initFormFields(res.condition);
        this.searchAdConditions = res.condition;
        if(isCallBackFunction(func)) {
          func();
        }
      }
    })
  }

  getRunTable = (isOnChange = false) => {
    let params =
      (this.systemAndRunLog.runSearchAdvance && this.systemAndRunLog.runSearchAdvance.getFormParams()) || {};
    API.doRunLog(params).then(res => {
      if (res.datas) {
        isOnChange
          ? this.systemAndRunLog.runTable.getDatas(res.datas, 1)
          : this.systemAndRunLog.runTable.getDatas(res.datas);
      }
    })
  }

  getScheduleRunLogCondition = (func) => {
    this.systemAndRunLog.runSearchAdvance = new WeaForm();
    API.getScheduleRunLogCondition({subcompanyid: this.status.subcompanyid}).then(res => {
      if(res.status == '1') {
        this.systemAndRunLog.runSearchAdvance.initFormFields(res.condition);
        this.systemAndRunLog.runSearchAdvanceCondition = res.condition;
        typeof(func) === 'function' && func();
      }
    })
  }

  @action getScheduleMonitorCondition = (func) => {
    this.monitorForm = new WeaForm();
    API.getScheduleMonitorCondition().then(result => {
      if(result.status == '1') {
        this.monitorForm.initFormFields(result.condition);
        this.setState({monitorFormCondition: result.condition});
        typeof(func) === 'function' && func();
      }
    })
  }

  getListRightMenus = params => {
    params = Object.assign({}, params, {subcompanyid: this.status.subcompanyid});
    API.getListRightMenus(params).then(res => {
      this.dropMenuDatas = res.btnMenu || [];
    });
  };

  getRunLogList = (p) => {
    this.runLogTableStore = new TableStore();
    let params =
      (this.systemAndRunLog.runSearchAdvance && this.systemAndRunLog.runSearchAdvance.getFormParams()) || {};
    params = Object.assign({}, params, p, {subcompanyid: this.status.subcompanyid});
    API.doRunLog(params).then(result => {
      if(result.ret && result.ret == "false"){
        this.hasManageDetachableRight = false;
      }else {
        this.hasManageDetachableRight = true;
      }
      if (result.datas) {
        this.runLogTableStore.getDatas(result.datas,1);
      } else {
        this.status = { ...this.status, isAlertPage: true };
      }
    });
  };

  getSysLogList = () => {
    let formParams = this.systemLogForm.getFormParams();
    let params = Object.assign({}, { "logType": 15, "logSmallType": 12 }, formParams, {endDate: formParams.startDate, operateTime: 6, operatorSubcompany: this.status.subcompanyid || ""});
    API.getSysLog(params).then(result => {
      if (result.sessionkey) {
        this.hasManageDetachableRight = true;
        this.sysLogTableStore = new TableStore();
        this.sysLogTableStore.getDatas(result.sessionkey,1);
      } else {
        this.hasManageDetachableRight = false;
        this.status = { ...this.status, isAlertPage: true };
      }
    });
  };

  getTriggerList = (p) => {
    let params = Object.assign({}, p, this.monitorForm.getFormParams());
    API.getTriggerList(params).then(result => {
      if (result.sessionkey) {
        this.triggerTableStore = new TableStore();
        this.triggerTableStore.getDatas(result.sessionkey,1);
      } else {
        this.status = { ...this.status, isAlertPage: true };
      }
    });
  };

  getListInfo = (params1, params2) => {
    this.loading = true;
    params1 = Object.assign({}, params1, this.searchAd ? this.searchAd.getFormParams() : {}, {subcompanyid: this.status.subcompanyid});
    params2 = Object.assign({}, params2, {subcompanyid: this.status.subcompanyid});
    Promise.all([
      API.getList(params1),
      API.getListRightMenus(params2),
    ]).then(([result1, result2]) => {
      if(result1.ret && result1.ret == "false"){
        this.hasManageDetachableRight = false;
      }else {
        this.hasManageDetachableRight = true;
      }
      this.loading = false;
      this.rightLoading = false;
      if (result1.datas) {
        this.taskList.getDatas(result1.datas, 1);
      }
      this.dropMenuDatas = result2.btnMenu || [];
    })
  }

  getList = (isOnChange = false) => {
    this.loading = true;
    if (isOnChange) {
      this.searchAd.clear();
    }
    let params = Object.assign({}, this.searchAd ? this.searchAd.getFormParams() : {}, {subcompanyid: this.status.subcompanyid});
    API.getList(params).then(res => {
      if(res.ret && res.ret=="false"){
        this.hasManageDetachableRight = false;
      }else{
        this.hasManageDetachableRight = true;
      }
      this.loading = false;
      this.rightLoading = false;
      if (res.datas) {
        this.taskList.getDatas(res.datas, 1);
      }
    });
  };

  insert = params => {
    this.loading = true;

    API.insert(params).then(res => { 
      this.loading = false;
      if(res.status === '-1') {
        message.error(res.errorMsg)
        return;
      }
      this.createTask.show = false;
      message.success(getLabel('22619', '保存成功'));
      doFormReset(this.createTask.form, this.createTask.conditions);
      this.getList();
    }).catch(err => {
      this.loading = false;
    })
  };

  update = params => {
    this.loading = true;
    API.update(params).then(res => {
      this.loading = false;
      if (res.status === "-1") {
        message.error(res.errorMsg)
        return;
      }
      if (res.status === "1") {
        this.createTask.show = false;
        message.success(getLabel('22619', '保存成功'));
        doFormReset(this.createTask.form, this.createTask.conditions);
        this.getList();
      }
    }).catch(err => {
      this.loading = false;
    })
  };

  deleteById = params => {
    this.loading = true;
    API.delete(params).then(res => {
      if (res.status === "1") {
        message.success(getLabel('30700','操作成功'));
        this.loading = false;
        this.getList();
      }else {
        message.error(getLabel('30651','操作失败'));
      }
    });
  };

  batchDelete = params => {
    API.batchDelete(params).then(res => {
      if (res.status === "1") {
        message.success(getLabel('20461','删除成功'));
        this.getList();
      }else {
        message.error(getLabel('20462','删除失败'));
      }
    });
  };

  start = params => {
    this.loading = true;
    API.start(params).then(res => {
      this.loading = false;
      if(res.flag === 'success') {
        message.success(getLabel('30700','操作成功'));
        this.getList();
      }else {
        message.error(getLabel('30651','操作失败'));
      }
    })
  }

  stop = params => {
    this.loading = true;
    API.stop(params).then(res => {
      this.loading = false;
      if(res.flag === 'success') {
        message.success(getLabel('30700','操作成功'));
        this.getList();
      }else {
        message.error(getLabel('30651','操作失败'));
      }
    })
  }
  pause = params => {
    this.loading = true;
    API.pause(params).then(res => {
      this.loading = false;
      if(res.flag === 'success') {
        message.success(getLabel('30700','操作成功'));
        this.getList();
      }else {
        message.error(getLabel('30651','操作失败'));
      }
    })
  }
  resume = params => {
    this.loading = true;
    API.resume(params).then(res => {
      this.loading = false;
      if(res.flag === 'success') {
        message.success(getLabel('30700','操作成功'));
        this.getList();
      }else {
        message.error(getLabel('30651','操作失败'));
      }
    })
  }
  immediatelyRun = params => {
    this.loading = true;
    API.immediatelyRun(params).then(result => {
      if(result.result){
        message.success(getLabel('30700','操作成功'));
        this.getList();
      }else {
        if(result.errorMsg) {
          message.error(result.errorMsg);
        } else {
          message.error(getLabel('30651','操作失败'));
        }
      }
    })
  }
  test = params => {
    this.loading = true;
    API.test(params).then(result => {
      if(result.status === '1') {
        if(result.result){
          message.success(getLabel('506670','测试成功'));
        }else {
          message.error(`${getLabel('503908','测试失败')},${result.errorMsg}`);
        }
      }
    })
  }

  @action getScheduleSysLogCondition = (func) => {
    this.systemLogForm = new WeaForm();
    API.getScheduleSysLogCondition({operatorSubcompany: this.status.subcompanyid || ""}).then(result => {
      if(result.status == '1') {
        this.systemLogForm.initFormFields(result.condition);
        this.setState({systemLogFormCondition: result.condition});
        typeof(func) === 'function' && func();
      }
    })
  }
}

export default Schedule;
