import React, { useState, useEffect } from 'react';
import { Modal, Row, Col, Card, Table, Typography, Spin, Empty, Button, DatePicker, Input, Divider } from 'antd';
import classNames from 'classnames';
import 'moment/locale/zh-cn';
import locale from 'antd/es/date-picker/locale/zh_CN';

import { dispatch, dispatchLatest } from '../../../../model';
import './TaskLogsModal.less';
import { showMessage } from '../../../../util';

const { Meta } = Card;
const { RangePicker } = DatePicker;

const TaskReviewModal = (props) => {
  const { visible, onCancel, scope, scopes } = props;

  const [ data, setData ] = useState([]);
  const [ taskTracersBindStateId, setTaskTracersBindStateId ] = useState([]);
  const [ expandedRowKeys, setExpandedRowKeys ] = useState([]);

  const cols = [
    {
      title: '序号',
      dataIndex: 'key',
      render: (text, record, index) => {
        return (index+1).toString();
      },
      width:80
    },
    {
      title: '系统',
      dataIndex: 'scope',
      ellipsis: true,
    },
    {
      title: '数据源',
      dataIndex: 'databaseName',
      ellipsis: true,
    },
    {
      title: '抽取schema',
      dataIndex: 'schema',
      ellipsis: true,
      render: (schemas) => (schemas??[]).toString() 
    },
    {
      title: '开始时间',
      dataIndex: 'startTime',
      ellipsis: true,
    },
    {
      title: '结束时间',
      dataIndex: 'endTime',
      ellipsis: true,
    },
    {
      title: '执行状态',
      dataIndex: 'state',
    },
    {
      title: '操作',
      key: 'action',
      width: 120,

      render: (_,record) => {
        return (
          <div style={{ display: 'flex', alignItems: 'center'  }}>
            <Button 
              type='link'
              size='small'
              onClick={() => { 
                dispatch({
                  type: 'datasource.startTask',
                  payload: {
                    params: {
                      harvestingTaskId: record.harvestingTaskId
                    }
                  },
                  callback: data => {
                    showMessage('success', '确定成功')
                    getTaskReviews()
                  }
                });
              }}
              style={{ padding: 0 }}
            >
            确定
            </Button>
            <div style={{ margin: '0 5px' }}>
              <Divider type='vertical' />
            </div>
            <Button
              type='link'
              size='small'
              onClick={() => {
                dispatch({
                  type: 'datasource.cancelReview',
                  payload: {
                    harvestingTaskId: record.harvestingTaskId
                  },
                  callback: data => {
                    showMessage('success', '取消成功')
                    getTaskReviews()
                  }
                });
              }}
              style={{ padding: 0 }}
            >
            取消
            </Button>
          </div>
        )
      }
    }
  ]

  useEffect(() => {
    if (visible) {
      getTaskReviews()
    }
    //eslint-disable-next-line react-hooks/exhaustive-deps
  }, [ visible ])

  const getTaskReviews = () => {
    dispatchLatest({
      type: 'datasource.getTaskReviews',
      payload: {
        namespace: ((scope||[]).length>0?scope[0]:''),
      },
      callback: data => {
        let _scopes = [];

        (scopes||[]).forEach(item => {
          (item.catalogs||[]).forEach((catalog) => {
            _scopes = [..._scopes, ...(catalog.scopes||[])]; 
          });
        });

        (data??[]).forEach(item => {
          (_scopes||[]).forEach(_item => {
            if (_item.scopeId === Number(item.scope)) {
              item.scope = _item.scopeName;
            }
          })
        });

        setData(data);
      }
    })
  }

  const getTaskTracer = (record) => {
    dispatch({
      type: 'datasource.getTaskTracerByStateId',
      payload: {
        taskStateId: record.taskStateId
      },
      callback: data => {
        setTaskTracersBindStateId([...taskTracersBindStateId, { key: record.taskStateId, value: data||[] }]);
      }
    });
  }

  const reset = () => {
    setData();
    setTaskTracersBindStateId([]);
    setExpandedRowKeys([]);
  }

  return (
    <Modal
      className='task-report-modal'
      forceRender
      title='元数据采集审核'
      visible={visible}
      width={1000}
      bodyStyle={{ padding: '15px', overflowX: 'auto', maxHeight: '80vh' }}
      onCancel={() => { 
        reset();
        onCancel && onCancel() 
      }}
      footer = {
        <Button
          key="1" 
          type="primary"
          onClick={() => {
            reset();
            onCancel && onCancel() 
          }}
        >
        取消
        </Button>
      }
    >
      <Table
        className='mt-3'
        columns={cols} 
        rowKey={'taskStateId'}
        dataSource={data||[]}
        pagination={false} 
        sticky
        expandable={{
          expandedRowRender: record => {

            let _tracer = null;
            (taskTracersBindStateId||[]).forEach(item => {
              if (item.key === record.taskStateId) {
                _tracer = item.value||[];
              }
            })

            return (
              <Spin spinning={_tracer===null}>
              {
                (_tracer||[]).length === 0 && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无日志" />
              }
              {
                _tracer && _tracer.map((_item, index) => {
                  return (
                    <Typography.Paragraph key={index} >
                    {_item.value||''}
                    </Typography.Paragraph>
                  )
                })
              }
              </Spin>
            );
          },
          expandedRowKeys,
          onExpand: (expanded, record) => {
            let exsit = false;
            (taskTracersBindStateId||[]).forEach(item => {
              if (item.key === record.taskStateId) {
                exsit = true;
              }
            })

            const newExpandedKeys = [...expandedRowKeys];
            if (expanded) {
              newExpandedKeys.push(record.taskStateId||'');
            } else {
              const index = newExpandedKeys.indexOf(record.id||'');
              newExpandedKeys.splice(index, 1);
            }

            setExpandedRowKeys([...newExpandedKeys]);

            if (expanded && !exsit) {
              getTaskTracer(record);
            }

          }
        }}
      />
    </Modal>
  );
}

export default TaskReviewModal;