import React, { useEffect, useState, useRef } from 'react';
import { Form, Select, Spin, Tooltip, Checkbox, Typography, Space, Button } from 'antd';

import { dispatch, dispatchLatest } from '../../../../model'; 
import { formatVersionDate, showMessage } from '../../../../util';
import VersionCompareHeader from './VersionCompareHeader';
import VersionCompareTable from './VersionCompareTable';
import VersionCompareIndex from './VersionCompareIndex';

import './VersionCompare.less';

const { Text, Paragraph } = Typography;
const { Option } = Select;

const VersionCompare = (props) => {

  const { id } = props;

  const [ basicVersion, setBasicVersion ] = useState('');
  const [ basicVersions, setBasicVersions ] = useState([]);
  const [ incVersion, setIncVersion ] = useState('');
  const [ incVersions, setIncVersions ] = useState([]);
  const [ loading, setLoading ] = useState(false);
  const [ compareData, setCompareData ] = useState(null);
  const [ loadingCompare, setLoadingCompare ] = useState(false);
  const [ onlyShowChange, setOnlyShowChange ] = useState(true);

  useEffect(() => {
    if ((id||'') !== '') {
      getVersions();
    }

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

  const getVersions = () => {
    setLoading(true);
    dispatch({
      type: 'assetmanage.listDataAssetHistoryTimeline',
      payload: {
        dataAssetId: id
      },
      callback: data => {
        setLoading(false);
        const newData = [];
        (data||[]).forEach((item, index) => {

          let name = item.name||'';
          name = name + '_' + formatVersionDate(item.ts);
          if (item.isCurrentVersion) {
            name = name+'(当前版本)';
          }

          newData.push({ id: item.versionId, name });
        })

        setBasicVersions(newData);

        if (newData.length >= 2) {
          const defaultBasicVersion = newData[1].id;
          const defaultIncVersion = newData[0].id;
          setBasicVersion(defaultBasicVersion);
          let index = -1;
          (newData||[]).forEach((version, i) => {
            if (version.id === defaultBasicVersion) {
              index = i;
            }
          })

          setIncVersions((newData||[]).slice(0, index));
          setIncVersion(defaultIncVersion);
          getCompare(defaultBasicVersion, defaultIncVersion);
        }
      },
      error: () => {
        setLoading(false);
      }
    })
  }

  const onBasicChange = (value) => {
    setBasicVersion(value);
    setIncVersion('');
    setCompareData(null);

    let index = -1;
    (basicVersions||[]).forEach((version, i) => {
      if (version.id === value) {
        index = i;
      }
    })

    setIncVersions((basicVersions||[]).slice(0, index));
  }

  const onIncChange = (value) => {
    setIncVersion(value);
    getCompare(basicVersion, value);
  }

  const getCompare = (value1=basicVersion, value2=incVersion, value3=onlyShowChange) => {
    setLoadingCompare(true);
    dispatchLatest({
      type: 'assetmanage.compareDataAssetWithDescribeInfo',
      payload: {
        params: {
          dataAssetId: id,
          versionId1: value1,
          versionId2: value2,
          includeSame: !value3
        }
      },
      callback: data => {
        setLoadingCompare(false);
        setCompareData({...data, left: data?.leftValue, right: data?.rightValue});
      },
      error: () => {
        setLoadingCompare(false);
      }
    })
  }

  const onOnlyShowChange = (e) => {
    setOnlyShowChange(e.target.checked);
    if (basicVersion!=='' && incVersion!=='') {
      getCompare(basicVersion, incVersion, e.target.checked);
    }
  }

  return (
    <div className='model-version-compare'>
      <Form layout='inline'>
        <Form.Item label='基线版本'>
          <Select loading={loading} value={basicVersion} style={{ width: 300 }} onChange={onBasicChange}  >
          {
            (basicVersions||[]).map((version, index) => {

              if (index === 0) {
                return (
                  <Option key={index} value={version.id||''} disabled={true}>
                    <Tooltip title={'最近版本只能在增量版本中被选中'}>
                    {version.name||''}
                    </Tooltip>
                  </Option>
                )
              };

              return (
                <Option key={index} value={version.id||''}>
                {version.name||''}
                </Option>
              );

            })
          }
          </Select>
        </Form.Item>
        <Form.Item label='增量版本'>
          <Select value={incVersion} style={{ width: 300 }} disabled={basicVersion===''} onChange={onIncChange}>
          {
            (incVersions||[]).map((version, index) => {
              return (
                <Option key={index} value={version.id||''}>{version.name||''}</Option>
              );
            })
          }
          </Select>
        </Form.Item>
        {/* <Form.Item>
          <Space>
            <Checkbox onChange={onOnlyShowChange} checked={onlyShowChange}>仅显示差异</Checkbox>
          </Space>
        </Form.Item> */}
      </Form>

      <div className='py-5'>    
        <Spin spinning={loadingCompare} >
          <CompareDetail data={compareData} showIndex={false} />
        </Spin>
      </div>
    </div>
  );
}

export default VersionCompare;

export const CompareDetail = ({ data, showIndex=true }) => {
  const [selectedColumnTitles, setSelectedColumnTitles] = React.useState()

  return (
    <>
    { 
      data && <div className='flex'>
        <div style={{ flex: 1, borderRight: '1px solid #EFEFEF', paddingRight: 10, overflow: 'hidden'}}>
          <VersionCompareHeader data={data} />
          <VersionCompareTable 
            data={data} 
            selectedColumnTitles={selectedColumnTitles} 
            onFilterChange={(val) => setSelectedColumnTitles(val)} 
          />
          { showIndex && <VersionCompareIndex data={data} />}
        </div>
        <div style={{ flex: 1, paddingLeft: 10, overflow: 'hidden'}}>
          <VersionCompareHeader data={data} direction='right' />
          <VersionCompareTable 
            data={data} 
            selectedColumnTitles={selectedColumnTitles} 
            onFilterChange={(val) => setSelectedColumnTitles(val)} 
            direction='right' 
          />
          { showIndex && <VersionCompareIndex data={data} direction='right'/> }
        </div>
      </div> 
    }
    </>
  )
}