import React, { useMemo } from 'react'
import ImageGallery from '../ImageGallery';
import { ClassNamesFn, themeable } from '../../theme';
import Icon from '../icons'
import { RecordTypeEnum, FileTypeEnum, ActionEnum } from './enum'
import type { CommentReplyType, FileType, LinkType, RecordType } from './type'
import { displayTime, transformDate } from '../../utils/helper'


class FileImg extends React.Component<any, any>{
  list?: Array<any>
  constructor(props: any) {
    super(props);
    this.state = {
      src: '',
      originalSrc: '',
    }
  }
  componentDidMount() {
    const {
      imgsrc
    } = this.props
    this.setState({
      src: imgsrc,
      originalSrc: imgsrc,
    })
  }
  render() {
    const {
      onImageEnlarge,
      imgsrc,
    } = this.props
    return (
      <div className='news-fileimg' onClick={() => { onImageEnlarge(this.state) }} >
        <div className='fileimg-hover'>
          <span><Icon icon="search" className='icon'></Icon></span>
        </div>
        <img src={imgsrc} alt="" />
      </div>
    )
  }

}


const CommentComponent: React.FC<CommentReplyType & {
  classnames: ClassNamesFn
  onEvent: Function
}> = (props) => {
  let { 
    classnames: cx,
    id,// 评论id
    type,
    username,// 用户名
    content,// 评论内容
    avatar,// 用户头像
    date,// 发表时间
    replyId,// 回复id
    deleted,// 是否已被删除 如果删除了 content可以不给
    deleteDate,// 删除时间
    isSelf,// 是否是自己的评论
    reply,// 被回复的用户名
    replyContent,// 被回复的内容
    replyDeleted,// 被回复的评论是否被删除
    onEvent,
  } = props;

  let dateText = date? displayTime(new Date(date).getTime(), Date.now()): ''
  let deleteDateText = deleteDate? transformDate(new Date(deleteDate).getTime()).date: ''

  return (
    <div className={cx(`Record-message`)}>
      <div className={cx(`Record-message-icon`)}>
        <div className={cx(`Record-message-member-avatar`)}>
          {avatar?<img src={avatar} />:null}
        </div>
      </div>
      <div className={cx(`Record-message-info`, {
        'is-deleted': deleted
      })}>
        <span className={cx(`Record-message-user`)}>{username}：</span>
        <div className={cx(`Record-message-content`)}>
          <span className={cx(`Record-message-content-text`)}>{content}</span>
          {
            replyId?(
              <div className={cx(`Record-message-quote`, {
                'is-deleted': replyDeleted
              })}>
                <span>
                  <span className={cx('Record-message-quote-author')}>{reply}：</span>
                  <span className={cx('Record-message-quote-text')}>{replyContent}</span>
                </span>
              </div>
            ): null
          }
        </div>

        <div className={cx(`Record-message-footer`)}>
          <div className={cx('Record-message-time')}>
            <span>{dateText}</span>
          </div>
          {
            deleted ?  <div className={cx('Record-message-update-time')}>删除于 {deleteDateText}</div> : (
              <div className={cx('Record-message-action')}>
                {
                  isSelf? (
                    <>
                    <span className={cx('Record-message-action-delete')} onClick={() => {
                      onEvent(type, id, ActionEnum.del)
                    }}>删除</span>
                    <span className={cx('Record-message-action-edit')} onClick={() => {
                      onEvent(type, id, ActionEnum.edit)
                    }}>编辑</span>
                    </>
                  ): null
                }
                <span className={cx('Record-message-action-reply')} onClick={() => {
                  onEvent(type, id, ActionEnum.reply)
                }}>回复</span>
              </div>
            )
          }
          
        </div>

      </div>
    </div>
  )
}

const FileComponent: React.FC<FileType & {
  classnames: ClassNamesFn
}> = (props) => {

  let {
    classnames: cx,
    username,
    fileType,
    filesize,
    fileUrl,
    date,
  } = props;

  let dateText = date? displayTime(new Date(date).getTime(), Date.now()): ''

  let fileName = fileUrl?.split('/')?.slice(-1)?.[0] || ''
  return (
    <div className={cx(`Record-message`)}>
      <div className={cx(`Record-message-icon`)}>
        <div className={cx(`Record-message-member-avatar`)}>
          <Icon icon='attachment'/>
        </div>
      </div>
      <div className={cx(`Record-message-info`)}>
        <span className={cx(`Record-message-user`)}>{username}：</span>
        {
          fileType === FileTypeEnum.img? (
            <div className={cx(`Record-message-content`)}>
              <span className='is-deleted'>上传了图片</span>
              <ImageGallery children={<FileImg imgsrc={fileUrl} />} ></ ImageGallery>
            </div>
          ): null
        }
        
        {
          fileType === FileTypeEnum.attachment? (
            <div className={cx(`Record-message-content`)}>
              <span className='is-deleted'>上传了附件</span>

              <div className='news-fileBox'>
                <span className='file-icon'>
                  <Icon icon='file' className='icon'></Icon>
                </span>
                <div>
                  <div>{fileName}</div>
                  <div style={{color:'#909090'}}>
                  {filesize}
                  </div>
                </div>
                <div className='news-filehover'>
                  <span onClick={() => {
                    window.open(fileUrl)
                  }}>
                    <Icon icon="upload" className="icon"></Icon>
                  </span>
                </div>
              </div>
            </div>
          ): null
        }
        <div className={cx(`Record-message-footer`)}>
          <div className={cx('Record-message-time')}>
            <span>{dateText}</span>
          </div>
        </div>
      </div>
    </div>
  )
}

const LinkComponent: React.FC<LinkType & {
  classnames: ClassNamesFn
}> = (props) => {

  return (
    <div>关联</div>
  )
}

const RecordComponent: React.FC<RecordType & {
  classnames: ClassNamesFn
}> = (props) => {
  let {
    classnames: cx,
    username,
    desc,
    date
  } = props;

  let dateText = date? displayTime(new Date(date).getTime(), Date.now()): ''

  const diff = useMemo(() => {
    let diffs: any[] = []
    let match: any[] | null = null
    desc = desc.replace(/\n/g, ' ')
    if(match = desc.match(/^(.+)\[(.*)\](.*)\((.*)\)(.*)$/)){// 更新
      diffs = match.slice(1, 6).map((v, i)=>{
        if(i === 1){
          return { t: 'remove', v }
        }else if(i === 2){
          return { t: 'link', v }
        }else if(i === 3){
          return { t: 'add', v }
        }else{
          return { t: 't', v }
        }
      })

    }else if(match = desc.match(/^(.+)\((.*)\)(.*)$/)){// 新增
      diffs = match.slice(1, 4).map((v, i)=>{
        if(i === 1){
          return { t: 'add', v }
        }else{
          return { t: 't', v }
        }
      })


    }else if(match = desc.match(/^(.+)\[(.*)\](.*)$/)){// 删除
      diffs = match.slice(1, 4).map((v, i)=>{
        if(i === 1){
          return { t: 'remove', v }
        }else{
          return { t: 't', v }
        }
      })

    }else{
      diffs = [{
        t: 't',
        v: desc
      }]
    }

    return (
      <span className={cx(`Record-message-diff`)}>
        {
          diffs.map((v, i)=>{
            if(v.t === 'remove'){
              return <span key={i} className="diff-remove">{v.v}</span>
            }else if(v.t === 'add'){
              return <span key={i} className="diff-add">{v.v}</span>
            }else if(v.t === 'link'){
              return v.v? v.v: <Icon icon='right-arrow-bold' key={i}/>
            }
            return v.v
          })
        }
      </span>
    )
  }, [desc])

  return (
    <div className={cx(`Record-message`)}>
      <div className={cx(`Record-message-icon`)}>
        <div className={cx(`Record-message-member-avatar`)}>
          <Icon icon='edit'/>
        </div>
      </div>
      <div className={cx(`Record-message-info`)}>
        <span className={cx(`Record-message-user`)}>{username}：</span>
        { diff }
        <div className={cx(`Record-message-footer`)}>
          <div className={cx('Record-message-time')}>
            <span>{dateText}</span>
          </div>
        </div>
      </div>
    </div>
  )
}

// @ts-ignore
export const RecordComponentMap = new Map([
  [RecordTypeEnum.comment, CommentComponent],
  [RecordTypeEnum.file, FileComponent],
  [RecordTypeEnum.link, LinkComponent],
  [RecordTypeEnum.record, RecordComponent]
])