import { Form, Input, Modal, Upload, Image, Button, Row, Col } from 'antd';
import type { 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 uploadImg from '~/assets/images/upload.png';
import deleteIcon from '~/assets/images/delete-icon.png';
import styles from './index.module.scss';

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 [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 handleChange: UploadProps['onChange'] = (info) => {
    const isSize = (info.file as any).size / 1024 / 1024 < 5;
    if (isSize) {
      window.messageApi.error('上传文件最大5M');
      return;
    }
    const isType = [
      'video/mp4',
      'video/avi',
      'video/wmv',
      'video/rmvb',
      'image/png',
      'image/jpeg',
      'image/jpg',
      'image/gif',
      'image/bmp',
    ].includes(info.file.type as string);
    if (!isType) {
      window.messageApi.error('上传文件类型错误');
      return;
    }
    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') {
      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;
            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 deleteMedia = (file: UploadFile) => {
    let list = fileList.filter((v) => v.uid !== file.uid);
    setFileList(list || []);
  };
  //提交
  const onFinish = (values: any) => {
    setShowLoad(true);

    if (userInfo) {
      api
        .publish({
          lat: position?.position?.lat, //纬度
          lon: position?.position?.lng, //经度
          description: values.description, //描述
          userId: userInfo.id, //用户id
          mediaVO: fileList.map((item) => ({
            type: item.type?.includes('image') ? 0 : 1,
            url: item.url as string,
          })),
        })
        .then((res) => {
          setShowLoad(false);
          if (res.code === '200') {
            window.messageApi.success('发布成功');
            props.onCancel();
            props.onOk && props.onOk();
            setTimeout(() => {
              form.resetFields();
              setFileList([]);
            }, 500);
          }
        });
    }
  };
  //取消
  const handleCancel = () => {
    form.resetFields();
    setFileList([]);
    props.onCancel();
  };
  return (
    <Modal
      title=''
      open={props.open}
      onCancel={handleCancel}
      width={500}
      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={256}
            style={{ height: 120, resize: 'none' }}
          ></Input.TextArea>
        </Form.Item>
        <Row style={{ marginTop: '10px' }}>
          {fileList.length ? (
            <Col>
              <div className={styles.mediaContent}>
                {fileList.map((v, index: number) => (
                  <div className={styles.mediaItemWrap} key={index}>
                    <div className={styles.mediaItem}>
                      {v.type?.includes('image') ? (
                        <Image
                          src={v.url}
                          width={100}
                          height={100}
                          alt=''
                          style={{ verticalAlign: 'top' }}
                        />
                      ) : (
                        <video src={v.url} style={{ width: '100px', height: '100px' }} controls />
                      )}
                    </div>
                    <NImage
                      src={deleteIcon}
                      alt=''
                      className={styles.mediaDelete}
                      width={20}
                      height={20}
                      onClick={() => deleteMedia(v)}
                    />
                  </div>
                ))}
              </div>
            </Col>
          ) : (
            ''
          )}

          <Col>
            <Form.Item valuePropName='picture' getValueFromEvent={normFile}>
              <Upload
                name='uploadFile'
                action={gApi.fileUpload}
                listType='picture-card'
                onChange={handleChange}
                showUploadList={false}
                maxCount={1}
                headers={{ token: token }}
              >
                {fileList.length >= 9 ? null : (
                  <NImage src={uploadImg} alt='' width={100} height={100} />
                )}
              </Upload>
            </Form.Item>
          </Col>
        </Row>
        <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>
  );
}
