import React, { useCallback, useEffect, useState } from "react";
import styles from "./index.module.scss";
import { CloseOutlined } from "@ant-design/icons";
import { A2BarrageType, A2R_fSaveType } from "@/types";
import { A2_APIgetRandCode, A2_APIsaveBarrage } from "@/store/action/A2Main";
import { MessageFu } from "@/utils/message";
import { Button, Form, Input } from "antd";
import TextArea from "antd/es/input/TextArea";

type Props = {
  closeFu: () => void;
  btnOkFlag: boolean; //是否开启的留言 能发送后端的开关
  barrageList: A2BarrageType[]; //所有留言的数组
  goodsId: number;
};

function Tab4Msg({ closeFu, btnOkFlag, barrageList, goodsId }: Props) {
  const [codeImg, setCodeImg] = useState<any>("");

  // 获取验证码函数
  const getRandCodeFu = useCallback(async () => {
    const res: any = await A2_APIgetRandCode();
    const reader = new FileReader();
    reader.readAsDataURL(res);
    reader.onload = () => {
      setCodeImg(reader.result);
    };
    // console.log(123, res);
  }, []);

  useEffect(() => {
    getRandCodeFu();
  }, [getRandCodeFu]);

  // 没有通过校验
  const onFinishFailed = useCallback(() => {}, []);

  // 通过校验
  const onFinish = useCallback(
    async (value: A2R_fSaveType) => {
      const obj = {
        ...value,
        goodsId,
      };
      const res = await A2_APIsaveBarrage(obj);
      if (res.code === 0) {
        MessageFu.success("留言成功，等待审核");
      }
    },
    [goodsId]
  );

  return (
    <div className={styles.Tab4Msg}>
      <div className="tab4Mmain">
        {/* 关闭按钮 */}
        <div className="tab4Mclose" onClick={closeFu}>
          <CloseOutlined />
        </div>
        <div className="tab4MTop">留言板</div>

        {/* 留言列表 */}

        {barrageList.length > 0 ? (
          <div className="tab4Mlist myscroll">
            {barrageList.map((v) => (
              <div className="tab4MlistRow" key={v.id}>
                <div className="tab4Mlist_Title">
                  <div className="tab4Mlist_Title_l">{v.authorName}</div>
                  <div className="tab4Mlist_Title_r">{v.createTime}</div>
                </div>
                <div className="tab4Mlist_Txt">{v.name}</div>
              </div>
            ))}
          </div>
        ) : (
          <div className="tab4MlistNone">暂无留言</div>
        )}

        {/* 表单主体 */}
        {btnOkFlag ? (
          <div className="tab4MF_main">
            <Form
              labelCol={{ span: 0 }}
              name="basic"
              onFinish={onFinish}
              onFinishFailed={onFinishFailed}
              autoComplete="off"
            >
              <Form.Item
                label="留言内容"
                name="name"
                rules={[
                  { required: true, message: "内容不能为空" },
                  {
                    validator: (rule, value) => {
                      if (value) {
                        const txt = value
                          .replaceAll(" ", "")
                          .replaceAll("\n", "");
                        return txt === ""
                          ? Promise.reject("内容不能为空")
                          : Promise.resolve();
                      } else return Promise.resolve();
                    },
                  },
                ]}
              >
                <TextArea
                  rows={4}
                  placeholder="请输入内容"
                  showCount
                  maxLength={50}
                />
              </Form.Item>

              <Form.Item
                label="您的昵称"
                name="authorName"
                rules={[{ required: true, message: "内容不能为空" }]}
                getValueFromEvent={(e) => e.target.value.replace(/\s+/g, "")}
              >
                <Input
                  style={{ width: 300 }}
                  maxLength={8}
                  showCount
                  placeholder="请输入内容"
                />
              </Form.Item>

              <Form.Item
                className="tab4MF_code"
                label="验证码"
                name="randCode"
                rules={[{ required: true, message: "内容不能为空" }]}
                getValueFromEvent={(e) => e.target.value.replace(/\s+/g, "")}
              >
                <Input
                  style={{ width: 200 }}
                  maxLength={5}
                  showCount
                  placeholder="请输入内容"
                />
              </Form.Item>

              {/* 验证码图 */}
              <div className="F_codeImg">
                <img src={codeImg} alt="" onClick={() => getRandCodeFu()} />
              </div>

              {/* 确定和取消按钮 */}
              <br />
              <Form.Item className="tab4MF_btn">
                <Button type="primary" htmlType="submit">
                  留言
                </Button>
                &emsp;
                <Button onClick={() => closeFu()}>取消</Button>
              </Form.Item>
            </Form>
            {/* 最后提示语句 */}
            <div className="F_tit">
              您的留言经审核并采纳后，才会在平台中公开展示
            </div>
          </div>
        ) : (
          <div className="noMsgBtn">
            <Button onClick={() => closeFu()}>关闭</Button>
          </div>
        )}
      </div>
    </div>
  );
}

const MemoTab4Msg = React.memo(Tab4Msg);

export default MemoTab4Msg;
