import dayjs from 'dayjs';
import { Form, Input, Row, Col, Select, Upload, Modal, message } from 'antd';
import ImgCrop from 'antd-img-crop';
import { PlusOutlined, LoadingOutlined } from '@ant-design/icons';
import * as coursesAPI from '../apis/coursesAPI';
import React, { useCallback, useEffect, useState } from 'react';
import moment from 'moment';
import 'dayjs/locale/zh-cn';

const { TextArea } = Input;

const layout = {
  labelCol: {
    span: 8,
  },
  wrapperCol: {
    span: 16,
  },
};

/* eslint-disable no-template-curly-in-string */
const validateMessages = {
  required: '${label}是必填项!',
  types: {
    email: '${label} is not a valid email!',
    number: '${label} is not a valid number!',
  },
  number: {
    range: '${label} must be between ${min} and ${max}',
  },
};
/* eslint-enable no-template-curly-in-string */

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

function CreateAlbum(param) {
  const { code, form, onRequestClose } = param;
  const [isHasEditCode, setHasEditCode] = useState(); // 是否有编辑code
  const [caseListData, setCaseListData] = useState(); // 病例标签
  const [courseListData, setCourseListData] = useState(); // 课程标签
  const [initialValues, setInitialValues] = useState(null); // 设置表单的编辑初始化
  const [previewOpen, setPreviewOpen] = useState(false);
  const [previewImage, setPreviewImage] = useState('');
  const [previewTitle, setPreviewTitle] = useState('');
  const [fileList, setFileList] = useState([]);

  const [loading, setLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState();

  const handleCancel = () => setPreviewOpen(false);
  const handlePreview = async (file) => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj);
    }
    setPreviewImage(file.url || file.preview);
    setPreviewOpen(true);
    setPreviewTitle(
      file.name || file.url.substring(file.url.lastIndexOf('/') + 1),
    );
  };
  const handleRemove = () => {};
  const handleChange = async (info) => {
    if (isImage(info.file)) {
      setFileList(info.fileList);
    }

    setLoading(false);
  };
  const beforeUpload = async (file) => {
    setLoading(true);

    if (isImage(file)) {
      const url = await coursesAPI.upload(file);
      setImageUrl(url);
    } else {
      message.error('请选择图片上传');
    }
    return false;
  };
  function isImage(file) {
    return file.type && file.type.startsWith('image/');
  }
  const onFinish = async (values) => {
    let result;
    values.album.Cover = imageUrl;
    if (typeof code === 'string') {
      values.album.CourseAlbumCode = code;
      result = await coursesAPI.updateCourseAlbumAsync(values.album);
      if (result.result) {
        onRequestClose();
      } else {
        message.error('编辑失败');
      }
    } else {
      result = await coursesAPI.addCourseAlbumAsync(values.album);
      if (result.result) {
        onRequestClose();
      } else {
        message.error('创建失败');
      }
    }
  };

  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div
        style={{
          marginTop: 8,
        }}>
        上传封面图
      </div>
    </div>
  );
  useEffect(() => {
    setHasEditCode(typeof code === 'string');
    if (isHasEditCode) {
      fetchCourseDetail();
    }
    getCourseLabelsAsyncData();
  }, [isHasEditCode]);
  // 获取标签
  const getCourseLabelsAsyncData = async () => {
    /// 病例标签
    const caseList = await coursesAPI.getCourseLabelsAsyncData(1);
    let caseListResult = [];
    let courseListResult = [];
    for (let i of caseList.result) {
      caseListResult.push({
        value: i.Code,
        label: i.Name,
      });
    }

    setCaseListData(caseListResult);
    /// 课程标签
    const courseList = await coursesAPI.getCourseLabelsAsyncData(2);
    for (let i of courseList.result) {
      courseListResult.push({
        value: i.Code,
        label: i.Name,
      });
    }

    setCourseListData(courseListResult);
  };

  /// 获取专辑详情
  const fetchCourseDetail = useCallback(async () => {
    let data = await coursesAPI.fetchCourseDetail(code, 'album');
    setInitialValues(null);
    try {
      const dateObj = moment(data.StartTime).local();
      const formattedTime = dateObj.format('YYYY-MM-DD HH:mm:ss');
      if (data.Cover) {
        setFileList([{ url: data.Cover }]);
        setImageUrl(data.Cover);
      }
      data.StartTime = dayjs(formattedTime, 'YYYY-MM-DD HH:mm:ss');
    } catch (err) {
      console.log('%c Line:259 👾 err', 'color:#ed9ec7', err);
    }
    setInitialValues({
      album: data,
    });
  }, [code]);

  return initialValues || !isHasEditCode ? (
    <Form
      {...layout}
      form={form}
      labelAlign='left'
      name='nest-messages'
      onFinish={onFinish}
      initialValues={initialValues}
      validateMessages={validateMessages}>
      <Row gutter={{ xs: 8, sm: 16, md: 24, lg: 32 }}>
        <Col className='gutter-row' span={12}>
          <Form.Item
            name={['album', 'Name']}
            label='名称'
            rules={[
              {
                required: true,
              },
              {
                pattern: /^\S+$/,
                message: '名称不能包含空格',
              },
            ]}>
            <Input placeholder='请输入名称' maxLength={40} />
          </Form.Item>
        </Col>
        <Col className='gutter-row' span={12}>
          <Form.Item name={['album', 'CourseLabelCodes']} label='课程标签'>
            <Select
              allowClear
              mode='multiple'
              placeholder='请选择'
              options={courseListData}
              filterOption={(input, option) =>
                (option?.label ?? '')
                  .toLowerCase()
                  .includes(input.toLowerCase())
              }
            />
          </Form.Item>
        </Col>

        <Col className='gutter-row' span={24}>
          <Form.Item
            name={['album', 'Introduction']}
            label='专辑描述'
            labelCol={{ span: 4 }}
            rules={[{}]}>
            <TextArea rows={4} placeholder='请输入' maxLength={100} />
          </Form.Item>
        </Col>
        <Col className='gutter-row' span={24}>
          <Form.Item
            name={['album', 'Cover']}
            label='封面'
            style={{ height: '102px' }}
            labelCol={{ span: 4 }}>
            <ImgCrop aspect={16 / 9} quality={1}>
              <Upload
                listType='picture-card'
                fileList={fileList}
                accept='image/jpeg,image/png,image/jpg'
                beforeUpload={beforeUpload}
                onPreview={handlePreview}
                onChange={handleChange}>
                {fileList.length >= 1 ? null : uploadButton}
              </Upload>
            </ImgCrop>
          </Form.Item>
        </Col>
      </Row>
      <Modal
        open={previewOpen}
        title={previewTitle}
        footer={null}
        onCancel={handleCancel}>
        <img alt='example' style={{ width: '100%' }} src={previewImage} />
      </Modal>
    </Form>
  ) : (
    <div>{'loadding...'}</div>
  );
}

export default CreateAlbum;
