import React, { useEffect, useState } from 'react';
import { Table, Space, Button, Tooltip, Modal, Form } from 'antd';
import { EditOutlined, DeleteOutlined  } from '@ant-design/icons';

import ScheduleAction from './ScheduleAction';
import { dispatch } from '../../../../model';
import { showMessage } from '../../../../util';

import './ScheduleCURDModal.less';

const ScheduleCURDModal = (props) => {

  const { visible, onCancel, id } = props;
  const [ schedules, setSchedules ] = useState([]);
  const [ loading, setLoading ] = useState(false);
  const [ action, setAction ] = useState('');
  const [ currentSchedule, setCurrentSchedule ] = useState('');
  const [ step, setStep ] = useState(0);
  const [ confirmLoading, setConfirmLoading ] = useState(false);
  const [ editSchedule, setEditSchedule ] = useState({});

  const [modal, contextHolder] = Modal.useModal();
  const [form] = Form.useForm();

  useEffect(() => {

    if (visible) {
      getSchedules();
    }

    //eslint-disable-next-line react-hooks/exhaustive-deps
  }, [ visible ])

  const columns = [
    {
      title: '序号',
      dataIndex: 'key',
      render: (_, __, index) => {
        return (index+1).toString();
      },
      width: 60,
    },
    {
      title: '调度名称',
      dataIndex: 'taskName',
      width: 180,
      ellipsis: true,
    },
    {
      title: '是否开启',
      dataIndex: 'status',
      width: 120,
      render: (text, _, __) => {
        return (text==='1')?'是':'否';
      }      
    },
    {
      title: '调度时间',
      dataIndex: 'cronDesc',
      width: 200,
      ellipsis: true,
    },
    {
      title: '描述',
      dataIndex: 'remark',
      ellipsis: true,
    },
    {
      title: '操作',
      key: 'action',
      width: 120,

      render: (_,record) => {
        return (
          <Space size='small'>
            <Tooltip placement='bottom' title={'修改'}>
              <Button icon={<EditOutlined />} size='small' onClick={() => { editItem(record); }} />
            </Tooltip>
            {/* <Tooltip placement='bottom' title={'详情'}>
              <Button icon={<ReconciliationOutlined />} size='small' onClick={() => { detailItem(record); }} />
            </Tooltip> */}
            <Tooltip placement='bottom' title={'删除'}>
              <Button icon={<DeleteOutlined />} size='small' onClick={() => { deleteItem(record); }} />
            </Tooltip>
          </Space>
        )
      }
    }
  ];

  const getSchedules = () => {
    setLoading(true);
    dispatch({
      type: 'datasource.getScheduleListByTaskId',
      payload: {
        params: {
          targetConfId: id
        }
      },
      callback: data => {
        setSchedules(data?.datas||[]);
        setLoading(false);
      },
      error: () => {
        setLoading(false);
      }
    })
  }

  const editItem = (record) => {
    setStep(1);
    setAction('edit');
    setCurrentSchedule(record);
  }

  // const detailItem = (record) => {
  //   setStep(1);
  //   setAction('detail');
  //   setCurrentSchedule(record);
  // }

  const deleteItem = (record) => {
    modal.confirm({
      title: '提示!',
      content: '您确定要删除该调度吗?',
      onOk: () => {
        dispatch({
          type: 'datasource.deleteSchedule',
          payload: {
            id: record.id
          },
          callback: () => {
            showMessage('success', '删除调度成功');
            getSchedules();
          }
        })
      }
    });
  }

  const onAddClick = () => {
    setStep(1);
    setAction('add');
  }

  const cancel = () => {
    reset();
    onCancel && onCancel(false);
  }

  const reset = () => {
    setStep(0);
    setSchedules([]);
    setCurrentSchedule({});
    setConfirmLoading(false);
  }

  const onActionChange = (data) => {
    setEditSchedule(data);
  }

  const prev = () => {
    setStep(step-1);
  }

  const save = async () => {
    try {
      await form.validateFields();

      setConfirmLoading(true);
      dispatch({
        type: 'datasource.saveAndStartSchedule',
        payload: { 
          data: editSchedule
        },
        callback: () => {
          setConfirmLoading(false);
          reset();
          getSchedules();
        },
        error: () => {
          setConfirmLoading(false);
        }
      })

    } catch (errInfo) {
      console.log('Validate Failed:', errInfo);
    }

  }

  let title = '';
  if (step === 0) {
    title = '调度详情';
  } 
  if (step === 1) {
    if (action === 'add') {
      title = '新增调度';
    } else if (action === 'edit') {
      title = '调度编辑';
    } else if (action === 'detail') {
      title = '调度详情';
    }
  }

  let footer = null;

  if (step === 0) {
    footer = [
      <Button
        key="0" 
        onClick={cancel}
      >
      取消
      </Button>,
    ]
  } else if (step === 1) {
    if (action === 'detail') {
      footer = [
        <Button
          key="0" 
          onClick={prev}
        >
        返回
        </Button>,
      ]
    } else {
      footer = [
        <Button
          key="0" 
          onClick={prev}
        >
        返回
        </Button>,
        <Button
          key="1" 
          type="primary"
          loading={confirmLoading}
          onClick={save}
        >
        保存
        </Button>
      ]
    }
  }

  return (
    <Modal 
      forceRender
      className='schedule-curd-modal'
      visible={visible}
      title={title}
      width={1000}
      maskClosable={true}
      onCancel={cancel}
      footer={footer}
    >
    {
      step === 0 && <> 
        <div className='d-flex mb-3' style={{ alignItems: 'center' }}>
          <Button type="primary" onClick={onAddClick} style={{ marginLeft: 'auto' }} >新增调度</Button>
        </div>
        <Table
          loading={loading}
          columns={columns} 
          rowKey={'id'}
          dataSource={schedules||[]}
          pagination={false} 
          sticky
        />
      </>
    }
    {
      step === 1 && <ScheduleAction 
        action={action} 
        id={currentSchedule.id} 
        form={form}
        tid={id}
        onChange={onActionChange}
      />
    }
    { contextHolder }
    </Modal>
  );
}

export default ScheduleCURDModal;