import React, { useState } from 'react';
import { Form, Input, message, Modal, ModalProps } from 'antd';
import { InterDataType } from '~/api/interface';
import { forumDetailType } from '~/api/interface/forumManageType';
import { Uploader } from '~/components/uploader';
import { PlusOutlined } from '@ant-design/icons';
import { ForumManageAPI } from '~/api';

//论坛详情返回类型
type DetailType = InterDataType<forumDetailType>;
// 参数类型
type PropsType = ModalProps & { detail?: DetailType; onCancel: () => void };

const DynamicEditModal: React.FC<PropsType> = ({ open, onCancel, detail, onOk }) => {
  // 表单钩子
  const [form] = Form.useForm();
  // 图片文件列表
  const [imgFileList, setImgFileList] = useState<any>([]);
  // 关闭事件
  const handleCancel = () => {
    form.resetFields();
    onCancel?.();
  };
  //确定事件
  const handleOk = () => {
    form.validateFields().then(async (values) => {
      const res = await ForumManageAPI.updateDynamic({
        id: Number(detail?.id),
        description: values.description,
        mediaVO: values.mediaVO,
      });
      if (res && res.code === '200') {
        message.success('编辑成功');
        onOk?.(values);
      }
    });
  };
  // 组件挂载
  React.useEffect(() => {
    if (!detail?.id) return;
    form.setFieldsValue({
      description: detail?.description,
      mediaVO: detail?.mediaVO,
    });
    setImgFileList(
      detail?.mediaVO?.filter((i) => i.type === 0).map((i, j) => ({ url: i.url, id: j })),
    );
  }, [detail]);
  return (
    <Modal open={open} title='编辑贴子' width={520} onCancel={handleCancel} onOk={handleOk}>
      <Form
        name='basic'
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 16 }}
        autoComplete='off'
        form={form}
      >
        <Form.Item
          label='详情'
          name='description'
          rules={[{ required: true, message: '请输入贴子详情' }]}
        >
          <Input.TextArea
            placeholder='请输入贴子详情'
            showCount
            rows={3}
            maxLength={140}
            allowClear
          />
        </Form.Item>
        <Form.Item
          label='图片'
          name='mediaVO'
          rules={[{ required: false, message: '请上传贴子图片' }]}
        >
          <Uploader
            listType={'picture-card'}
            fileUpload
            fileLength={9}
            fileSize={10}
            fileType={['image/png', 'image/jpeg', 'image/jpg', 'image/gif', 'image/bmp']}
            onChange={(e) => {
              setImgFileList(e);
              form.setFieldValue('mediaVO', e?.map((i) => ({ type: 0, url: i.url })));
            }}
            defaultFileList={imgFileList}
          >
            <PlusOutlined />
          </Uploader>
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default DynamicEditModal;
