import React, { useState } from 'react';
import { DatePicker, Form, Input, message, Modal, Radio } from 'antd';
import moment from 'dayjs';
import { PointManageAPI } from '@/api';
import { maxLength8, maxString8 } from '@/utils/validateUtils';

// 传参类型
interface propType {
  title: string;
  open: boolean;
  closed: any;
  data?: any;
}

export const AddEditModal: React.FC<propType> = (props: propType) => {
  // 组件默认值
  AddEditModal.defaultProps = {
    data: null,
  };
  // 参数
  const { title, open, closed, data } = props;
  // 表单钩子
  const [form] = Form.useForm();
  // 生效时间单选
  const [radioValue, setRadioValue] = useState(0);
  // 关闭弹窗
  const handleCancel = () => {
    form.resetFields();
    setRadioValue(0);
    closed();
  };
  // 提交弹窗
  const handleOk = () => {
    form
      .validateFields()
      .then(async (values) => {
        await handleSubmit(values);
      })
      .catch((err) => {
        message
          .warning({
            content: err.errorFields[0].errors[0],
          })
          .then();
      });
  };
  // 提交数据
  const handleSubmit = async (values: any) => {
    const res = await PointManageAPI.AddConvertRule({
      coupon: Number(values.coupon),
      entryIntoForceTime:
        values.ruleSetting === 1
          ? moment(values.entryIntoForceTime.$d).format('YYYY-MM-DD HH:mm:ss')
          : undefined,
      ruleName: values.ruleName,
      score: Number(values.score),
    });
    if (res && res.code === '200') {
      handleCancel();
    }
  };
  return (
    <Modal open={open} title={title} onCancel={handleCancel} onOk={handleOk} destroyOnClose>
      <Form
        name='addForm'
        form={form}
        labelAlign='right'
        // layout="inline"
      >
        <Form.Item
          label='规则名称'
          name='ruleName'
          rules={[{ required: true, message: '请输入规则名称' }]}
        >
          <Input placeholder='请输入规则名称' maxLength={15} allowClear />
        </Form.Item>
        <Form.Item label='兑换比例（积分：券额）' required>
          <Form.Item
            name='score'
            rules={[{ required: true, message: '请输入积分比例' }]}
            style={{ display: 'inline-block', width: 'calc(50% - 8px)' }}
          >
            <Input placeholder='请输入积分比例' type='number' onInput={maxLength8} />
          </Form.Item>
          <Form.Item
            name='coupon'
            rules={[
              { required: true, message: '请输入券额比例' },
              {
                pattern: /^(\d|[1-9]\d+)(\.\d{1,2})?$/,
                message: '只能输入两位小数',
              },
            ]}
            style={{
              display: 'inline-block',
              width: 'calc(50% - 8px)',
              margin: '0 8px',
            }}
          >
            <Input placeholder='请输入券额比例' type='number' onInput={maxString8} />
          </Form.Item>
        </Form.Item>
        <div style={{ transform: 'translateY(-10px)' }}>
          说明：若兑换比例为1：20，则1积分可兑20元VIP优惠券，且为无门槛优惠券
        </div>
        <Form.Item
          label='生效时间'
          name='ruleSetting'
          rules={[{ required: true, message: '请选择生效时间' }]}
          initialValue={0}
        >
          <Radio.Group
            options={[
              { label: '立即生效', value: 0 },
              { label: '手动设置', value: 1 },
            ]}
            value={radioValue}
            onChange={({ target: { value } }) => {
              setRadioValue(value);
            }}
          />
        </Form.Item>
        {radioValue === 1 && (
          <Form.Item
            label='生效时间'
            name='entryIntoForceTime'
            rules={[{ required: radioValue === 1, message: '请设置生效时间' }]}
          >
            <DatePicker
              placeholder='请选择生效时间'
              allowClear
              showTime={{ format: 'HH:mm:ss' }}
              format='YYYY-MM-DD HH:mm:ss'
              style={{ width: '100%' }}
              disabledDate={(current) => {
                // 限制时间不可早于当日
                return current && current <= moment();
              }}
            />
          </Form.Item>
        )}
      </Form>
    </Modal>
  );
};
