import { Button, Image, Space, Input, Form, Divider, Skeleton } from 'antd';
import Layout from '~/components/layout';
import styles from './index.module.scss';
import errImg from '~/assets/errImg';
import { RightOutlined } from '@ant-design/icons';
import { useContext, useEffect, useState } from 'react';
import PublishMessage from './components/publishMessage';
import api, { ByDynamicResp, Dynamic } from './api';
import InfiniteScroll from 'react-infinite-scroll-component';
import { UserContext } from '~/lib/userProvider';
import moment from 'moment';

interface Item extends Dynamic {
  openComment?: boolean; //是否开启评论
  showCommentAll?: boolean; //是否展示全部评论
  commentList?: Array<ByDynamicResp>; //评论列表
}

export default function Forum() {
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [list, setList] = useState<Array<Item>>([]);
  const [pageParams, setPageParams] = useState({
    pageNo: 1,
    pageSize: 16,
  });
  const [count, setCount] = useState(0); //动态总数
  const { userInfo, setNeedLogin } = useContext(UserContext);
  const [form] = Form.useForm(); //评论区的form

  useEffect(() => {
    api
      .dynamicList({
        userId: 1,
        ...pageParams,
      })
      .then((res) => {
        if (pageParams.pageNo === 1) {
          setList(res.result?.list || []);
        } else {
          setList([...list, ...(res.result?.list || [])]);
        }

        setCount(res.result?.totalCount || 0);
      });
  }, [pageParams]);

  /**
   * 展示发布模态框
   */
  const showModal = () => {
    if (userInfo) {
      setIsModalOpen(true);
    } else {
      setNeedLogin(true);
    }
  };

  /**
   * 取消发布
   */
  const onPublishCancel = () => {
    setIsModalOpen(false);
  };

  /**
   * 打开评论
   * @param item 当前点击项
   */
  const openComment = (item: Item) => {
    item.openComment = !item.openComment;
    const temp = [...list];
    setList(temp);
    getCommentList(item);
  };

  //获取评论列表
  const getCommentList = (item: Item) => {
    api
      .byDynamic({
        dynamicId: item.id,
      })
      .then((res) => {
        if (res?.code === '200') {
          item.commentList = res.result?.commentAndReplyVO || [];
        }
        const temp = [...list];
        setList(temp);
      });
  };

  //展示所有评论
  const showCommentAll = (item: Item) => {
    item.showCommentAll = true;
    const temp = [...list];
    setList(temp);
  };

  //评论内容
  const onComment = (values: any, item: Item) => {
    if (userInfo) {
      api
        .comment({
          content: values.content,
          dynamicId: item.id,
          rootPath: item.id.toString(),
        })
        .then((res) => {
          if (res.code === '200') {
            window.messageApi.success('评论成功');
            form.resetFields(['content']);
            item.commentCount += 1;
            getCommentList(item);
          }
        });
    } else {
      setNeedLogin(true);
    }
  };

  //点赞或取消
  const onLike = (item: Item) => {
    if (userInfo) {
      api
        .likeOrCancel({
          dynamicId: item.id,
        })
        .then((res) => {
          if (res.code === '200') {
            item.likes = !item.likes;
            if (item.likes) {
              item.likesCount++;
            } else {
              item.likesCount--;
            }
            const temp = [...list];
            setList(temp);
          }
        });
    }
  };

  return (
    <Layout>
      <div className={styles.forum}>
        <div className={styles.header}>
          <div className={styles.title}>最新讨论</div>
          <Button className={styles.btn} type='primary' onClick={showModal}>
            发布动态
          </Button>
        </div>
        <InfiniteScroll
          dataLength={list.length}
          next={() => setPageParams({ ...pageParams, pageNo: pageParams.pageNo + 1 })}
          hasMore={list.length < count}
          loader={<Skeleton avatar paragraph={{ rows: 1 }} active />}
          endMessage={<Divider plain>没有更多内容了~🤐</Divider>}
          scrollableTarget='body'
        >
          <Space direction='vertical' size={8} style={{ width: '100%' }}>
            {list.map((item, i) => {
              return (
                <div key={item.id} className={styles.item}>
                  <Space size={10} align='start'>
                    <Image
                      alt=''
                      className={styles.headImg}
                      src={item.userBaseInfo?.userImg}
                    ></Image>
                    <div className={styles.info}>
                      <div className={styles.name}>{item.userBaseInfo?.nickName}</div>
                      <div className={styles.desc}>{item.description}</div>
                      <div className={styles.imgs}>
                        <Space size={6} wrap>
                          {item?.mediaVO?.map((v, index: number) =>
                            v.type === 0 ? (
                              <Image
                                key={index}
                                alt=''
                                className='img'
                                width={132}
                                height={132}
                                src={v.url}
                                fallback={errImg}
                              />
                            ) : (
                              <video
                                key={index}
                                src={v.url}
                                controls
                                style={{ width: '132px', height: '132px' }}
                              />
                            ),
                          )}
                        </Space>
                      </div>
                      <div className={styles.ctrls}>
                        <div className={styles.ctrlsItem} onClick={() => openComment(item)}>
                          <div className={`${styles.ctrlsItemIcon} ${styles.iconComment}`}></div>
                          {item.commentCount}评论
                        </div>
                        <div className={styles.ctrlsItem} onClick={() => onLike(item)}>
                          <div
                            className={`${styles.ctrlsItemIcon} ${styles.iconPraise} ${
                              item.likes && styles.active
                            }`}
                          ></div>
                          {item.likesCount}赞
                        </div>
                      </div>
                    </div>
                  </Space>
                  {item.openComment && (
                    <div className={styles.commentWrap}>
                      <Form
                        form={form}
                        onFinish={(values) => {
                          onComment(values, item);
                        }}
                      >
                        <Form.Item
                          name='content'
                          rules={[{ required: true }]}
                          help=''
                          style={{ marginBottom: 0 }}
                        >
                          <div className={styles.draftWrap}>
                            <div className={styles.commentHeadImg}>自已</div>
                            <Input
                              className={styles.commentInput}
                              placeholder='说点什么吧，万一火了呢~'
                            ></Input>
                          </div>
                        </Form.Item>
                        <div className={styles.btnCommentWrap}>
                          <Button type='primary' htmlType='submit' className='btnComment'>
                            评论
                          </Button>
                        </div>
                      </Form>

                      <div className={styles.comments}>
                        {/* 判断是否展示所有评论 */}
                        {item.commentList
                          ?.filter((comment, i) => {
                            if (item.showCommentAll) {
                              return true;
                            } else {
                              if (i < 2) {
                                return true;
                              }
                            }
                          })
                          .map((comment) => {
                            return (
                              <div key={comment.id} className={styles.commentItem}>
                                <div className={styles.commentHeadImg}>
                                  <Image src={comment.userBaseInfo?.userImg}></Image>
                                </div>
                                <div className={styles.info}>
                                  <div className={styles.nameWrap}>
                                    <div className={styles.commentName}>
                                      {comment.userBaseInfo?.nickName}：
                                      <div className={styles.date}>
                                        {moment(comment.dynamicPublishTime).format('YYYY-MM-DD')}
                                      </div>
                                    </div>
                                    <div className={styles.commentContent}>
                                      {comment.description}
                                    </div>
                                  </div>
                                </div>
                              </div>
                            );
                          })}
                      </div>
                      {!item.showCommentAll && item.commentCount > 2 && (
                        <div className={styles.showAll} onClick={() => showCommentAll(item)}>
                          查看全部{item.commentCount}条评论
                          <RightOutlined size={14} />
                        </div>
                      )}
                    </div>
                  )}
                </div>
              );
            })}
          </Space>
        </InfiniteScroll>
      </div>
      <PublishMessage
        open={isModalOpen}
        onCancel={onPublishCancel}
        onOk={() => {
          setPageParams({
            ...pageParams,
            pageNo: 1,
          });
        }}
      ></PublishMessage>
    </Layout>
  );
}
