import React, { useEffect, useState } from 'react';
import { Timeline, Spin } from 'antd';

import { dispatch } from '../../../../model'; 
import { formatVersionHistoryDate } from '../../../../util';
import { Action, ModelerId, VersionId } from '../../../../util/constant';
import IframeDrawer from '../../ModelConfig/Component/IframeDrawer' ;

const VersionHistory = (props) => {

  const { id } = props;
  const [ versions, setVersions ] = useState([]);
  const [ loading, setLoading ] = useState(false);
  const [ iframeDrawerParams, setIframeDrawerParams ] = useState({
    visible: false,
    title: undefined,
    url: undefined,
  })

  useEffect(() => {
    if ((id||'') !== '') {
      getVersions();
    }
    
    //eslint-disable-next-line react-hooks/exhaustive-deps
  }, [ id ])

  const getVersions = () => {
    setLoading(true);
    dispatch({
      type: 'datamodel.getVersions',
      payload: {
        params: {
          id
        }
      },
      callback: data => {
        setLoading(false);
        setVersions(data||[]);
      },
      error: () => {
        setLoading(false);
      }
    })
  }

  const onVersionItemClick = (version) => {
    setIframeDrawerParams({
      visible: true,
      title: '模型版本详情',
      url: `/data-govern/data-model-action?${Action}=detail-version&${ModelerId}=${version.dataModelId||''}&${VersionId}=${version.id||''}`
    })
  }

  return (
    <Spin spinning={loading}>
      <Timeline style={{ padding: 24 }}>
      {
        (versions||[]).map((version, index) => {
          let name = version.name||'';
          if (index === 0 && version.id !== '-1') {
            name = name+'(当前版本)';
          }
          if (index === 1 && versions[0].id === '-1') {
            name = name+'(当前版本)';
          }

          let color = '';
          if (version.state?.id === '1') {
            color = '#DE7777';
          } else if (version.state?.id === '2') {
            color = '#779BDE';
          } else if (version.state?.id === '4') {
            color = '#77DEBF';
          }

          return <Timeline.Item key={index} color={ color } >
            <div>
              <div>
                <a onClick={()=>{ onVersionItemClick(version); }}>
                {name}
                </a>
              </div>
              <div className='pt-2'>
                <span style={{ color }}>{version.state?.cnName||''}</span>
              </div>
              <div className='pt-2'>
                <span>{version.editor||''}</span>
                <span className='pl-2'>{formatVersionHistoryDate(version.ts)}</span>
              </div>
            </div>
          </Timeline.Item>
        })
      }
      </Timeline>
      <IframeDrawer
        {...iframeDrawerParams}
        onCancel={() => {
          setIframeDrawerParams({
            visible: false,
            title: undefined,
            url: undefined,
          })
        }}
      />
    </Spin>
  );
}

export default VersionHistory;