import React from 'react'
import { Modal, Button, Spin, Tooltip, Typography, Space, Input } from "antd"

import { dispatch } from '../../../../model'
import Table from '../../../../util/Component/Table'
import { checkMenuAdmit, inputWidth, isSzseEnv, showMessage } from '../../../../util'
import { useDebounceEffect } from 'ahooks'
import { throwIfEmpty } from 'rxjs'

const topN = 20

const FC = (props) => {
  const { visible, name, cnName, onCancel, onOk, triggerType = 'cnName', hiveDeployed = false } = props
  const [loading, setLoading] = React.useState(false)
  const [suggests, setSuggests] = React.useState()
  const [selectedRows, setSelectedRows] = React.useState()
  const [havaMore, setMore] = React.useState(false)
  const [offset, setOffset] = React.useState(1)
  const [animating, setAnimating] = React.useState(false)
  const [args, setArgs] = React.useState({
    name: undefined,
    cnName: undefined,
    triggerType: undefined,
  })

  React.useEffect(() => {
    if (visible) {
      setAnimating(true)
      setArgs({
        name,
        cnName,
        triggerType
      })

      setTimeout(() => {
        setAnimating(false)
      }, 300)
    }
  }, [visible])

  useDebounceEffect(()=>{
    if (args.name || args.cnName) {
      getSuggests()
    }
  }, [args], { wait:300 })

  const onSourceClick = (id, name) => {
    const timestamp = new Date().getTime();
    const tempArray = (id??'').split('=');
    if (tempArray.length>=3) {

      dispatch({
        type: 'datamodel.getParent',
        payload: {
          id
        },
        callback: data => {
          window.open(`/center-home/metadetail?mid=${encodeURIComponent(data?._id)}&action=metadetail&type=detail&manager=false&activekey=1&name=${encodeURIComponent(name||'')}`);
        }
      })
    } else {
      if (checkMenuAdmit('datastandard')) {
        window.open(`/center-home/menu/datastandard?id=${id}&timestamp=${timestamp}`);
      }
    }
  }

  const cols = React.useMemo(() => {
    return [
      {
        title: '中文名称',
        dataIndex: 'cnName',
        width: 200,
        render: (text, _, __) => {
          return (
            <Tooltip title={text||''}>
              <span>{text||''}</span>
            </Tooltip>
          )
        }
      },
      {
        title: '英文名称',
        dataIndex: 'name',
        render: (text, _, __) => {
          return (
            <Tooltip title={text||''}>
              <span>{text||''}</span>
            </Tooltip>
          )
        }
      },
      {
        title: '类型',
        dataIndex: 'datatype',
        width: 160,
        render: (_, record, __) => {
          if (record?.datatype) {
  
            if ((record?.datatype?.name==='Char'||record?.datatype?.name==='Varchar') && record?.datatype?.parameterValues?.length>0) {
  
              return `${record?.datatype?.name||''}(${(record?.datatype?.parameterValues[0]?record.datatype.parameterValues[0]:0)})`;
            
            } else if ((record?.datatype?.name==='Decimal'||record?.datatype?.name==='Numeric') && record?.datatype?.parameterValues?.length>1) {
              return `${record?.datatype?.name||''}(${(record?.datatype?.parameterValues[0]?record.datatype.parameterValues[0]:0)},${(record?.datatype?.parameterValues[1]?record.datatype.parameterValues[1]:0)})`;
            }
  
            return record.datatype.name||'';
          }
  
          return '';
        }
      },
      {
        title: '业务含义',
        dataIndex: 'remark',
        render: (text, _, __) => {
          return (
            <Tooltip title={text||''}>
              <Typography.Text ellipsis={true}>{text||''}</Typography.Text>
            </Tooltip>
          )
        }
      },
      {
        title: '匹配度',
        dataIndex: 'score',
        width: 100,
        render: (_, record, index) => {
          return (
            <React.Fragment>
              <span style={{ color: '#f50' }}>{`${record.recommendedStats?.score}%`}</span>
              { index===0 && <span style={{ color: '#f50' }}> 推荐</span> }
            </React.Fragment>
          );
        }
      },
      {
        title: '使用次数',
        dataIndex: 'referencesCount',
        width: 80,
        render: (_, record) => {
          return (
            <span>{record.recommendedStats?.referencesCount}</span>
          );
        }
      },
      {
        title: '来源',
        dataIndex: 'source',
        render: (_, record) => {
          return (
            <SourceComponent data={record.recommendedStats?.sourceInfos||[]} name={record.name||''} onClick={onSourceClick} />
          );
        }
      },
    ]
  }, [onSourceClick])

  const getSuggests = () => {
    setLoading(true)
    dispatch({
      type: 'datamodel.suggest',
      payload: {
        params: {
          name: args.name,
          cnName: args.cnName,
          offset,
          topN,
        }
      },
      callback: data => {
        setLoading(false)

        if (args.triggerType === 'cnName') {
          setSuggests(prevSuggests => {
            const newSuggests = (offset===1) ? data?.[0]?.suggestions : [...prevSuggests??[], ...data?.[0]?.suggestions??[]]
            setOffset((data?.[0]?.suggestions??[]).length + offset)
            setMore((data?.[0]?.suggestions??[]).length === topN)

            return newSuggests
          })
        } else if (args.triggerType === 'name') {
          setSuggests(prevSuggests => {
            const newSuggests = (offset===1) ? data?.[1]?.suggestions :  [...prevSuggests??[], ...data?.[1]?.suggestions??[]]
            setOffset((data?.[1]?.suggestions??[]).length + offset)
            setMore((data?.[1]?.suggestions??[]).length === topN)

            return newSuggests
          })
        }
      },
      error: () => {
        setLoading(false)
      }
    })
  }

  const close = () => {
    setLoading(false)
    setAnimating(false)
    setSuggests()
    setOffset(1)
    setSelectedRows()
    setMore(false)
    onCancel?.()
  }

  const save = () => {
    if ((selectedRows??[]).length === 0) {
      showMessage('warn', '请先选择推荐项')
      return
    }

    onOk?.(selectedRows?.[0], hiveDeployed)
    close()
  }

  const footer = React.useMemo(() => {
    return [
      <Button key='cancel'
        onClick={() => close()}
      >取消</Button>,
      <Button key='save' type='primary'
        onClick={() => save()}
      >确定</Button>
    ]
  }, [close, save])

  return (
    <Modal
      visible={visible}
      footer={footer}
      width='80%'
      bodyStyle={{ padding: '15px', overflowX: 'auto', maxHeight: '80vh' }}
      title='匹配推荐'
      centered destroyOnClose
      onCancel={() => { close() }}
    >
      <div className='mb-3'>
        <Space>
          <span>中文名称:</span>
          <Input size="middle"
            placeholder="请输入中文名称"
            value={args.cnName}
            bordered={true} allowClear
            onChange={(e) => {
              setOffset(1)
              setArgs({...args, cnName: e.target.value, triggerType: 'cnName'})
            }} 
            style={{ width: inputWidth }}
          />
          <span>英文名称:</span>
          <Input size="middle"
            placeholder="请输入英文名称"
            value={args.name}
            bordered={true} allowClear
            onChange={(e) => {
              setOffset(1)
              setArgs({...args, name: e.target.value, triggerType: 'name'})
            }} 
            style={{ width: inputWidth }}
          />
        </Space>
      </div>
      {
        !animating && <Spin spinning={loading}>
          <Table
            extraColWidth={32}
            size='small'
            rowKey='iid'
            dataSource={suggests||[]}
            columns={cols}
            pagination={false}
            rowClassName={(record, index) => {
              return 'pointer';
            }}
            onRowClick={(event, record) => {
              setSelectedRows([record])
            }}
            rowSelection={{
              type: 'radio',
              selectedRowKeys: (selectedRows??[]).map(item => item.iid),
              onChange: (selectedRowKeys, selectedRows) => {
                setSelectedRows(selectedRows)
              },
            }}
          />
          <div className='flex pt-3' style={{ justifyContent: 'center' }}>
            <Tooltip title={!havaMore?'没有更多推荐字段':''}>
              <Button onClick={getSuggests} disabled={!havaMore} >加载更多</Button>
            </Tooltip>
          </div> 
        </Spin>
      }
    </Modal>
  )
}

export default FC

const SourceComponent = (props) => {
  const { data, onClick, name } = props;

  const moreSourceComponent = <div style={{ maxWidth: 400 }}>
  {
    (data||[]).map((source, index) => {
      return (
        <div 
          className='pointer'
          key={index}
          style={{
            textDecoration: 'underline',
          }}
          onClick={(e) => {
            e.stopPropagation();
            onClick && onClick(source.sourceId, name);
          }}
        >
        {source.sourcePath||''}
        </div>
      );
    })
  }
  </div>;

  return (
    <Tooltip 
      title={moreSourceComponent}
      overlayClassName='tooltip-common'
    >
      <a 
        href='#' 
        onClick={(e) => {
          e.stopPropagation();
          onClick && onClick(data[0].sourceId, name);
        }}
      >
      {
        (data||[]).length>0 && <span>{data[0].sourcePath||''}</span>
      }
      </a>
    </Tooltip>
  );
}