import {
  Button,
  Form,
  NavBar,
  TextArea,
  Uploader,
} from "@nutui/nutui-react-taro";
import { View } from "@tarojs/components";
import Taro, { showToast, navigateBack } from "@tarojs/taro";
import { useState } from "react";
import { createPostApi } from "../../api/post";
import { ArrowLeft } from "@nutui/icons-react-taro";

const Publish = () => {
  const [uploadedFiles, setUploadedFiles] = useState<any[]>([]);
  const [form] = Form.useForm();

  // 获取 Authorization token
  const getAuthToken = () => {
    const token = Taro.getStorageSync("Authorization");
    return token ? `Bearer ${token}` : "";
  };

  // 处理提交
  const handleSubmit = async (data: any) => {
    const res: any = await createPostApi({
      circle_id: 1,
      content: data.content,
      media_url: data.urls.map((item: any) => item.url).join(","),
    });
    if (res.code === 200) {
      showToast({ title: "发布成功", icon: "success" });
      setTimeout(() => {
        navigateBack({ delta: 1 });
      }, 1500);
    }
  };

  // 处理上传成功
  const handleUploadSuccess = (param: {
    responseText: string;
    option: any;
    files: any[];
  }) => {
    // 从 responseText 中解析响应数据
    let responseData: any = null;
    try {
      // responseText 是一个对象，实际数据在 data 字段中
      const responseString =
        (param.responseText as any).data || param.responseText;
      responseData =
        typeof responseString === "string"
          ? JSON.parse(responseString)
          : responseString;
    } catch (error) {
      console.error("解析 responseText 失败:", error);
    }

    if (responseData && responseData.code === 200 && responseData.data) {
      const newFile = {
        name: responseData.data.origin_name || "未命名图片",
        url: responseData.data.media_url,
        uid: new Date().getTime(),
        type: "image",
        status: "success",
        message: "上传成功",
      };

      // 添加到现有文件列表
      setUploadedFiles((prevFiles) => {
        const updatedFiles = [...prevFiles, newFile];
        console.log("添加新文件:", newFile);
        console.log("更新后的文件列表:", updatedFiles);
        return updatedFiles;
      });
      console.log("添加新文件:", newFile);
      console.log("更新后的文件列表:", [...uploadedFiles, newFile]);
      // 追加图片到 uploadedFiles 状态
      form.setFieldValue("urls", [...uploadedFiles, newFile]);
    }
  };

  return (
    <>
      <NavBar
        back={
          <>
            <ArrowLeft />
            返回
          </>
        }
        onBackClick={(e) => {
          e.preventDefault();
          navigateBack({ delta: 1 });
        }}
      >
        发布
      </NavBar>
      <View className="p-[10px] pt-[0] bg-[#f7f8fa] min-h-screen">
        <Form form={form} onFinish={(data) => handleSubmit(data)}>
          <Form.Item name="content">
            <TextArea placeholder="这一刻的想法..." rows={10} />
          </Form.Item>

          <Form.Item name="urls">
            {/* 调试信息 */}
            <Uploader
              uploadLabel="添加图片"
              multiple
              maxCount={9}
              autoUpload
              accept="image/*"
              url={`/api/files/upload`}
              headers={{
                Authorization: getAuthToken(),
              }}
              onSuccess={handleUploadSuccess}
            />
          </Form.Item>
          <Form.Item>
            <Button block type="primary" onClick={() => form.submit()}>
              发布
            </Button>
          </Form.Item>
        </Form>
      </View>
    </>
  );
};

export default Publish;
