import React from "react";
import {Button, Col, Container, FormControl, Image, ListGroup, Row,} from "react-bootstrap";
import {Chat, PageProps, User} from "../entity";
import {Tooltip} from "@material-ui/core";
import moment from "moment";
import {MyInfo} from "./MyInfo";
import {MyDialog} from "../ui/MyDialog";
import {userObj} from "../ui/TestData";
import {JSONResponse, Method, request} from "../interface";
import {EmptyBodyTransform, PageDataMessage, SimpleMessage, UserRes, UserTransform} from "../result";
import {loadMyFriend, scrollBottom} from "../public";
import {Api} from "../api";
import {SimpleSnackbar} from "../ui/toast";

const maxLength=150
/**
 * 我的好友
 */
export class MyFriend extends React.Component<
    { user:string },
    {
    //好友列表
    friendList?:Array<User>;
    //查找好友关键字
    queryFriend:string;
    //查找用户关键字
    queryUser:string;
    //用户列表
    userList?:Array<User>;
    //聊天记录
    chatList:Array<Chat>;
    //当前选中好友
    friendIndex:number|null;
    //发送内容
    sendContent:String;
    //查看用户ID
    userId:string|null;
    //操作反馈
    result:JSX.Element|null;
    //分页信息
    page?:PageProps;
    //滚动提示
    scrollTip:string|null,
}
>{


    constructor(props: Readonly<any>) {
        super(props);

        this.state={
            //好友列表
            friendList:[],
            //查找好友关键字
            queryFriend:"",
            queryUser:"",
            //聊天记录
            chatList:[],
            //当前选中好友
            friendIndex:null,
            //发送内容
            sendContent:'',
            userId:null,
            result:null,
            scrollTip:null
        }
    }

    componentDidMount() {
        loadMyFriend('',this,1)
        this.joinChat()
    }

    componentWillUnmount() {
        this.leaveChat()
    }

    /**
     * 进入聊天室
     */
    joinChat(){
        this.refreshStatus(true)
    }


    /**
     * 刷新聊天室状态
     */
    refreshStatus(chatStatus:boolean){
        let that=this
        request(Api.account.refreshChat,Method.POST, {chatStatus:String(chatStatus)},new EmptyBodyTransform(),function (res:JSONResponse<SimpleMessage>) {
            switch (res.customResult) {
                case SimpleMessage.fail:
                    that.setState({
                        result:<h3 className="text-danger text-center">{chatStatus?"进入":"退出"}聊天室失败，请联系管理员</h3>
                    })
                    break
            }
        })
    }

    /**
     * 离开聊天室
     */
    leaveChat(){
        this.refreshStatus(false)
    }

    /**
     * 查找用户
     */
    queryUser(name:string){

        if(!name){
            this.setState({
                userList:[]
            })
        }else {

            let that = this
            request(Api.account.findUser, Method.GET, {name:name}, new UserTransform(), function (res: UserRes) {
                switch (res.customResult) {
                    case PageDataMessage.ok:
                        that.setState({
                            userList: res.dataList
                        })
                        break
                }
            })
        }
    }


    //加载聊天记录
    loadMyChat(user:User){

        this.setState({
            chatList:[userObj,userObj,userObj,userObj]
        })
    }

    render() {
        const that=this
        return (
            <Container>
                <Row className="d-flex justify-content-center bg-light">
                    <div>
                        <ListGroup className="overflow-auto bg-light friend-list" onScroll={(e:any)=>scrollBottom(e,that,function () {
                                loadMyFriend(that.state.queryFriend,that,(that.state.page?.currentPage||1)+1)
                            })
                        }>
                            <ListGroup.Item variant="primary">我的好友</ListGroup.Item>
                            <ListGroup.Item>
                                <FormControl value={this.state.queryFriend} placeholder="查找好友" onChange={(e)=>{
                                    this.setState({
                                        queryFriend:e.target.value
                                    })
                                    loadMyFriend(e.target.value,this,1)
                                }}/>
                            </ListGroup.Item>
                            {this.state.friendList?this.state.friendList.map((friend:User,index:number)=>

                                    <ListGroup.Item  key={"tooltip"+index}  className={"d-flex justify-content-between "+(index===this.state.friendIndex?"text-success":"text-dark")}
                                        style={{cursor:"pointer"}} variant={friend.chatStatus?"info":"secondary"}>
                                        <Tooltip  title={"点击查看和"+friend.name+"的聊天记录"} placement={"right"}>
                                            <span onClick={()=>
                                            {
                                                this.setState({
                                                    friendIndex:index
                                                })
                                                this.loadMyChat(friend)
                                            }}>{friend.name}</span>
                                        </Tooltip>
                                        <Tooltip title="查看用户信息" placement="right">
                                            <img src="user.svg" alt="查看用户信息" className="userIcon" onClick={()=>this.setState({userId:friend.userId})}/>
                                        </Tooltip>
                                    </ListGroup.Item>
                                ):null}

                            {this.state.scrollTip!==null?<SimpleSnackbar message={this.state.scrollTip} onClose={()=>this.setState({scrollTip:null})} duration={1000}/>:null}
                        </ListGroup>

                        <ListGroup className="overflow-auto bg-light friend-list">
                            <ListGroup.Item variant="primary">添加好友</ListGroup.Item>
                            <ListGroup.Item>
                                <FormControl placeholder="查找用户"  onChange={(e)=>{
                                    this.setState({
                                        queryUser:e.target.value
                                    })
                                    this.queryUser(e.target.value)
                                }}/>
                            </ListGroup.Item>

                            {this.state.userList?this.state.userList.length>0?this.state.userList.map((user:User,index:number)=>
                                <ListGroup.Item key={"list"+index} className="d-flex justify-content-between" variant="info">
                                    <span>{user.name}</span>
                                    <Tooltip title="查看用户信息" placement="right">
                                        <img src="user.svg" alt="查看用户信息" className="userIcon" onClick={()=>this.setState({userId:user.userId})}/>
                                    </Tooltip>
                                </ListGroup.Item>):<ListGroup.Item>没有匹配任何用户</ListGroup.Item>:null}
                        </ListGroup>

                    </div>

                    <Col className="d-none" xs={8}>
                        <Container className="bg-light chat-history overflow-auto">
                            {this.state.chatList.map((chat:Chat,index:number)=>
                                this.props.user===chat.userId?
                                 <Row key={"row"+index}>
                                    <Col xs={4}>
                                        <Image roundedCircle={true} src={chat.headImg} className="chat-headImg"/>
                                        <span className="d-block text-center user-name">{chat.name}</span>
                                    </Col>
                                     <Col xs={7}>
                                         <h6 className="text-center">{moment(chat.time).format("YYYY-MM-DD HH:mm:ss")}</h6>
                                         <p>{chat.content}</p>
                                     </Col>
                                 </Row>:
                                <Row key={"row"+index}>
                                    <Col xs={7}>
                                        <h6 className="text-center">{moment(chat.time).format("YYYY-MM-DD HH:mm:ss")}</h6>
                                        <p>{chat.content}</p>
                                    </Col>
                                    <Col xs={4}>
                                        <Image roundedCircle={true} src={chat.headImg} className="chat-headImg"/>
                                        <span className="d-block text-center user-name">{chat.name}</span>
                                    </Col>
                                </Row>
                            )}
                        </Container>
                        <Container className={"bg-white chat-send p-3 border-info border "+(this.state.friendIndex!==null?"":"d-none")}>
                            <Row>
                                <Col xs={12} className="chat-send-content" contentEditable={true} onKeyPress={(e:any)=>{
                                    if(e.target.innerText.length>=maxLength){
                                        e.preventDefault()
                                    }
                                }} onKeyUp={(e:any)=>
                                {
                                    this.setState({sendContent:e.target.innerText})
                                }}>

                                </Col>
                            </Row>
                            <Row>
                                <Col xs={8}>
                                    <p className="text-info align-middle">{"您还可以输入"+(maxLength-this.state.sendContent.length)+"个字符"}</p>
                                </Col>
                                <Col className="text-right">
                                    <Button variant={"info"}>发送</Button>
                                </Col>
                            </Row>
                        </Container>
                    </Col>
                </Row>

                <MyDialog content={this.state.result} open={this.state.result!=null} titleId="my-friend-dialog" menuName="提示信息" onClose={()=>this.setState({
                    result:null
                })}/>

                <MyDialog titleId="view-user" menuName="用户信息"
                          content={<MyInfo isOwn={false}  isAdd={true} userId={this.state.userId?this.state.userId:""}/>}
                          open={this.state.userId!==null} onClose={()=>this.setState({userId:null})}/>
            </Container>
        );
    }
}
