import { history } from 'umi';
import { Input, Card, Form, Button, message, InputNumber } from 'antd';
import { useEffect, useState } from 'react';
import ProCard from '@ant-design/pro-card';
import { UploadImage } from '@/components/Upload';
import { addBanner, updateBanner } from '@/services/banner';

const goBack = () => {
  history.goBack();
};
const FormItem = Form.Item;
export default (props) => {
  const { data } = props.location;

  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [image, setImage] = useState();

  const formItemLayout = {
    //布局
    labelCol: { span: 6 },
    wrapperCol: { span: 14 },
  };

  const Submit = (values) => {
    setLoading(true);
    if (data) {
      updateBanner(data.bannerId, values)
        .then(() => {
          setLoading(false);
          message.success('数据更新成功');
          goBack();
        })
        .catch((err) => {
          setLoading(false);
          message.error(err.message || err);
        });
    } else {
      addBanner(values)
        .then((res) => {
          setLoading(false);
          message.success('数据保存成功');
          goBack();
        })
        .catch((err) => {
          setLoading(false);
          message.error(err.message || err);
        });
    }
  };
  useEffect(() => {
    if (data) {
      form.setFieldsValue(data);
    }
  }, [data]);
  return (
    <Card>
      <ProCard tabs={{ type: 'card' }} style={{ marginTop: '16px' }}>
        <ProCard.TabPane key={1} tab="轮播图编辑">
          <Form {...formItemLayout} onFinish={Submit} form={form}>
            <FormItem label="图片" name="image" rules={[{ required: true, message: '请选择' }]} tooltip='轮播图尺寸建议5:3这样小程序可以更好地显示'>
              <UploadImage value={image} onChange={setImage} />
            </FormItem>
            <FormItem label="排序" name="sortNo" rules={[{ required: true, message: '请输入' }]}>
              <InputNumber min={0} placeholder="请输入排序" style={{ width: '350px' }} />
            </FormItem>
            <FormItem label=" " colon={false}>
              <Button type="default" onClick={() => goBack()}>
                返回
              </Button>
              <Button
                type="primary"
                loading={loading}
                htmlType="Submit"
                style={{ marginLeft: '4em' }}
              >
                保存
              </Button>
            </FormItem>
          </Form>
        </ProCard.TabPane>
      </ProCard>
    </Card>
  );
};
