import {
  Button,
  Image,
  Space,
  Input,
  Modal,
  Form,
  List,
  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 || [];
        }
        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,
        })
        .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}>
                        <Image.PreviewGroup
                          preview={{
                            onChange: (current, prev) =>
                              console.log(
                                `current index: ${current}, prev index: ${prev}`
                              ),
                          }}
                        >
                          <Space size={6} wrap>
                            {item?.mediaVO?.picture?.map((img) => {
                              return (
                                <Image
                                  key={img}
                                  alt=""
                                  className="img"
                                  width={132}
                                  height={132}
                                  src={img}
                                  fallback={errImg}
                                />
                              );
                            })}
                          </Space>
                        </Image.PreviewGroup>
                      </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.userBaseInfoVO?.userImg}
                                  ></Image>
                                </div>
                                <div className={styles.info}>
                                  <div className={styles.nameWrap}>
                                    <div className={styles.commentName}>
                                      {comment.userBaseInfoVO?.nickName}：
                                      <div className={styles.date}>
                                        {moment(comment.createTime).format(
                                          "YYYY-MM-DD"
                                        )}
                                      </div>
                                    </div>
                                    <div className={styles.commentContent}>
                                      {comment.content}
                                    </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>
  );
}
