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 { importActionSubject } from "./ImportAction"

import './ImportActionHeader.less'
import './ImportActionComment.less'

const FC = (props) => {
  const { modelerData, action } = props
  const [isCollapse, setCollapse] = React.useState(false)
  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(() => {
  //   const $importActionSubject = importActionSubject.subscribe((props) => {
  //     if (props.type === 'expand' && props.key === 'model-import-action-comment' && props.action === action) {
  //       setCollapse(false)
  //     } 
  //   })

  //   return () => {
  //     $importActionSubject.unsubscribe()
  //   }
  // }, [action])

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

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

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

    dispatch({
      type: 'datamodel.addComment',
      payload: {
        data: {
          fileList,
          modelId: modelerData?.id,
          comment,
          type:'assetsinfo'
        }
      },
      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 => {
      if (uploading) {
        showMessage('warn', '文件上传中,请稍后')
        return
      }

      const isLt20M = file.size / 1024 / 1024 <= 100
      if (!isLt20M) {
        showMessage('error', '上传文件限制最大100M')
        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'>
      <Divider orientation='left'>评论{` (${(comments??[]).length})`}</Divider>
      {
        !isCollapse && <div className='mt-3'>
          <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 loading={uploading} 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='mt-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>
        </div>
      }
      {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>
  )
}