import React from "react"
import { Button, Space, Input, Divider, Upload, Row, Col, Tooltip, List, Typography, Modal } from "antd"
import { DownOutlined, UpOutlined, PlusOutlined } from '@ant-design/icons'
import { showMessage } from "../../../../util"
import { dispatch } from '../../../../model'

import './ImportActionComment.less'

const FC = (props) => {
  const { modelerData } = props
  const [isCollapse, setCollapse] = React.useState(true)
  const [uploading, setUploading] = React.useState(false)
  const [fileList, setFileList] = React.useState()
  const [comment, setComment] = React.useState()
  const [comments, setComments] = React.useState()
  const [modal, contextHolder] = Modal.useModal()

  React.useEffect(() => {
    if (modelerData?.id) {
      getComments()
    }
  }, [modelerData])

  const getComments = () => {
    dispatch({
      type: 'datamodel.getComments',
      payload: {
        modelId: modelerData?.id
      },
      callback: data => {
        setComments(data)
      }
    })
  }

  const onAddCommentClick = () => {
    if (uploading) {
      showMessage('warn', '文件上传中,请稍后')
      return
    }

    dispatch({
      type: 'datamodel.addComment',
      payload: {
        data: {
          fileList,
          modelId: modelerData?.id,
          comment
        }
      },
      callback: data => {
        showMessage('success', '发表评论成功')
        setFileList([])
        setComment()
        getComments()
      }
    })
  }

  const onDeleteClick = (item) => {
    modal.confirm({
      title: '提示',
      content: '确定删除该评论嘛?',
      onOk: () => {
        dispatch({
          type: 'datamodel.deleteComment',
          payload: { 
            id: item?.id
          },
          callback: data => {
            showMessage('success', '删除成功')
            getComments()
          },
        })
      }
    })
  }

  const uploadProps = {
    beforeUpload: file => {
      const isLt5M = file.size / 1024 / 1024 < 5
      if (!isLt5M) {
        showMessage('error', '上传文件必须小于5M')
        return false
      }

      setUploading(true)
      dispatch({
        type: 'datamodel.uploadCommentFile',
        payload: {
          fileList: [file]
        },
        callback: data => {
          setUploading(false)
          if (data) {
            setFileList(prevFileList => {
              return [...prevFileList??[], data]
            })
          }
        },
        error: () => {
          setUploading(false)
        }
      }) 

      return false
    },
    fileList: []
  }

  return (
    <div className='model-import-action-comment'>
      <div className='mb-3'>
        <Space>
          <h3 style={{ marginBottom: 0 }}>评论{` (${(comments??[]).length})`}</h3>
          {
            isCollapse ? <Button type='primary' size='small' onClick={() => {
              setCollapse(!isCollapse)
            }}>展开<DownOutlined /></Button> : <Button type='primary' size='small' onClick={() => {
              setCollapse(!isCollapse)
            }}>收起<UpOutlined /></Button>
          }
        </Space>
      </div>
      {
        !isCollapse && <React.Fragment>
          <div style={{ border: '1px solid #d9d9d9', borderRadius: 4 }}>
            <Input.TextArea value={comment} bordered={false} rows={3} placeholder='请输入您的评论' onChange={(e) => { setComment(e.target.value) }}  />
            <Divider style={{ margin: 0 }}/>
            <div className='flex' style={{ padding: '8px 11px', justifyContent: 'space-between' }}>
              <Space align='start'>
                <Upload {...uploadProps }>
                  <Button size='small' icon={<PlusOutlined />} />
                </Upload>
                <AttachesItem value={fileList} onChange={(val) => { setFileList(val) }} />
              </Space>
              <Tooltip title={comment?'':'请先输入您的评论'}>
                <Button disabled={!comment} size='small' type='primary' onClick={onAddCommentClick}>发表评论</Button>
              </Tooltip>
            </div>
          </div>
          <div className='my-3'>
            <List
              itemLayout="horizontal"
              dataSource={comments??[]}
              pagination={
                (comments??[]).length<=20 ? false : {
                pageSize: 20,
                size: 'small',
              }}
              renderItem={(item) => (
                <List.Item
                  actions={item.currentUser?[<a key="list-delete" onClick={() => {
                    onDeleteClick(item)
                  }}>删除</a>]:null}
                >
                  <List.Item.Meta
                    avatar={
                      <div style={{ width: 60 }}>
                        <Tooltip title={item.userName}>
                          <Typography.Text ellipsis={true}>{item.userName}</Typography.Text>
                        </Tooltip>
                      </div>
                    }
                    title={
                      <div>
                        {item.comment}
                        <AttachesItem value={item.fileList} readOnly />
                      </div>
                    }
                    description={new Date(item.createdTS).toLocaleString()}
                  />
                </List.Item>
              )}
            />
          </div>
        </React.Fragment>
      }
      {contextHolder}
    </div>
  )
}

export default FC

const AttachesItem = ({ value, onChange, readOnly }) => {
  return (
    <React.Fragment>
      {
        value?.map((item, index) => {
          return (
            <div key={index} style={{ marginTop: (!readOnly&&index!==0)?5:0 }}>
              <Space>
                <a onClick={() => {
                  window.open(`/api/datamodelercomment/file/download?id=${item.id}`)
                }}>{item.fileName}
                </a>
                {
                  !readOnly && <Button 
                    size='small' 
                    type='danger'
                    onClick={() => {
                      dispatch({
                        type: 'datamodel.deleteCommentFile',
                        payload: {
                          id: item?.id
                        },
                        callback: () => {
                          const newValue = [...value]
                          newValue.splice(index, 1)
                          onChange?.(newValue)
                        }
                      }) 
                    }}
                  >删除</Button>
                }
              </Space>
            </div>
          )
        })
      }
    </React.Fragment>
  )
}