import React from 'react'
import { Row, Col, Select, Space, Tooltip, Spin, Typography } from 'antd'

import { dispatch } from '../../../../model'
import Table from '../../../../util/Component/Table'

import '../../Model/Component/VersionCompare.less'

const FC = ({ item }) => {
  const [versions, setVersions] = React.useState()
  const [basicVersion, setBasicVersion] = React.useState()
  const [incVersion, setIncVersion] = React.useState()
  const [loading, setLoading] = React.useState(false)
  const [compareData, setCompareData] = React.useState()
  const [loadingCompare, setLoadingCompare] = React.useState(false)

  React.useEffect(() => {
    if (item?.id) {
      getVersions()
    }    
  }, [item])

  const [basicVersions, incVersions] = React.useMemo(() => {
    let newBasicVersions = [], newIncVersions = []
    for (const [index,item] of (versions??[]).entries()) {
      let name = `${item.name??''}_${new Date(item.createdTs).toLocaleString()}`
      if (index === 0) {
        name = name+'(当前版本)'
      }

      newBasicVersions.push({ id: item.id, name });
    }
    const index = newBasicVersions.findIndex(item => item.id === basicVersion)
    if (index !== -1) {
      newIncVersions = newBasicVersions.slice(0, index)
    }

    return [newBasicVersions, newIncVersions]
  }, [versions, basicVersion])

  const getVersions = () => {
    setLoading(true)
    dispatch({
      type: 'datamodel.getRuleCatalogVersionList',
      payload: {
        catalogId: item?.id,
      },
      callback: data => {
        setLoading(false)
        setVersions(data)
        if ((data??[]).length >= 2) {
          setBasicVersion(data[1].id)
          setIncVersion(data[0].id)
          getCompare()
        }
      },
      error: () => {
        setLoading(false);
      }
    })
  }

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

  const onIncChange = (value) => {
    setIncVersion(value)
    getCompare()
  }

  const getCompare = () => {
    setBasicVersion(prevBasicVersion => {
      setIncVersion(prevIncVersion => {
        setLoadingCompare(true)
        dispatch({
          type: 'datamodel.compareRuleCatalogVersion',
          payload: {
            leftVersionId: prevBasicVersion,
            rightVersionId: prevIncVersion
          },
          callback: data => {
            setLoadingCompare(false)
            setCompareData(data)
          },
          error: () => {
            setLoadingCompare(false)
          }
        })

        return prevIncVersion
      })

      return prevBasicVersion
    })
  }

  return (
    <div className='model-version-compare'>
      <Row gutter={15}>
        <Col span={12}>
          <Space size={8}>
            <span>基线版本:</span>
            <Select
              loading={loading}
              value={basicVersion}
              allowClear
              onChange={onBasicChange}
              style={{ width: 300 }}
            >
            {
              basicVersions?.map((item, index) => <Select.Option
                disabled={index===0} 
                key={index} 
                value={item.id}>
                  <Tooltip title={(index===0)?'最近版本只能在增量版本中被选中':''}>
                  {item.name}
                  </Tooltip>
                </Select.Option>
              )  
            }
            </Select>
          </Space>
        </Col>
        <Col span={12}>
          <Space size={8}>
            <span>增量版本:</span>
            <Select
              loading={loading}
              value={incVersion}
              allowClear
              onChange={onIncChange}
              style={{ width: 300 }}
            >
            {
              incVersions?.map((item, index) => <Select.Option
                key={index} 
                value={item.id}>
                {item.name}
                </Select.Option>
              )  
            }
            </Select>
          </Space>
        </Col>
      </Row>
    
      <div className='py-3'>    
        <Spin spinning={loadingCompare} >
        {
          compareData && <div className='flex'>
            <div style={{ flex: 1, borderRight: '1px solid #EFEFEF', paddingRight: 7.5 }}>
              <Basic 
                title='基本信息'
                header={compareData?.headers?.ruleHeader} 
                data={compareData?.left?.ruleValue} 
              /> 
              <Attribute 
                title='规则信息'
                header={compareData?.headers?.attributeHeader} 
                data={compareData?.left?.attributeValue}  
              />
            </div>
            <div style={{ flex: 1, paddingLeft: 7.5}}>
              <Basic 
                title='基本信息'
                header={compareData?.headers?.ruleHeader} 
                data={compareData?.right?.ruleValue} 
              /> 
              <Attribute 
                title='规则信息'
                header={compareData?.headers?.attributeHeader} 
                data={compareData?.right?.attributeValue}  
              />
            </div>
          </div>     
        }
        </Spin>
      </div>
    </div>
  )
}

export default FC

export const Basic = ({ header, data, title }) => {
  return (
    <Typography>
      <div className='mb-3'>
        <Typography>
          <Typography.Title level={5}>{title}</Typography.Title>
        </Typography>
      </div>
      {
        header?.map((item, index) => {
          let columnValue = undefined
          if ((data??[]).length>index) {
            columnValue = data[index]
          }

          let stateClassName = ''
          if (columnValue?.state==='ADD' || columnValue?.state==='UPDATE') {
            stateClassName = 'add'
          } else if (columnValue?.state === 'DELETE') {
            stateClassName = 'delete'
          }

          return (
            <Typography.Paragraph>
              <Tooltip key={index} title={columnValue.value||''}>
                <Typography.Text ellipsis={true}>
                {item??''}:&nbsp;<Typography.Text className={stateClassName}>{columnValue.value||''}</Typography.Text>
                </Typography.Text>
              </Tooltip>
            </Typography.Paragraph>
          );
        })
      }
    </Typography>
  )
}

export const Attribute = ({ header, data, title }) => {
  const [columns, tableData] = React.useMemo(() => {
    const newTableData = [], newColumns = [{
      title: '序号',
      dataIndex: 'index',
      width: 100,
      render: (_, __, index) => `${index+1}`
    }]

    for (const [index, item] of (header||[]).entries()) {
      newColumns.push({
        title: item??'',
        dataIndex: `column${index}`,
        render: (item, record) => {
          let stateClassName = '';
          if (item?.state==='ADD' || item?.state==='UPDATE') {
            stateClassName = 'add';
          } else if (item?.state === 'DELETE') {
            stateClassName = 'delete';
          }

          return (
            <Typography.Paragraph>
              <Tooltip title={item?.value}>
                <Typography.Text className={stateClassName} ellipsis={true}>{item?.value||''}</Typography.Text>
              </Tooltip>
            </Typography.Paragraph>
          );
        },
        ellipsis: true,
        option: true,
      })
    }
 
    for (const item of data??[]) {
      let newAttrItem = {}
      for (const [index, _item] of item.entries()) {
        newAttrItem[`column${index}`] = _item
      }
      newTableData.push(newAttrItem)
    }

    return [newColumns, newTableData]
  }, [header, data])

  return (
    <div>
      <div className='my-3'>
        <Typography>
          <Typography.Title level={5}>{title}</Typography.Title>
        </Typography>
      </div>
      <Table
        columns={columns||[]}
        dataSource={tableData}
        pagination={false}
      />
    </div>
  )
}