import React, { useState, useEffect } from 'react';
import { Modal, Row, Col, Card, Table, Typography, Spin, Empty, Button, DatePicker, Input } 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';

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

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

  const [ summaryDatas, setSummaryDatas ] = useState([]);
  const [ currentSummaryData, setCurrentSummaryData ] = useState({});
  const [ reportDetail, setReportDetail ] = useState({});
  const [ taskTracersBindStateId, setTaskTracersBindStateId ] = useState([]);
  const [ rangeValue, setRangeValue ] = useState([]);
  const [ expandedRowKeys, setExpandedRowKeys ] = useState([]);
  const [ keyword, setKeyword ] = useState('');
  const [ filterReportData, setFilterReportData ] = useState([]);

  useEffect(() => {

    if (visible) {
      getTaskReportSummary((rangeValue.length)>=1?rangeValue[0]: null, (rangeValue.length)===2?rangeValue[1]: null);
    }
    
    //eslint-disable-next-line react-hooks/exhaustive-deps
  }, [ visible, rangeValue ])

  const getTaskReportSummary = (startTime=null, endTime=null) => {
    dispatch({
      type: 'datasource.getTaskReportSummary',
      payload: {
        namespace: ((scope||[]).length>0?scope[0]:''),
        startTime,
        endTime
      },
      callback: data => {

        function compare(val1, val2) {
          var a = val1.seq;
          var b = val2.seq;
          return (a - b);
        }

        (data||[]).sort(compare);
        setSummaryDatas(data||[]);

        const _currentSummaryData = (data||[]).length>0?data[0]:{};
        setCurrentSummaryData(_currentSummaryData);
        getTaskReportDetail(_currentSummaryData.params, startTime, endTime);
      }
    })
  }

  const getTaskReportDetail = (params, startTime, endTime) => {
    dispatchLatest({
      type: 'datasource.getTaskReportDetail',
      payload: {
        namespace: ((scope||[]).length>0?scope[0]:''),
        params,
        startTime,
        endTime
      },
      callback: data => {

        function compare(val1, val2) {
          var a = val1.seq;
          var b = val2.seq;
          return (a - b);
        }

        data && (data.title||[]).sort(compare);

        let _scopes = [];

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

        data && (data.title||[]).forEach(item => {
          item.title = item.value||'';
          item.dataIndex = item.name||'';
          item.ellipsis = true;
        })

        if (data) {
          data.title = [{
            title: '序号',
            dataIndex: 'key',
            render: (text, record, index) => {
              return (index+1).toString();
            },
            width:80
          }, ...(data.title||[])];
        }

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

        setReportDetail(data||{});

        setFilterReportData(data?(data.datas||[]).filter(item => (item.scope||'').indexOf(keyword)!==-1 || (item.databaseName).indexOf(keyword)!==-1):[]);
      }
    })
  }

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

  const onTimeChange = (value, dateString) => {
    if (value === null) {
      setRangeValue([]);
    }
  }

  const onTimeOk = (value) => {

    const _moments = [];

    value.forEach(item => {
      if ((item||'') !== '') {
        _moments.push(item.valueOf());
      }
    })

    setRangeValue(_moments);
  }

  const onSummaryDataChange = (item) => {
    if (item.hasDetail) {
      setTaskTracersBindStateId([]);
      setCurrentSummaryData(item);
      setExpandedRowKeys([]);
      getTaskReportDetail(item.params, (rangeValue.length)>=1?rangeValue[0]: null, (rangeValue.length)===2?rangeValue[1]: null);
    }
  }

  const onSearchInputChange = (e) => {
    setKeyword(e.target.value||'');
    setFilterReportData((reportDetail.datas||[]).filter(item => (item.scope||'').indexOf(e.target.value||'')!==-1 || (item.databaseName||'').indexOf(e.target.value||'')!==-1));
  }

  const reset = () => {
    setSummaryDatas([]);
    setCurrentSummaryData({});
    setReportDetail({});
    setTaskTracersBindStateId([]);
    setExpandedRowKeys([]);
    setFilterReportData([]);
    setKeyword('');
  }

  return (
    <Modal
      className='task-report-modal'
      forceRender
      title={'日志报告'}
      visible={visible}
      width={1000}
      onCancel={() => { 
        reset();
        onCancel && onCancel() 
      }}
      footer = {
        <Button
          key="1" 
          type="primary"
          onClick={() => {
            reset();
            onCancel && onCancel() 
          }}
        >
        取消
        </Button>
      }
    >
      <div className='d-flex' style={{ alignItems: 'center' }}>
        <span>查询报告:</span>
        <RangePicker
          className='ml-3'
          locale={locale}
          showTime={{ format: 'HH:mm' }}
          format="YYYY-MM-DD HH:mm"
          onChange={onTimeChange}
          onOk={onTimeOk}
        />
      </div>
      <Row className='mt-5' gutter={20}>
      {
        summaryDatas && summaryDatas.map((item, index) => {
          const classes = classNames((item===currentSummaryData)?'title-highlight':'title' , {
            'pointer': item.hasDetail
          }); 

          return (
            <Col key={index} span={6}>
              <Card>
                <Meta 
                  title={
                    <div className={classes}  onClick={() => { onSummaryDataChange(item); }}>
                    {item.cnName||''}  
                    </div>
                  }
                  description={
                    <div style={{ color: '#000', fontSize: 16 }}>
                      <span>{item.value||0}</span>
                      <span>{item.unit?` (${item.unit}) `: ''}</span>
                    </div>
                  }
                />
              </Card>
            </Col>
          );
        })
      }  
      </Row>
      <div className='d-flex mt-5' style={{ alignItems: 'center' }}>
        <span className='mr-3'>日志搜索:</span>
        <Input 
          placeholder="请输入系统名称或者数据源名称" 
          allowClear 
          value={keyword}
          onChange={onSearchInputChange} 
          style={{ width: 250 }}
        />
      </div>
      <Table
        className='mt-3'
        columns={reportDetail.title||[]} 
        rowKey={'taskStateId'}
        dataSource={filterReportData||[]}
        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 TaskLogsModal;