AddModal.jsx 20.6 KB
Newer Older
皮倩雯's avatar
皮倩雯 committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/* eslint-disable default-case */
import React, { useEffect, useState } from 'react';
import SiteModal from '@/components/Modal/SiteModa';
import { AddIISAgentConfig } from '@/services/scheduledTasks/api';

import {
  Input,
  Card,
  InputNumber,
  Form,
  Radio,
  DatePicker,
  Switch,
  Select,
  message,
  notification,
皮倩雯's avatar
皮倩雯 committed
17
  Checkbox,
皮倩雯's avatar
皮倩雯 committed
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
} from 'antd';
import { EditOutlined, InfoCircleOutlined } from '@ant-design/icons';
import moment from 'moment';
import HourOfDaySelect from './HourOfDaySelect';
import DayOfWeekSelect from './DayOfWeekSelect';
import styles from './AddModal.less';

const { Item } = Form;

const { TextArea } = Input;
let unitType = { Hour: '小时', Minute: '分钟', Second: '秒' };
const hours = {
  '1': '星期一',
  '2': '星期二',
  '3': '星期三',
  '4': '星期四',
  '5': '星期五',
  '6': '星期六',
  '7': '星期天',
};
const AddModal = props => {
  const { submitCallback, visible, onCancel, type, record } = props;
  const [isReentrant, setIsReentrant] = useState(false);
  const [postCheck, setPostCheck] = useState(false);
  const [reenCheck, setReenCheck] = useState(false);
  const [logCheck, setLogCheck] = useState(false);
  const [isEndTimeShow, setIsEndTimeShow] = useState(false);
  const [isLoopShow, setIsLoopShow] = useState(false);
  const [isDayLoopShow, setIsDayLoopShow] = useState(false);
  const [isWeekLoopShow, setIsWeekLoopShow] = useState(false);
  const [waitCheck, setWaitCheck] = useState(false);
49
  const [isUse, setIsUse] = useState(false);
皮倩雯's avatar
皮倩雯 committed
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
  const [interval, setInterval] = useState(1);
  const [loop_unit, setLoop_unit] = useState('Hour');
  const [exeType, setExeType] = useState(true);
  const [isType, setIsType] = useState('重复执行');
  const [isTypeValue, setIsTypeValue] = useState('ByLoop');
  const [time_out, setTime_out] = useState(30);
  const [weekData, setWeekData] = useState([]);
  const [exeTime, setExeTime] = useState(moment().format('YYYY-MM-DD 00:00:00'));
  const [selectValues, setSelectValues] = useState([]);
  const [form] = Form.useForm();
  const dateFormat = 'YYYY-MM-DD HH:mm:ss';

  useEffect(() => {
    if (visible) {
      if (type === 'edit') {
        let startTime =
          record.LoopMode === 'ByOnce'
            ? moment(new Date(new Date().toLocaleDateString()), 'YYYY-MM-DD 00:00:00').add(
                1,
                'days',
              )
            : moment(new Date(new Date().toLocaleDateString()), 'YYYY-MM-DD 00:00:00');
        form.setFieldsValue({
          name: record.Name,
74
          is_enable: !record.Enabled,
皮倩雯's avatar
皮倩雯 committed
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
          url_type: record.Absolute ? true : false,
          url_path: record.Url,
          request_header: record.CustomHeader,
          plan_type: record.LoopMode,
          start_time: record.StartFrom ? moment(record.StartFrom, dateFormat) : startTime,
          end_time: record.EndAt ? moment(record.EndAt, dateFormat) : null,
          loop_mode: record.LoopMode,
          interval: record.Interval,
          loop_unit: record.LoopUnit,
          hour_of_day: record.HourOfDay && record.HourOfDay.split(','),
          day_of_week: record.DayOfWeek,
          time_out: (record.Timeout !== -1 && record.Timeout / 1000) || 30,
          post_state: record.UsePostState,
          reentrant: record.AllowReentrant,
          enable_log: record.AllowLog,
        });
        if (record.UsePostState) {
          setIsReentrant(true);
        }
        let startTimeValue =
          record.LoopMode === 'ByOnce'
            ? moment()
                .add(1, 'days')
                .format('YYYY-MM-DD 00:00:00')
            : moment().format('YYYY-MM-DD 00:00:00');
        setExeTime(record.StartFrom ? record.StartFrom : startTimeValue);
101
        setIsUse(!record.Enabled);
皮倩雯's avatar
皮倩雯 committed
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
        changeLoopMode(record.LoopMode);
        setReenCheck(record.AllowReentrant);
        setPostCheck(record.UsePostState);
        setLogCheck(record.AllowLog);
        setInterval(record.Interval);
        setLoop_unit(record.LoopUnit);
        setWaitCheck(record.UseTimeout || false);
        setTime_out((record.Timeout !== -1 && record.Timeout / 1000) || 30);
        if (record.Timeout !== -1) {
          setWaitCheck(true);
        }
        if (record.LoopMode === 'ByOnce') {
          setIsType('执行一次');
          form.setFieldsValue({
            type: '执行一次',
          });
          setExeType(false);
        } else {
          setIsType('重复执行');
          form.setFieldsValue({
            type: '重复执行',
          });
          if (record.LoopMode === 'ByDay') {
            setSelectValues(record.HourOfDay.split(','));
          } else if (record.LoopMode === 'ByWeek') {
            setWeekData(record.DayOfWeek.split(','));
          }
          setExeType(true);
        }
      } else {
        form.setFieldsValue({
          type: '重复执行',
          url_type: false,
          loop_mode: 'ByLoop',
          start_time: moment(new Date(new Date().toLocaleDateString()), 'YYYY-MM-DD 00:00:00'),
        });
        setExeTime(moment().format('YYYY-MM-DD 00:00:00'));
        setIsType('重复执行');
        changeLoopMode('ByLoop');
皮倩雯's avatar
皮倩雯 committed
141
        setIsUse(false);
皮倩雯's avatar
皮倩雯 committed
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
        setInterval(1);
        setLoop_unit('Hour');
      }
    } else {
      form.resetFields();
      setSelectValues([]);
      setWeekData([]);
      setLogCheck(false);
      setIsReentrant(false);
      setReenCheck(false);
      setPostCheck(false);
      setWaitCheck(false);
      setExeType(true);
    }
  }, [visible]);

  const handleOk = async () => {
    form.validateFields().then(validate => {
      let fv = form.getFieldValue();
      if (
        (fv.loop_mode === 'ByDay' && !selectValues.length) ||
        (fv.loop_mode === 'ByWeek' && !weekData.length)
      ) {
        message.warning('请选择计划执行日');
        return false;
      }
      let data = {
        Url: fv.url_path,
        CustomHeader: fv.request_header || '',
        StartFrom: fv.start_time && fv.start_time.format(dateFormat),
        EndAt: fv.end_time && fv.end_time.format(dateFormat),
        LoopMode: isType === '重复执行' ? fv.loop_mode : 'ByOnce',
        LoopUnit: loop_unit,
        MonthOfYear: null,
        WeekOfMonth: null,
        DayOfWeek: fv.day_of_week ? fv.day_of_week.toString() : '',
        DayOfMonth: null,
        HourOfDay: fv.hour_of_day && fv.hour_of_day.toString(),
        Interval: interval.toString(),
        UsePostState: fv.post_state,
        AllowReentrant: fv.reentrant,
        AllowLog: fv.enable_log,
184
        Enabled: !isUse,
皮倩雯's avatar
皮倩雯 committed
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
        Timeout: time_out ? parseInt(time_out) * 1000 : 30000,
        Absolute: fv.url_type,
        SiteInfo: null,
        Name: fv.name,
        Tolerate: null,
        UseTimeout: waitCheck,
      };
      time_out ? (data.MillisecondsTimeout = parseInt(time_out)) : -1;
      if (!waitCheck) {
        data.Timeout = -1;
        data.MillisecondsTimeout = -1;
      }

      AddIISAgentConfig(data).then(res => {
        if (res.code === 0) {
          onCancel();
          submitCallback(fv.type);
          notification.success({
            message: '提示',
            duration: 3,
            description: '新增成功',
          });
        } else {
          notification.error({
            message: '提示',
            duration: 3,
            description: res.msg,
          });
        }
      });
    });
  };

  const onPostChange = value => {
    setIsReentrant(value);
    setReenCheck(false);
    setPostCheck(value);
    form.setFieldsValue({
      post_state: value,
      reentrant: false,
    });
  };
  const onReenChange = value => {
    setReenCheck(value);
    form.setFieldsValue({
      reentrant: value,
    });
  };
  const onLogChange = value => {
    setLogCheck(value);
    form.setFieldsValue({
      enable_log: value,
    });
  };

  const changeLoopMode = value => {
    setIsTypeValue(value);
    switch (value) {
      case 'ByOnce':
        setIsEndTimeShow(false);
        setIsLoopShow(true);
        setIsWeekLoopShow(false);
        setIsDayLoopShow(false);
        break;
      case 'ByLoop':
        setIsEndTimeShow(true);
        setIsLoopShow(true);
        setIsWeekLoopShow(false);
        setIsDayLoopShow(false);
        break;
      case 'ByDay':
        setIsEndTimeShow(true);
        setIsLoopShow(false);
        setIsWeekLoopShow(false);
        setIsDayLoopShow(true);
        break;
      case 'ByWeek':
        setIsEndTimeShow(true);
        setIsLoopShow(false);
        setIsWeekLoopShow(true);
        setIsDayLoopShow(false);
        break;
    }
  };
  const onLoopModeChange = e => {
    changeLoopMode(e.target.value);
    setSelectValues([]);
    setWeekData([]);
    form.setFieldsValue({
      hour_of_day: '',
      day_of_week: '',
    });
  };
皮倩雯's avatar
皮倩雯 committed
278 279
  const onChange = e => {
    setIsUse(e.target.checked);
皮倩雯's avatar
皮倩雯 committed
280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582
  };
  const handleExe = e => {
    let obj = form.getFieldValue();
    let data = e.target.value;
    setIsType(data);
    if (data === '执行一次') {
      changeLoopMode('ByOnce');
      setLoop_unit('Second');
      form.setFieldsValue({
        loop_mode: 'ByOnce',
        hour_of_day: '',
        day_of_week: '',
        end_time: obj.start_time,
      });
      if (!record) {
        form.setFieldsValue({
          start_time: moment(new Date(new Date().toLocaleDateString()), 'YYYY-MM-DD 00:00:00').add(
            1,
            'days',
          ),
          end_time: moment(new Date(new Date().toLocaleDateString()), 'YYYY-MM-DD 00:00:00').add(
            1,
            'days',
          ),
        });
        setExeTime(
          moment()
            .add(1, 'days')
            .format('YYYY-MM-DD 00:00:00'),
        );
      }
      setExeType(false);
    } else {
      changeLoopMode('ByLoop');
      setExeType(true);
      form.setFieldsValue({
        loop_mode: 'ByLoop',
        end_time: '',
      });
      if (!record) {
        form.setFieldsValue({
          start_time: moment(new Date(new Date().toLocaleDateString()), 'YYYY-MM-DD 00:00:00'),
          hour_of_day: '',
          day_of_week: '',
        });
        setExeTime(moment().format('YYYY-MM-DD 00:00:00'));
      }
    }
  };
  const onWait = e => {
    setWaitCheck(e);
  };
  const changeUnit = e => {
    setLoop_unit(e);
  };
  const changeInterval = e => {
    setInterval(e);
  };
  const InputTimeOut = e => {
    setTime_out(e);
  };

  const changeStartTime = e => {
    const time = moment(e).format('YYYY-MM-DD HH:mm:ss');
    setExeTime(time);
    let obj = form.getFieldValue();
    if (obj.loop_mode === 'ByOnce') setLoop_unit('Second');
  };

  const changeDay = data => {
    if (data) setSelectValues(data);
  };

  const changeWeek = data => {
    if (data) setWeekData(data);
  };

  return (
    <div className={styles.agent_container}>
      <SiteModal
        {...props}
        title={`${type === 'add' ? '新增' : '编辑'}定时任务`}
        bodyStyle={{ width: '100%', minHeight: '100px' }}
        style={{ top: 100, borderRadius: '20px' }}
        width="800px"
        destroyOnClose
        cancelText="取消"
        okText="确认"
        forceRender
        visible={visible}
        onOk={() => handleOk()}
        onCancel={() => onCancel()}
      >
        <div className={styles.IISAgent_container}>
          <Form form={form} labelCol={{ span: 4 }} wrapperCol={{ span: 18 }}>
            <Item label="计划名称" name="name" rules={[{ required: true }]}>
              <Input placeholder="请输入计划名称" disabled={type === 'edit' ? true : false} />
            </Item>
            <Item label="URL路径">
              <Item label="" name="url_type" style={{ marginBottom: '0.2rem' }}>
                <Radio.Group>
                  <Radio value={false}>相对路径(便于配置迁移)</Radio>
                  <Radio value={true}>绝对路径(用于外链)</Radio>
                </Radio.Group>
              </Item>
              <Item label="" name="url_path" style={{ marginBottom: '0' }}>
                <TextArea rows={3} placeholder="请输入URL名称" />
              </Item>
            </Item>

            <Item label="请求头" name="request_header">
              <Input placeholder="请求头,选填" />
            </Item>
            <Item label="计划类型" name="type">
              <Radio.Group onChange={handleExe}>
                <Radio.Button value="重复执行">重复执行</Radio.Button>
                <Radio.Button value="执行一次">执行一次</Radio.Button>
              </Radio.Group>
            </Item>
            {exeType && (
              <Item label="执行方式" name="loop_mode">
                <Radio.Group onChange={onLoopModeChange}>
                  <Radio value="ByLoop">循环</Radio>
                  <Radio value="ByDay">每天</Radio>
                  <Radio value="ByWeek">每周</Radio>
                </Radio.Group>
              </Item>
            )}
            <Item label="开始时间" wrapperCol={{ span: 28 }} style={{ marginBottom: '0' }}>
              <div style={{ display: 'flex' }}>
                <Item label="" name="start_time" style={{ marginRight: '1rem' }}>
                  <DatePicker showTime onChange={changeStartTime} />
                </Item>
                {isEndTimeShow && (
                  <Item label="结束时间" name="end_time">
                    <DatePicker showTime />
                  </Item>
                )}
              </div>
            </Item>

            {isLoopShow && isType === '重复执行' && (
              <Card style={{ width: 600, margin: '0 0 1rem 3.6rem', height: '8rem' }}>
                <div className={styles.loopShow}>
                  <span></span>
                  <InputNumber
                    min={0}
                    value={interval}
                    style={{ margin: '0 0.5rem' }}
                    onChange={changeInterval}
                    placeholder="请输入循环周期"
                  />
                  <Select
                    value={loop_unit}
                    onChange={changeUnit}
                    style={{ width: '8rem', margin: '0 0.5rem' }}
                  >
                    <Select.Option value="Hour">小时</Select.Option>
                    <Select.Option value="Minute">分钟</Select.Option>
                    <Select.Option value="Second"></Select.Option>
                  </Select>
                  <span> 执行一次</span>
                </div>
              </Card>
            )}
            {isDayLoopShow && (
              <Item label="日循环" name="hour_of_day">
                <HourOfDaySelect changeDay={changeDay} />
              </Item>
            )}
            {isWeekLoopShow && (
              <Item label="周循环" name="day_of_week">
                <DayOfWeekSelect changeWeek={changeWeek} />
              </Item>
            )}
            {isTypeValue === 'ByDay'
              ? !selectValues.length && (
                  <span style={{ color: '#f00' }} className={styles.exeTime}>
                    <InfoCircleOutlined style={{ marginRight: '0.2rem' }} />
                    必须选择计划执行时刻
                  </span>
                )
              : ''}

            {isTypeValue === 'ByWeek'
              ? !weekData.length && (
                  <span style={{ color: '#f00' }} className={styles.exeTime}>
                    <InfoCircleOutlined style={{ marginRight: '0.2rem' }} />
                    必须选择计划执行时刻
                  </span>
                )
              : ''}
            <Item label="说明">
              <div style={{ color: '#909EB6FF', fontSize: '12px' }}>
                {isType === '执行一次' && <span>{exeTime}执行一次</span>}
                {isType === '重复执行' && isTypeValue === 'ByDay' && (
                  <span style={{ color: selectValues.length ? '#909EB6FF' : '#f00' }}>
{exeTime}开始{selectValues.length ? ',在每天' : ''}
                    {selectValues.length
                      ? selectValues.map((item, index) => {
                          return item.length > 1
                            ? `${item}:00${index == selectValues.length - 1 ? '' : ','}`
                            : `0${item}:00${index == selectValues.length - 1 ? '' : ','}`;
                        })
                      : ''}
                    {selectValues.length ? '执行' : ''}
                  </span>
                )}
                {isType === '重复执行' && isTypeValue === 'ByWeek' && (
                  <span style={{ color: weekData.length ? '#909EB6FF' : '#f00' }}>
{exeTime}开始{weekData.length ? ',在每周' : ''}
                    {weekData.length
                      ? weekData.map((item, index) => {
                          return `${hours[item]}${index == weekData.length - 1 ? '' : ','}`;
                        })
                      : ''}
                    {weekData.length && selectValues.length
                      ? selectValues.map((item, index) => {
                          return item.length > 1
                            ? `${item}:00${index == selectValues.length - 1 ? '' : ','}`
                            : `0${item}:00${index == selectValues.length - 1 ? '' : ','}`;
                        })
                      : ''}{' '}
                    {weekData.length ? '执行' : ''}
                  </span>
                )}
                {isType === '重复执行' && isTypeValue === 'ByLoop' && (
                  <span style={{ color: '#909EB6FF' }}>
{exeTime}开始,每{interval}
                    {unitType[loop_unit]}执行一次。
                  </span>
                )}
              </div>
            </Item>
            <Item label="其他设置" wrapperCol={{ span: 28 }} style={{ marginBottom: '0' }}>
              {' '}
              <div style={{ display: 'flex' }}>
                <div style={{ display: 'flex' }}>
                  <Item name="wait" style={{ marginRight: '0.5rem' }}>
                    <Switch
                      checkedChildren="开启"
                      unCheckedChildren="关闭"
                      onChange={onWait}
                      checked={waitCheck}
                    />
                  </Item>
                  <div style={{ paddingTop: '0.3rem' }}>请求等待时间(单位:秒)</div>
                </div>

                {waitCheck && (
                  <Item name="time_out">
                    <div>
                      <InputNumber value={time_out} onChange={InputTimeOut} />
                    </div>
                  </Item>
                )}
              </div>
            </Item>
            <Item label=" " wrapperCol={{ span: 28 }} colon={false} style={{ marginBottom: '0' }}>
              {' '}
              <div style={{ display: 'flex' }}>
                <Item name="post_state" style={{ marginRight: '0.5rem' }}>
                  <Switch
                    checkedChildren="开启"
                    unCheckedChildren="关闭"
                    onChange={onPostChange}
                    checked={postCheck}
                  />
                </Item>
                <div style={{ paddingTop: '0.3rem' }}>
                  使用POST维持状态(上一次返回结果传入下一次请求)
                </div>
              </div>
            </Item>
            <Item label=" " wrapperCol={{ span: 28 }} colon={false} style={{ marginBottom: '0' }}>
              <div style={{ display: 'flex' }}>
                <Item style={{ marginRight: '0.5rem' }} name="reentrant">
                  <Switch
                    checkedChildren="开启"
                    unCheckedChildren="关闭"
                    onChange={onReenChange}
                    disabled={isReentrant}
                    checked={reenCheck}
                  />
                </Item>
                <div style={{ paddingTop: '0.3rem' }}>
                  允许重入(上一次未执行完,也会执行下一次请求)
                </div>
              </div>
            </Item>
            <Item label=" " wrapperCol={{ span: 28 }} colon={false} style={{ marginBottom: '0' }}>
              <div style={{ display: 'flex' }}>
                <Item name="enable_log" style={{ marginRight: '0.5rem' }}>
                  <Switch
                    checkedChildren="开启"
                    unCheckedChildren="关闭"
                    onChange={onLogChange}
                    checked={logCheck}
                  />
                </Item>
                <div style={{ paddingTop: '0.3rem' }}>记录日志(小于每分钟一次的请求不会记录)</div>
              </div>
            </Item>
583
            <Item label="禁用此计划" style={{ color: '#f00' }} name="is_enable">
皮倩雯's avatar
皮倩雯 committed
584
              <Checkbox checked={isUse} onChange={onChange} />
皮倩雯's avatar
皮倩雯 committed
585 586 587 588 589 590 591 592
            </Item>
          </Form>
        </div>
      </SiteModal>
    </div>
  );
};
export default AddModal;