"use client";

import React, { useEffect, useState } from 'react';
import { Button, Form, GetProp, Input, InputNumber, Modal, Select, Upload, UploadFile, UploadProps, message } from 'antd';
import { Loading } from "@/components/dashboard/loading";
import service, { UserDataStorageName } from '@/lib/http/service';
import toast from 'react-hot-toast';
import { DocumentInfo, StaffsInfo, addDocument, addStaff } from '@/lib/http/staff';
import { usePathname, useRouter, useSearchParams } from 'next/navigation';
import { PlusOutlined, UploadOutlined } from '@ant-design/icons';
import { useLocalStorage } from '@/lib/hooks/use-local-storage';
import { UserData } from '@/components/user-menu';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { useTranslation } from 'react-i18next';





export interface CreateFormProps {
  onCancel?: () => void;
  onSubmit?: (values: StaffsInfo) => void;
  createModalVisible?: boolean;
}

const FormItem = Form.Item;

const formLayout = {
  labelCol: { span: 7 },
  wrapperCol: { span: 13 },
};

type FileType = Parameters<GetProp<UploadProps, 'beforeUpload'>>[0];

const supportedFormats: string[] = [
  "HTML", "HTM", "MHTML", "MD", "JSON", "JSONL", "CSV", "PDF", "DOCX", "DOC", "TXT",
  // "PPT", "PPTX", "PNG", "JPG", "JPEG", "BMP", "EML", "MSG", "RST", "RTF", 
  // "XML", "EPUB", "ODT", "TSV", "EML", "MSG", "EPUB", "XLSX", "XLS", "XLSD", "IPYNB",
  // "ODT", "PY", "RST", "RTF", "SRT", "TOML", "TSV", "DOCX", "DOC", "XML", "PPT",
  // "PPTX", "ENEX"
];

const MaxSize = 100

// 检查文件类型是否在支持的数组中
const isSupported = (file: UploadFile): boolean => {

  const fileName = file.type!
  const extension = fileName.split('.').pop()?.toUpperCase() ?? "";
  return supportedFormats.includes(extension);
};

const checkFileSize = (file: FileType) => {
  const maxSize = MaxSize * 1024 * 1024; // 10 MB
  if (file.size > maxSize) {
    message.error('文件大小不能超过10MB！');
    return false;
  }
  return true;
};

const checkFileType = (file: FileType) => {

  // const fileName = file.type ? file.type : file.name
  // // const fileExtension = fileName.split('.').pop().toUpperCase();
  // const fileExtension = fileName.split('/').pop()?.toUpperCase() ?? "";

  const fileExtension = file.name.split('.').pop()?.toUpperCase() ?? "";

  console.log("==checkFileType===", file, fileExtension)
  if (!supportedFormats.includes(fileExtension)) {
    message.error(`只能上传 ${supportedFormats.join(", ")} 格式的文件！`);
    return false;
  }
  return true;
};

const getBase64 = (file: FileType): Promise<string> =>
  new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result as string);
    reader.onerror = (error) => reject(error);
  });

/**
 * 添加节点
 * @param fields
 */
const handleAdd = async (staff_id: number, fields: DocumentInfo) => {
  const hide = message.loading('正在添加');
  try {
    // fields.password = md5(fields.password)
    // fields.user_alias = fields.user_name
    console.log("----------:", fields)

    let result: any = await addDocument(staff_id, [fields]);

    console.log("---handleAdd-result------:", result)
    hide();
    if (result.data.header.code != 0) {
      message.success(result.data.header.message);
      return false;
    }
    // message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};

const UploadWorkspace: React.FC<CreateFormProps> = (props) => {
  const [form] = Form.useForm();

  const [initLoading, setInitLoading] = useState(false);

  const router = useRouter();
  const [open, setOpen] = useState(false);

  const [isLoading, setIsLoading] = useState(false);
  const [payQrcode, setPayQrcode] = useState("");

  const path = usePathname()
  const { t, i18n } = useTranslation()

  const searchParams = useSearchParams()
  const staffId = searchParams.get('staffId')

  console.log("---PlanCard----", staffId, path)


  const {
    onSubmit,
    onCancel,
    createModalVisible,
  } = props;

  useEffect(() => {
    if (form && !createModalVisible) {
      form.resetFields();
    }
  }, [props.createModalVisible]);


  const handleSubmit = () => {
    if (!form) return;
    form.submit();
  };

  // const handleFinish = (values: JobListItem) => {
  //   if (onSubmit) {
  //     onSubmit(values);
  //   }
  // };

  {/* 
  file_name: string; // 原始文件名
  file_path: string; // 文件存储相对路径
  file_size: number; // 文件大小(字节)
  file_url: string; // 文件访问URL */}

  const [previewOpen, setPreviewOpen] = useState(false);
  const [previewImage, setPreviewImage] = useState('');
  const [urlImage, setURLImage] = useState('');

  const [uploading, setUploading] = useState(false);

  // const [fileInfo, setFileInfo] = useState({
  //   file_size: 0,
  //   file_url: "",
  //   file_path: "",
  //   file_name: "",
  // });
  const [fileInfo, setFileInfo] = useState<UploadFile>();


  const handlePreview = async (file: UploadFile) => {

    console.log("----handlePreview------", file)
    if (!(checkFileSize(file as FileType) && checkFileType(file as FileType))) {
      return
    }
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj as FileType);
    }

    setPreviewImage(file.url || (file.preview as string));
    setPreviewOpen(true);


  };



  const uploadButton = (
    <button style={{ border: 0, background: 'none' }} type="button">
      <PlusOutlined />
      <div style={{ marginTop: 8 }}>Upload</div>
    </button>
  );

  const [userData, setUserData] = useLocalStorage(
    UserDataStorageName,
    {
      auth_token: "",
      id: 1,
      login_ip: "",
      login_time: 0,
      role: "",
      user_name: "",
      first_name: "",
      version: ""
    } as UserData
  )

  const renderContent = () => {
    return (
      <>
        {/* <Form.Item label="版本">
          <Select defaultValue="demo" disabled>
            <Select.Option value="demo">通用版本</Select.Option>
            <Select.Option value="demo2">高级版本</Select.Option>
          </Select>
        </Form.Item> */}

        {/* <Form.Item
          label="文件名称(必填)"
          name="name"
          rules={[{ required: true }]}
        >
          <Input
            // variant="borderless"
            // className="placeholder:text-[#808080] "
            // style={{
            //   background: "#F5F5F5",
            //   borderRadius: "0",
            //   // width: 360

            // }}
            placeholder="设置名称"
          />
        </Form.Item> */}

        <Form.Item
          label="上传文档"
          name="file_url"
        // valuePropName="fileList"
        // getValueFromEvent={(e) => {
        //   if (Array.isArray(e)) {
        //     return e;
        //   }
        //   return e && e.fileList;
        // }}
        // rules={[{ required: true }]}
        >
          {/* <Input
            // variant="borderless"
            // className="placeholder:text-[#808080] "
            // style={{
            //   background: "#F5F5F5",
            //   borderRadius: "0",
            //   // width: 360

            // }}
            placeholder="设置Logo"
          /> */}
          <Card className="flex items-start justify-between ">
            <CardHeader>
              <CardTitle>支持格式</CardTitle>
              <CardDescription>
                Limit {MaxSize}MB per file • {supportedFormats.join(", ")}
              </CardDescription>
            </CardHeader>
            <CardContent>

              <Upload
                action={process.env.NEXT_PUBLIC_FILE_BASE + "/api/v1/customer/upload/file"}
                // action="//jsonplaceholder.typicode.com/posts/"
                accept='*'
                listType="picture"
                maxCount={1}
                // headers={{"Authorization": 'Bearer ' + localStorage.getItem(UserDataStorageName)}}
                // headers={{ "Authorization": localStorage.getItem(UserDataStorageName) }}

                headers={{
                  "Authorization": userData.auth_token,
                }}
                data={(file) => {
                  // const formData = new FormData()
                  // formData.append('files[]', file as FileType)
                  return {
                    file_data: file,
                    file_name: file.name,
                  }

                }}
                // defaultFileList={[fileItem]}
                // name='file_data'
                onPreview={handlePreview}

                // onChange={handleChange}
                onChange={(info) => {

                  console.log("-------info----", info)
                  if (info.file.status !== 'uploading') {
                    console.log(info.file, info.fileList);
                  }
                  if (info.file.status === 'done') {
                    message.success(`${info.file.name} file uploaded successfully`);

                    if (info.file.response.header.code === 0) {
                      setURLImage(info.file.response.data.file_url)

                      // setFileInfo(info.file.response.data)

                      setFileInfo(info.file);
                    } else {
                      message.error(`${info.file.response.header.message}.`);
                    }

                  } else if (info.file.status === 'error') {
                    message.error(`${info.file.name} file upload failed.`);
                  }





                  // setFileList([
                  //   ...fileList,
                  //   ...info.fileList,
                  //   {
                  //     uid: info.file.originFileObj?.uid || "",
                  //     name: info.file.name,
                  //     status: 'done',
                  //     url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
                  //   }
                  // ]);
                }}
                // previewFile={(file) => {
                //   console.log('Your upload file:', file);
                //   // Your process logic. Here we just mock to the same file

                //   const formData = new FormData();
                //   // fileList.forEach((file) => {
                //   //   formData.append('files[]', file as FileType);
                //   // });

                //   formData.append('files[]', file as FileType);

                //   return fetch(process.env.NEXT_PUBLIC_FILE_BASE + "/api/v1/customer/upload/file", {
                //     method: 'POST',
                //     body: formData,
                //   })
                //     .then((res) => res.json())
                //     .then(({ thumbnail }) => thumbnail);
                // }}




                beforeUpload={(file) => {
                  // setFileList([...fileList, file]);

                  console.log("====beforeUpload=======", file)

                  // const uploadedFileName = file.type

                  if (!(checkFileSize(file) && checkFileType(file))) {
                    console.log(`${file.name} is a not supported format.`);
                    // message.error('不支持格式！')
                    return false || Upload.LIST_IGNORE;
                  }
                  return true;
                }}

              >
                <Button icon={<UploadOutlined />}>Upload</Button>
              </Upload>
              <br />

            </CardContent>
          </Card>


        </Form.Item >




        <Form.Item label="文档描述"
          name="description"
        // wrapperCol={{
        //   offset: 2,
        //   span: 16
        // }}
        // validateStatus="error"
        // hasFeedback
        // help="Should have something"
        >
          <Input.TextArea
            // allowClear
            // showCount 
            // style={{
            //   background: "#fff",
            //   borderRadius: "0",
            //   border: "none",
            //   height: "100px",
            // }}
            className=""
          />
        </Form.Item>



        {/* <Button type="primary" htmlType="submit" className="bg-[#000] w-full rounded">
                创建AI客服


              </Button> */}

        <Form.Item wrapperCol={{ span: 12, offset: 12 }}>
          <Button
            // disabled={initLoading || !form.formState.isValid}

            disabled={
              initLoading
              // ||
              // !form.isFieldsTouched(true) ||
              // !!form.getFieldsError().filter(({ errors }) => errors.length).length
            }
            className="mt-4 bg-[#000] text-[#fff]"
            htmlType="submit"
          >
            {initLoading ? <Loading /> : "添加文件到知识库"}
          </Button>
        </Form.Item>




      </>
    );
  };

  const modalFooter = { okText: '保存', onOk: handleSubmit, onCancel };


  return (
    // <Modal
    //   forceRender
    //   destroyOnClose
    //   title="新建职位信息"
    //   open={createModalVisible}
    //   {...modalFooter}
    // >
    //   <Form
    //     {...formLayout}
    //     form={form}
    //     onFinish={handleFinish}
    //   >
    //     {renderContent()}
    //   </Form>
    // </Modal>

    <div>

      <Form
        {...formLayout}
        form={form}

        initialValues={{
          tone: 'friendly and sincere',
          output_length: 'short',
          language_mode: 'spoken language',
          language_response: 'chinese',
        }}
        onFinish={async (e: DocumentInfo) => {


          // file_path: string; // 文件存储相对路径
          // file_size: number; // 文件大小(字节)
          // file_url: string; // 文件访问URL

          e.file_name = fileInfo?.response.data.file_name || e.file_name
          e.file_path = fileInfo?.response.data.file_path || ""
          e.file_size = fileInfo?.response.data.file_size || ""
          e.file_url = fileInfo?.response.data.file_url || ""
          console.log("-----onFinish--------", e)
          if (await handleAdd(Number(staffId), e)) {
            router.push(`/manage/staffs/${staffId}`)
          }

        }}
      >
        {renderContent()}
      </Form>
    </div>
  );
};

export default UploadWorkspace;


