import { Drawer, Form, Input, DatePicker, Button, Space, message } from 'antd';
import { addCoupon, editCoupon, getCoupon } from '../api';
import { useEffect } from 'react';
import dayjs from 'dayjs';
const { RangePicker } = DatePicker;

export default function FormDrawer({ id, onComplete, ...rest }) {
  const [form] = Form.useForm();
  async function fetchInfo() {
    if (!id) return;
    const { data } = await getCoupon({ id });
    const time = [dayjs(data.start_time), dayjs(data.end_time)];
    form.setFieldsValue({ ...data, time });
  }
  useEffect(() => {
    fetchInfo();
  }, [id]);

  const title = id ? '编辑优惠券' : '添加优惠券';
  const onFinish = async (values) => {
    const { time, ...params } = values;
    if (time) {
      params.start_time = new Date(time[0]).getTime() / 1000;
      params.end_time = new Date(time[1]).getTime() / 1000;
    }
    const res = id ? await editCoupon({ ...params, id }) : await addCoupon(params);
    message.success(res.message);
    rest.onClose && rest.onClose();
    onComplete && onComplete();
  };
  const onClose = () => {
    form.resetFields();
    rest.onClose && rest.onClose();
  };

  return (
    <Drawer placement='right' title={title} {...rest} onClose={onClose}>
      <Form form={form} onFinish={onFinish} labelCol={{ span: 6 }} autoComplete='off'>
        <Form.Item
          name='name'
          label='优惠券名称'
          rules={[
            { required: true, message: '请输入优惠券名称' },
            { max: 30, message: '最大30字符' },
          ]}
        >
          <Input placeholder='请输入优惠券名称' />
        </Form.Item>
        <Form.Item
          name='norm_price'
          label='达标金额'
          rules={[
            { required: true, message: '请输入达标金额' },
            {
              validator: (_, value) => {
                return new Promise((resolve, reject) => {
                  if (!value || /^[1-9]\d*$/.test(value)) {
                    resolve();
                  } else {
                    reject(new Error('必须是正整数'));
                  }
                });
              },
            },
          ]}
        >
          <Input placeholder='请输入达标金额' />
        </Form.Item>

        <Form.Item
          name='reduced_price'
          label='满减金额'
          rules={[
            { required: true, message: '请输入满减金额' },
            {
              validator: (_, value) => {
                return new Promise((resolve, reject) => {
                  if (!value || /^[1-9]\d*$/.test(value)) {
                    resolve();
                  } else if (!(Number(value) <= Number(form.getFieldValue('norm_price')))) {
                    reject('小于等于达标金额');
                  }
                });
              },
            },
          ]}
        >
          <Input placeholder='请输入满减金额' />
        </Form.Item>
        <Form.Item name='time' label='有效期' rules={[{ required: true, message: '请选择有效期' }]}>
          <RangePicker></RangePicker>
        </Form.Item>
        <Form.Item style={{ textAlign: 'center' }}>
          <Space size={20}>
            <Button type='default' onClick={onClose}>
              取消
            </Button>
            <Button type='primary' htmlType='submit'>
              提交
            </Button>
          </Space>
        </Form.Item>
      </Form>
    </Drawer>
  );
}
