import { useState } from 'react';
import { Form, Input, message, Modal, Upload, UploadProps } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { UploadFile } from 'antd/es/upload/interface';
// import { GoodsAPI, UserAPI } from '~/api';

interface PropsType {
  visible: boolean;
  closed: any;
  data: any;
}

export const ChangeModal = (props: PropsType) => {
  // 父组件传参
  const { visible, closed, data } = props;
  // 表格事件
  const [form] = Form.useForm();
  // 图片上传文件列表
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  // 图片是否放大
  const [visibleImg, setVisibleImg] = useState<boolean>(false);
  // 当前放大图片
  const [currentImgList, setCurrentImgList] = useState<{ src: string }[]>([]);
  // 预览图片
  const handlePreview = (url: string) => {
    setVisibleImg(true);
    setCurrentImgList([{ src: url }]);
  };
  // 关闭图片放大
  const setVisibleEvent = () => {
    setVisibleImg(false);
  };
  // 判断文件类型
  const beforeUpload: UploadProps['beforeUpload'] = ({ size, type }) => {
    const isImage = [
      'image/gif',
      'image/jpg',
      'image/png',
      'image/bmp',
      'image/jpeg',
      'image/webp',
    ].includes(type);
    if (!isImage) {
      message.warning('请上传图片').then();
      return isImage || Upload.LIST_IGNORE;
    }
    const isLimit = size / 1024 / 1024 <= 2;
    if (!isLimit) {
      message.warning('图片最大上传2M').then();
      return isLimit || Upload.LIST_IGNORE;
    }
  };
  // 上传图片
  const handleUpload: UploadProps['customRequest'] = async ({ file }) => {
    const { uid, name } = file as { uid: string; name: string };
    const formData = new FormData();
    formData.append('uploadFile', file as unknown as string);
    const res = await GoodsAPI.commonUpload(formData);
    if (res && res.code === '200') {
      setFileList([
        ...fileList,
        {
          uid,
          name,
          status: 'done',
          url: res.result[0],
        },
      ]);
      form.setFieldsValue({
        vouchers: [...fileList.map((i) => i.url), res.result[0]],
      });
    } else {
      message.warning(res.message);
    }
  };
  // 删除图片
  const handleDelete: UploadProps['onRemove'] = (res) => {
    const newFileList = fileList.filter((i) => i.uid !== res.uid);
    setFileList(newFileList);
  };
  // 关闭事件
  const handleClosed = () => {
    setFileList([]);
    form.resetFields();
    closed();
  };
  // 触发表单验证
  const handleSubmit = () => {
    form
      .validateFields()
      .then(async (values) => {
        const { mallUserId } = data;
        const res: any = await UserAPI.bountyModify({
          ...values,
          mallUserId,
        });
        if (res && res.code === '200') {
          message.success('操作成功');
          await handleClosed();
        } else {
          message.warning(res.message);
        }
      })
      .catch((err) => {
        message.warning(err.errorFields[0].errors[0]).then();
      });
  };
  return (
    <>
      <Modal
        open={visible}
        title='奖励金变更'
        onCancel={handleClosed}
        destroyOnClose
        width={768}
        onOk={handleSubmit}
      >
        <Form name='form' form={form} layout='horizontal' labelWrap>
          <Form.Item label='账号信息' labelCol={{ span: 5 }} wrapperCol={{ span: 15 }}>
            <div>{`${data.uid}（${data.userName}）`}</div>
          </Form.Item>
          <Form.Item
            label='金额变动'
            name='money'
            rules={[{ required: true, message: '请输入金额' }]}
            labelCol={{ span: 5 }}
            wrapperCol={{ span: 15 }}
          >
            <Input
              placeholder='正数表示充值，负数为扣除'
              maxLength={11}
              allowClear
              type='number'
              onInput={(val: any) => {
                if (val.target.value.length > 11) val.target.value = val.target.value.slice(0, 11);
              }}
            />
          </Form.Item>
          <Form.Item
            label='相关凭证'
            name='vouchers'
            labelCol={{ span: 5 }}
            wrapperCol={{ span: 15 }}
          >
            <Upload
              listType='picture-card'
              fileList={fileList}
              beforeUpload={beforeUpload}
              onPreview={() => {
                handlePreview(fileList[0].url || '');
              }}
              customRequest={handleUpload}
              onRemove={handleDelete}
            >
              {fileList.length >= 5 ? null : (
                <div>
                  <PlusOutlined />
                  <div style={{ marginTop: 8 }}>上传图片</div>
                </div>
              )}
            </Upload>
          </Form.Item>
          <Form.Item label='备注' name='remark' labelCol={{ span: 5 }} wrapperCol={{ span: 15 }}>
            <Input.TextArea placeholder='请输入备注' maxLength={50} allowClear />
          </Form.Item>
          <Form.Item
            label='操作人员密码'
            name='password'
            rules={[{ required: true, message: '请输入密码' }]}
            labelCol={{ span: 5 }}
            wrapperCol={{ span: 15 }}
          >
            <Input
              placeholder='请输入密码'
              maxLength={11}
              allowClear
              type='password'
              autoComplete='new-password'
            />
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};
