import React, { useState } from 'react';
import { PictureOutlined } from '@ant-design/icons';
import { InterDataType, InterReqType } from '~/api/interface';
import { insertUserMessageType, selectUserListType } from '~/api/interface/systemManageType';
import { FileUploadProps, Uploader } from '~/components/uploader';
import { SystemManageAPI } from '~/api';
import { Button, Input, message } from 'antd';

// 当前消息类型
type DataType = InterDataType<selectUserListType>;
// 请求类型
type ReqType = Omit<InterReqType<insertUserMessageType>, 'receiverUserId'>;

const MessageChatActionView: React.FC<{
  currentData: DataType[0];
  userAccountId: number;
  onRefresh: () => void;
}> = ({ currentData, userAccountId, onRefresh }) => {
  // 消息数据
  const [messageValue, setMessageValue] = useState<string>();
  // 提交数据
  const handleSubmit = async (data?: ReqType) => {
    if (!messageValue && !data?.imgUrl) {
      await message.warning('请输入内容');
      return;
    }
    if (currentData?.userAccountId === userAccountId) {
      await message.warning('不能给自己发送消息');
      return;
    }
    const res = await SystemManageAPI.insertUserMessage({
      content: messageValue,
      receiverUserId: currentData?.userAccountId,
      backUserId: currentData?.companyInfoVO?.backUserId,
      sendUserId: userAccountId,
      ...data,
    });
    if (res && res.code === '200') {
      setMessageValue(undefined);
      await message.success('发送成功');
      // 刷新数据
      onRefresh?.();
    }
  };
  // 上传图片回调
  const handleUploadImage: FileUploadProps['onChange'] = async (res) => {
    await handleSubmit({
      imgUrl: JSON.stringify([res?.at(-1)?.url]),
    });
  };
  return (
    <div className='message-chat-action'>
      <div className='action-head'>
        <Uploader
          fileUpload
          listType='text'
          fileLength={6}
          fileSize={50}
          showUploadList={false}
          onChange={handleUploadImage}
        >
          <PictureOutlined style={{ fontSize: 20, color: '#777' }} />
        </Uploader>
      </div>
      <div className='action-input'>
        <Input.TextArea
          value={messageValue}
          maxLength={200}
          placeholder='请输入消息，点击发送按钮发送'
          showCount
          rows={4}
          onChange={(e) => setMessageValue(e.target.value)}
          // placeholder='请输入消息，按Enter键 或 点击发送按钮发送'
        />
      </div>
      <div className='action-button flex-end'>
        <Button type={'primary'} onClick={() => handleSubmit()}>
          发送
        </Button>
      </div>
    </div>
  );
};

export default MessageChatActionView;
