/* eslint-disable */
import { useContext, useState } from 'react';

import { Form, Input, Modal, Image, Button, Row, Col } from 'antd';
import type { UploadFile } from 'antd/es/upload/interface';
import NImage from 'next/image';

import deleteIcon from '~/assets/images/delete-icon.png';
import uploadImg from '~/assets/images/upload.png';
import { Uploader } from '~/components/uploader';
import { useGeolocation } from '~/lib/hooks';
import { UserContext } from '~/lib/userProvider';

import api from './api';
import styles from './index.module.scss';

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

const normFile = (e: any) => {
  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 } = useContext(UserContext);
  const position = useGeolocation();

  // 图片上传
  const fileUploadChange = (value: any) => {
    setFileList([...fileList, ...value]);
  };
  // 删除媒体
  const deleteMedia = (file: UploadFile) => {
    const 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}>
              <Uploader
                fileUpload
                showUploadList={false}
                fileSize={5}
                fileLength={9}
                fileType={[
                  'video/mp4',
                  'video/avi',
                  'video/wmv',
                  'video/rmvb',
                  'image/png',
                  'image/jpeg',
                  'image/jpg',
                  'image/gif',
                  'image/bmp',
                ]}
                onChange={fileUploadChange}
              >
                <NImage src={uploadImg} alt='' width={100} height={100} />
              </Uploader>
            </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>
  );
}
