import React from "react";
import { inject, observer } from "mobx-react";
import { toJS } from "mobx";
import { WeaTableNew, WeaLogView } from "comsMobx";
import { Button } from "antd";
import {
  doFormReset,
  doConfirm
} from "../../util/index.js";
import isEmpty from 'lodash/isEmpty';
import {
  WeaLeftRightLayout,
  WeaLocaleProvider,
  WeaRightMenu,
  WeaTop,
  WeaTab,
} from "ecCom";
import AddOrEditTask from "./AddOrEditTask.js";
import RunLog from './RunLog';
import * as IntegrationUtil from "../../util/IntegrationUtil.js";
import NoRight from "../../public/NoRight";
import OrganizationTree from '../../public/OrganizationTree';

const { WeaTable } = WeaTableNew;
const getLabel = WeaLocaleProvider.getLabel;
const WeaLogViewComp = WeaLogView.Component;

@inject("schedule")
@observer
export default class AboutBrowser extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
    };
  }

  componentDidMount() {
    const { schedule } = this.props;
    schedule.doInit();
  }

  componentWillReceiveProps(nextProps) {
    const { schedule } = this.props;
    if (this.props.location.key !== nextProps.location.key) {
      schedule.doInit();
    }
  }
  // 分权刷新
  refreshData = (id, type) => {
    const {
      schedule
    } = this.props, {
      selectedKey,
    } = toJS(schedule.status);
    // 如果点击的是分部
    if("1" === type) {
      schedule.setState({
        subcompanyid: id  
      })
    } else{
      schedule.setState({
        subcompanyid: ""  
      })
    }
    if(selectedKey == 0) {
      schedule.getSearchAd(schedule.getListInfo); 
    } else if (selectedKey == 2) {
      schedule.getScheduleRunLogCondition(schedule.getRunLogList);
    } else if (selectedKey == 1) {
      schedule.getScheduleSysLogCondition(schedule.getSysLogList);
    }
  }

  createTask = () => {
    const { createTask, initAddForm } = this.props.schedule;
    const { form } = createTask;
    form.clear();
    initAddForm();
    createTask.show = true;
    createTask.isEdit = false;
    createTask.editData.cronexpr = "";
  };

  onOperatesClick = (record, recordIndex, operate, opertaeIndex) => {
    const { schedule } = this.props;
    const { deleteById, start, stop, setRecordId,pause ,resume, immediatelyRun, test, getScheduleRunLogCondition, getRunLogList, systemAndRunLog } = schedule;
    switch (Number(opertaeIndex)) {
      // 编辑
      case 0:
        this.doEditById(record);
        break;
      // 删除
      case 1:
        doConfirm(`${getLabel('15097','确定要删除吗？')}`, () => {
          deleteById({ id: record.randomFieldId });
        })
        break;
      // 系统日志
      case 2:
        setRecordId(record.randomFieldId);
        schedule.systemLogView = true;
        break;
      // 启用
      case 3:
        IntegrationUtil.doConfirm(getLabel('385724','确定要启用吗？'), start, { id: record.randomFieldId });
        break;
      // 运行
      case 4:
        IntegrationUtil.doConfirm(getLabel('385359','确定要禁用吗?'), stop, { id: record.randomFieldId });
        break;
      // 禁止
      case 5:
        IntegrationUtil.doConfirm(getLabel('516856','确定要暂停吗？'), pause, { id: record.randomFieldId });
        break;
      case 6:
        IntegrationUtil.doConfirm(getLabel('131519','确定要恢复吗？'), resume, { id: record.randomFieldId });
        break;
      case 7:
        IntegrationUtil.doConfirm(getLabel('516857','确定要执行吗？'), immediatelyRun, { id: record.randomFieldId, pointid: record.pointid });
        break;
      case 8:
        test({ id: record.randomFieldId, pointid: record.pointid })
        break;
      case 9:
        schedule.setState({record: record});
        getScheduleRunLogCondition(() => getRunLogList({id: record.randomFieldId, scheduleid: record.pointid}));
        systemAndRunLog.show = true;
        break;
    }
  };

  doEditById = (record) => {
    const { schedule } = this.props;
    const { createTask, initAddForm } = schedule;
    const { editData } = createTask;
    const { form, conditions } = createTask;
    createTask.show = true;
    createTask.isEdit = true;
    doFormReset(form, toJS(conditions));
    editData.id = record.randomFieldId;
    editData.runstatus = record.runstatus;
    initAddForm({ id: record.randomFieldId })
  };

  batchDelete = () => {
    const { taskList, batchDelete } = this.props.schedule;
    doConfirm(`${getLabel(385625, "确定要删除选择的记录吗？")}`, () => {
      batchDelete({ ids: taskList.selectedRowKeys });
    });
  };

  logClick = type => {
    const { schedule } = this.props;
    const { systemAndRunLog } = schedule;
    
    switch (type) {
      case "system":
        systemAndRunLog.type = 0;
        schedule.systemLogView = true;
        break;
      case "run":
        systemAndRunLog.type = 1;
        systemAndRunLog.show = true;
        break;
    }
  };

  getDropMenuDatas = () => {
    const { schedule } = this.props;
    const { taskList, dropMenuDatas, status } = schedule;
    const {selectedKey} = toJS(status);
    const btns = [];

    if(selectedKey == 0) {
      toJS(dropMenuDatas).forEach(m => {
        switch (m.type) {
          case "BTN_BatchDelete":
            btns.push({
              key: m.type,
              icon: <i className={m.menuIcon} />,
              content: m.menuName,
              disabled: toJS(taskList.selectedRowKeys).length === 0,
              onClick: () => this.dropMenuDatasClick(m.type)
            });
            break;
          default:
            btns.push({
              key: m.type,
              icon: <i className={m.menuIcon} />,
              content: m.menuName,
              onClick: () => this.dropMenuDatasClick(m.type)
            });
            break;
        }
      });
    }
    btns.push({
      key: "BTN_COLUMN",
      icon: <i className="icon-coms-Custom" />,
      content: `${getLabel(32535, "显示列定制")}`,
      onClick: () => this.dropMenuDatasClick("BTN_COLUMN")
    })
    return btns;
  };

  dropMenuDatasClick = type => {
    const { schedule } = this.props;
    const {taskList, sysLogTableStore, status, runLogTableStore, triggerTableStore} = schedule;
    const {selectedKey} = toJS(status);

    switch (type) {
      case "BTN_Insert":
        this.createTask();
        break;
      case "BTN_Syslog":
        schedule.setRecordId('');
        schedule.systemLogView = true;
        break;
      case "BTN_Runlog":
        this.logClick("run")
        break;
      case "BTN_BatchDelete":
        this.batchDelete()
        break;
      case "BTN_COLUMN":
        if(selectedKey == 0) {
          taskList.setColSetVisible(true);
          taskList.tableColSet(true);
        }else if(selectedKey == 1) {
          sysLogTableStore.setColSetVisible(true);
          sysLogTableStore.tableColSet(true);
        }else if(selectedKey == 2) {
          runLogTableStore.setColSetVisible(true);
          runLogTableStore.tableColSet(true);
        }else if(selectedKey == 3) {
          triggerTableStore.setColSetVisible(true);
          triggerTableStore.tableColSet(true);
        }
        break;
    }
  }

  getTopBtns = () => {
    const { schedule } = this.props;
    const { taskList, dropMenuDatas } = schedule;
    const btns = [];
    toJS(dropMenuDatas).forEach(m => {
      switch (m.type) {
        case "BTN_BatchDelete":
          btns.push((
            <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@7n1j5b@integrationScheduleButton${m.type}`}
              onClick={() => this.dropMenuDatasClick(m.type)} type="primary"
              disabled={toJS(taskList.selectedRowKeys).length === 0}
            >
              {m.menuName}
            </Button>
          ));
          break;
        case "BTN_Insert":
          btns.push((
            <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@hhujaf@integrationScheduleButton${m.type}`} onClick={() => this.dropMenuDatasClick(m.type)} type="primary">
             {m.menuName}
            </Button>
          ));
          break;
      }
    });
    return btns;

  }

  getColumnsInfo = (data) => {
    const that = this;
    const {schedule} = this.props;
    if (!isEmpty(data)) {
      for (let index = 0; index < data.length; index++) {
        if (data[index].dbField == "pointid") {
          data[index].render = (text, record, index) => {
            record.id=record.randomField0;
            return (<a onClick={that.doEditById.bind(that, record)}>{text}</a>);
          }
        }else if(data[index].dbField == 'newValues' || data[index].dbField == 'id' || data[index].dataIndex == "id" || data[index].dataIndex == "newValues") {
          // /spa/coms/components/comMobx/wea-log-view/components/LogComponent.js(参考文件进行修改)
          data[index].render = (text, record, index) => {
            return (
              <a
                className="common"
                href="javascript:void(0);"
                onClick={() => {
                  if(record.clientIp) {
                    let title = `${record.operateTypespan} -
                    ${record.logsmalltypelabelnamespan || ""}
                    : ${record.targetNamespan}`;
                    schedule.setDetailTitle(title);
                    schedule.updateDetailkey(`${new Date().getTime()}`);
                    // schedule.setDetailVisible(true);
                    schedule.setShowParams(false);
                    schedule.setDetailRecord(record);
                    schedule.getDetailTable();
                    schedule.zhangChenGetDatas(record.keyidspan);
                  }
                }}
              >
                {getLabel("33564", "查看")}
              </a>
            )
          }
        }else if(data[index].dbField == "subcompanyid") {
          data[index].render = (text, record, index) => <a href={`${window.ecologyContentPath || ""}/spa/hrm/engine.html#/hrmengine/organization?showTree=false&isView=1&type=subcompany&id=${record.subcompanyid}`} target="_blank">{record.subcompanyidspan}</a>;
        }
      }
    }
  }

  getSearchAdvanced = () => {
    const {form, datas=[]} = this.getSearchCondition();
    return IntegrationUtil.getAdvancedItem(form, datas, this.getSearchFun, false, this && this.props && this.props.ecId || '', "integrationSchedule");
  };

  getSearchCondition = () => {
    const {schedule} = this.props;
    const {searchAd, searchAdConditions, systemAndRunLog, status, monitorForm, systemLogForm} = schedule;
    const {selectedKey, monitorFormCondition, systemLogFormCondition} = toJS(status);
    const {runSearchAdvance, runSearchAdvanceCondition} = systemAndRunLog;
    let form = '', datas = [];
    switch (Number(selectedKey)) {
      case 0:
        form = searchAd;
        datas = toJS(searchAdConditions);
        break;
      case 1:
        form = systemLogForm;
        datas = systemLogFormCondition;
        break;
      case 2:
        form = runSearchAdvance;
        datas = toJS(runSearchAdvanceCondition);
        break;
      case 3: 
        form = monitorForm;
        datas = monitorFormCondition;
        break;
    }
    return {
      form,
      datas,
    }
  }

  getSearchFun = () => {
    const { schedule } = this.props;
    const { getRunLogList, status, getTriggerList, getSysLogList} = schedule;
    const {selectedKey} = toJS(status);
    const {form} = this.getSearchCondition();
    const formParams = form.getFormParams();
    switch(Number(selectedKey)) {
      case 0:
        schedule.setState({ 
          showSearchAd: false,
          subcompanyid: formParams.subcompanyid1,
        })
        schedule.getListInfo();
        break;
      case 1:
        schedule.setState({ 
          showSearchAd: false,
          subcompanyid: formParams.operatorSubcompany,
         })
        getSysLogList();
        break;
      case 2:
        schedule.setState({ 
          showSearchAd: false,
          subcompanyid: formParams.subcompanyid1,
        })
        getRunLogList();
        break;
      case 3:
        schedule.setState({ showSearchAd: false });
        getTriggerList();
        break;
    }
  }

  getTabButtonsAd = () => {
    const { schedule } = this.props;
    let cancelClick = e => {
      schedule.setState({ showSearchAd: false })
    }
    const {form} = this.getSearchCondition();
    return IntegrationUtil.getSearchBtns(
      this.getSearchFun,
      () => form.reset(),
      cancelClick,
      this && this.props && this.props.ecId || '', 
      "integrationSchedule"
    );
  }

  handleChangeTab = (v) => {
    const {schedule} = this.props;
    const {getListInfo, getSearchAd, getSysLogList, getScheduleSysLogCondition, getRunLogList, getScheduleRunLogCondition, getTriggerList, getScheduleMonitorCondition} = schedule;

    schedule.setState({
      selectedKey: v,
      subcompanyid: "",
    });
    switch(Number(v)) {
      case 0:
        getSearchAd(getListInfo);
        break;
      case 1:
        getScheduleSysLogCondition(getSysLogList);
        break;
      case 2:
        getScheduleRunLogCondition(getRunLogList);
        break;
      case 3:
        getScheduleMonitorCondition(getTriggerList);
        break;
    }
  }

  closeLogDialog = () => this.props.schedule.systemLogView = false;

  render() {
    const { 
      schedule, 
    } = this.props, {
      taskList,
      runLogTableStore,
      sysLogTableStore,
      triggerTableStore,
      searchAd,
      systemLogView,
      systemLog,
      hasRight,
      rightLoading,
      hasManageDetachableRight,
      status,
    } = schedule, {
      showSearchAd, 
      selectedKey,
      hasOrganization,
      subcompanyid,
    } = toJS(status);
    const topTab = [
      {
        color: "#000000",
        groupid: "flowAll",
        showcount: true,
        title: `${getLabel('18505', "任务列表")}`,
        viewcondition: 0
      }
      // ,{
      //   color: "#000000",
      //   groupid: "flowAll",
      //   showcount: true,
      //   title: `${getLabel(775, "系统日志")}`,
      //   viewcondition: 1
      // }
      ,{
        color: "#000000",
        groupid: "flowAll",
        showcount: true,
        title: `${getLabel(	131274, "运行日志")}`,
        viewcondition: 2
      }
      ,{
        color: "#000000",
        groupid: "flowAll",
        showcount: true,
        title: `${getLabel(	23755, "任务监控")}`,
        viewcondition: 3
      }
    ];
    const condition = this.getSearchCondition().datas;
    return rightLoading
      ? null 
      : <div style={{height: '100%'}}>
          <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@bmr3gq`} datas={(selectedKey == 0 || selectedKey == 2) && (!hasManageDetachableRight) ? [] : this.getDropMenuDatas()}>
            <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@1omk90`}
              title={getLabel(16539, "计划任务")}
              icon={<i className="icon-coms-integration" />}
              iconBgcolor="#1a57a0"
              buttons={selectedKey == 0 && hasManageDetachableRight ? this.getTopBtns() : []}
              showDropIcon={true}
              dropMenuDatas={(selectedKey == 0 || selectedKey == 2) && (!hasManageDetachableRight) ? [] : this.getDropMenuDatas()}
              dropMenuProps={{
                collectParams: {
                  favname: `${getLabel(16539, "计划任务")}`,
                  favouritetype: 1,
                  objid: 0,
                  link: "wui/engine.html#/integration/schedule",
                  importantlevel: 1
                }
              }}
            />
            <WeaLeftRightLayout ecId={`${this && this.props && this.props.ecId || ''}_WeaLeftRightLayout@buemzy`}
              showLeft={selectedKey != 3 && hasOrganization && hasManageDetachableRight}
              showBtn={selectedKey != 3 && hasOrganization && hasManageDetachableRight}
              leftCom={<OrganizationTree ecId={`${this && this.props && this.props.ecId || ''}_OrganizationTree@lrnskb`} 
                ref="schedule"
                selectedKeys={[subcompanyid]}
                refreshData={this.refreshData}
                rightStr={"intergration:schedulesetting"}
                {...(this.props.orgTreeParams || {})} 
              />}
            >
              <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@ysbe6v`}
                datas={topTab}
                keyParam="viewcondition" //主键
                countParam="groupid" //数量
                selectedKey={selectedKey}
                advanceHeight={(condition && condition.length) ? Math.ceil(condition[0].items.length/2) * 72 : 72}
                showSearchAd={showSearchAd}
                searchType={(selectedKey == 0 || selectedKey == 1 || selectedKey == 2) && (!hasManageDetachableRight) ? [] : ((selectedKey==0) ? ['base','advanced']: ['advanced'])}
                searchsAd={this.getSearchAdvanced()}
                buttonsAd={this.getTabButtonsAd()}
                setShowSearchAd={(v) => schedule.setState({showSearchAd: v})}
                hideSearchAd={() => schedule.setState({showSearchAd: false})}
                onSearch={this.getSearchFun}
                onSearchChange={value => searchAd.updateFields({pointid: value})}
                searchsBaseValue={selectedKey == 0 ? searchAd.getFormParams().pointid: ''}
                onChange={this.handleChangeTab}
              />
              {
                (selectedKey == 0 || selectedKey == 1 || selectedKey == 2) && (!hasManageDetachableRight)
                  ? <NoRight ecId={`${this && this.props && this.props.ecId || ''}_NoRight@3ie809`} />
                  : <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@jdtnhz`}
                      hasOrder={true}
                      onOperatesClick={this.onOperatesClick}
                      comsWeaTableStore={selectedKey == 0 ? taskList : selectedKey == 1 ? sysLogTableStore : selectedKey == 2 ? runLogTableStore : triggerTableStore} 
                      needScroll={true}
                      getColumns={this.getColumnsInfo}
                      key={selectedKey}
                    />
              }
            </WeaLeftRightLayout>
            <AddOrEditTask ecId={`${this && this.props && this.props.ecId || ''}_AddOrEditTask@rc8adv`} />
            <RunLog ecId={`${this && this.props && this.props.ecId || ''}_RunLog@t36oku`} />
          </WeaRightMenu>
          <WeaLogViewComp ecId={`${this && this.props && this.props.ecId || ''}_WeaLogViewComp@gbkt78`} 
            logStore={systemLog} 
            logType="15" 
            logSmallType="12"
            targetId={schedule.recordId}
            visible={systemLogView} 
            onCancel={this.closeLogDialog} 
          />
        </div>
  }
}
