import { PlusOutlined } from "@ant-design/icons";
import { Form, Input, Modal, Upload, Image, Button, Row, Col } from "antd";
import type { RcFile, UploadProps } from "antd/es/upload";
import type { UploadFile } from "antd/es/upload/interface";
import { useContext, useEffect, useState } from "react";
import gApi from "~/api";
import NImage from "next/image";
import api from "./api";
import { useGeolocation } from "~/lib/hooks";
import { UserContext } from "~/lib/userProvider";
import { useToken } from "antd/es/theme/internal";

type Props = {
  open: boolean;
  onCancel: () => void;
  onOk?: () => void;
};

const normFile = (e: any) => {
  console.log("Upload event:", e);
  if (Array.isArray(e)) {
    return e;
  }
  return e?.fileList;
};

export default function PublishMessage(props: Props) {
  const [confirmLoading, setConfirmLoading] = useState(false);
  const [previewOpen, setPreviewOpen] = useState(false);
  const [previewImage, setPreviewImage] = useState("");
  const [previewTitle, setPreviewTitle] = useState("");
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [showLoading, setShowLoad] = useState(false);
  const [form] = Form.useForm();
  const { userInfo, setNeedLogin } = useContext(UserContext);
  const position = useGeolocation();
  const [token, setToken] = useState('');

  useEffect(() => {
    setToken(window.localStorage.getItem('token') || '');
  }, [])

  //预览关闭
  const handlePreviewCancel = () => setPreviewOpen(false);

  //图片预览
  const handlePreview = async (file: UploadFile) => {
    if (file.url) {
      setPreviewImage(file.url);
      setPreviewOpen(true);
      setPreviewTitle(
        file.name || file.url!.substring(file.url!.lastIndexOf("/") + 1)
      );
    }
  };

  //图片上传
  const handleChange: UploadProps["onChange"] = (info) => {
    console.log("uploadChange", info);
    if (info.file.status === "uploading") {
      let find = fileList.find((item) => {
        return item.uid === info.file.uid;
      });
      if (!find) {
        setFileList([...fileList, info.file]);
      }
      return;
    } else if (info.file.status === "done") {
      // Get this url from response in real world.
      if (info.file.response.code === "200" && info.file.response.result) {
        let fileList1 = fileList.map((item) => {
          if (item.uid === info.file.uid) {
            info.file.url = info.file.response.result?.[0];
            return info.file;
          }
          return item;
        });
        setFileList([...fileList1]);
      } else {
        window.messageApi.error(info.file.response?.message || "上传失败");
        info.fileList = fileList.filter((item) => {
          return item.uid !== info.file.uid;
        });
        setFileList([...info.fileList]);
      }
    } else {
      setFileList([...info.fileList]);
    }
  };

  //提交
  const onFinish = (values: any) => {
    console.log(values);
    setShowLoad(true);

    if (userInfo) {
      api
        .publish({
          lat: position?.position?.lat, //纬度
          lon: position?.position?.lng, //经度
          title: "", //标题
          description: values.description, //描述
          userId: userInfo.id, //用户id
          mediaVO: {
            //发布图片
            //@ts-ignore
            picture: fileList
              .filter((item) => item.url)
              .map((item) => item.url),
          },
        })
        .then((res) => {
          console.log("提交结果", res);
          setShowLoad(false);
          if (res.code === "200") {
            window.messageApi.success("发布成功");
            props.onCancel();
            props.onOk && props.onOk();

            setTimeout(() => {
              form.resetFields(["title", "description"]);
              setFileList([]);
            }, 500);
          }
        });
    }
  };

  return (
    <Modal
      title=""
      open={props.open}
      onCancel={props.onCancel}
      width={500}
      confirmLoading={confirmLoading}
      footer={null}
      okButtonProps={{ style: { height: 37, padding: "0 32px", fontSize: 16 } }}
      cancelButtonProps={{ style: { display: "none" } }}
      maskClosable={false}
    >
      <Form style={{ paddingTop: 32 }} onFinish={onFinish} form={form}>
        <Form.Item
          name="description"
          rules={[{ required: true }]}
          help="请输入内容"
        >
          <Input.TextArea
            allowClear
            showCount
            placeholder="输入内容"
            maxLength={100}
            style={{ height: 120, resize: "none" }}
          ></Input.TextArea>
        </Form.Item>
        <Form.Item valuePropName="picture" getValueFromEvent={normFile}>
          <Upload
            name="uploadFile"
            action={gApi.imgOss}
            listType="picture-card"
            fileList={fileList}
            onPreview={handlePreview}
            onChange={handleChange}
            maxCount={1}
            headers={{ token: token }}
          >
            {fileList.length >= 8 ? null : (
              <div>
                <PlusOutlined />
                <div style={{ marginTop: 8 }}>Upload</div>
              </div>
            )}
          </Upload>
          <Modal
            open={previewOpen}
            title={previewTitle}
            footer={null}
            onCancel={handlePreviewCancel}
            bodyStyle={{ textAlign: "center" }}
          >
            <Image alt="example" src={previewImage} preview={false} />
          </Modal>
        </Form.Item>
        <Row justify="space-between" align="middle">
          <Col>
            <NImage
              style={{ verticalAlign: "text-top", marginRight: 7 }}
              alt=""
              src={require("./assets/position.png")}
              width={14}
              height={17}
            />
            {position?.address?.formattedAddress || "位置"}
          </Col>
          <Col>
            <Button
              type="primary"
              htmlType="submit"
              size="large"
              style={{ width: 95 }}
              loading={showLoading}
            >
              发布
            </Button>
          </Col>
        </Row>
      </Form>
    </Modal>
  );
}
