import React, { useEffect, useImperativeHandle, useState } from 'react';
import { Modal, Form, Input, Row, Col, Upload, message, Button } from 'antd';
import { LoadingOutlined, PlusOutlined, UploadOutlined } from '@ant-design/icons';
import Cookies from 'js-cookie';
import { uploadImgURL } from '~/api/request';
import events from '~/events';
import deletePng from '~/assets/image/delete.png';
import './index.scss';

function Index(props: any) {
  const headers: any = {
    token: Cookies.get('SXTB-TOKEN'),
  };
  const [form] = Form.useForm();
  const [imageUrl, setImageUrl] = useState('');
  const [fileList, setFileList]: any = useState([]);

  useEffect(() => {
    events.addListener('removeFileList', () => {
      // console.log("执行了");
      setFileList([]);
      setImageUrl('');
    });
    events.addListener('setImgFile', (str) => {
      setImageUrl(str);
      form.setFieldsValue({ icon: str });
    });
  });

  useImperativeHandle(props.baseRef, () => ({
    getForm: () => form,
  }));
  function onFinish() {}
  function onFinishFailed() {}
  function getBase64(img: any, callback: Function) {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
  }
  function handleChange(val: any) {
    // console.log("上传图片-->", val);
    if (!['image/jpg', 'image/jpeg', 'image/png'].includes(val.file.type)) {
      message.error('请上传图片格式为jpg，jpeg，png的图片');
      form.setFieldsValue({ icon: '' });
      setFileList([]);
      return;
    }
    const limitM = 2;
    const isLimit = val.file.size / 1024 / 1024 <= limitM;
    if (!isLimit) {
      message.error('图片最大上传2M');
      form.setFieldsValue({ icon: '' });
      setFileList([]);
      return;
    }
    if (val.file.status == 'error') {
      message.error('服务器异常');
      setFileList([]);
      form.setFieldsValue({ icon: '' });
    } else if (val.file.response && val.file.response.code != '200') {
      message.error(val.file.response.message);
      setFileList([]);
      form.setFieldsValue({ icon: '' });
    } else if (val.file.status === 'done') {
      setImageUrl(val.file.response.result[0]);
      setFileList(val.fileList);
      form.setFieldsValue({ icon: val.file.response.result[0] });
    } else {
      setFileList(val.fileList);
    }
  }
  const beforeUpload = (file: any) => {
    // const isPNG = file.type === 'image/png';
    // if (!isPNG) {
    //   message.error(`${file.name}`);
    // }
    // return isPNG || Upload.LIST_IGNORE;
  };
  // 图片删除
  const deleteImg = () => {
    setImageUrl('');
    form.setFieldsValue({ icon: undefined });
    setFileList([]);
  };
  return (
    <Modal
      title={props.title}
      visible={props.isVisable}
      onOk={() => props.handleOk()}
      onCancel={() => props.handleCancel()}
    >
      <Form
        name='basic'
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 16 }}
        initialValues={{ remember: true }}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        autoComplete='off'
        form={form}
      >
        <Form.Item
          label='分类名称'
          name='groupName'
          rules={[{ required: true, message: '请输入分类名称' }]}
        >
          <Input placeholder='请输入分类名称' maxLength={15} allowClear />
        </Form.Item>
        <Form.Item
          label='分类描述'
          name='description'
          rules={[{ required: false, message: '请输入分类描述' }]}
        >
          <Input.TextArea
            placeholder='请输入分类描述'
            showCount
            rows={3}
            maxLength={70}
            allowClear
          />
        </Form.Item>
        <Form.Item
          label='分类图标'
          name='icon'
          rules={[{ required: true, message: '请上传分类图标' }]}
        >
          {imageUrl ? (
            <div className='img-wrap'>
              <div className='img-content'>
                <img src={imageUrl} className='img' onClick={() => props.imgClick(imageUrl)} />
                <img src={deletePng} alt='' className='delete-img' onClick={deleteImg} />
              </div>
            </div>
          ) : (
            <Upload
              // className="avatar-uploader"
              name='uploadFile'
              fileList={fileList}
              action={uploadImgURL}
              maxCount={1}
              beforeUpload={beforeUpload}
              onChange={handleChange}
              headers={headers}
              accept='image/*'
            >
              {fileList.length >= 1 ? '' : <Button icon={<UploadOutlined />}>上传</Button>}
            </Upload>
          )}
        </Form.Item>
        <Form.Item label='备注' name='remark' rules={[{ required: false, message: '请输入备注' }]}>
          <Input.TextArea rows={5} maxLength={150} showCount />
        </Form.Item>
      </Form>
    </Modal>
  );
}
export default Index;
