import React, { useEffect, useState } from 'react';
import { DatePicker, Form, Input, message, Modal, Select, Space } from 'antd';
import { InterListType, InterReqType } from '~/api/interface';
import { insertBannerInfo, listBannerInfoPage } from '~/api/interface/commonType';
import { CommonAPI } from '~/api';
import { PlusOutlined } from '@ant-design/icons';
import { Uploader } from '~/components/uploader';
import RichText from '~/components/richText';
import dayjs from 'dayjs';

// 列表的类型
type TableType = InterListType<listBannerInfoPage>;
// 请求的表单类型
type ReqType = InterReqType<insertBannerInfo>;
// 传参类型
interface propType {
  title: string;
  open: boolean;
  closed: any;
  data?: TableType[0];
  moduleId: number;
}
// 详情类型
const bannerType = [
  { label: '无', value: 0 },
  { label: '海报', value: 1 },
  { label: '路由', value: 2 },
  { label: '路由(需要授权)', value: 9 },
  { label: '路由(跳转Tab栏)', value: 10 },
  { label: '小程序', value: 3 },
  // { label: '弹窗', value: 4 },
  { label: '纯文本', value: 5 },
  // { label: '服务SKU', value: 6 },
  // { label: '红包', value: 7 },
  { label: '链接', value: 8 },
  { label: '富文本', value: 11 },
  { label: '分享', value: 12 },
];

const AddEditModal: React.FC<propType> = (props) => {
  AddEditModal.defaultProps = {
    data: undefined,
  };
  // 参数
  const { title, open, closed, data, moduleId } = props;
  // 表单钩子
  const [form] = Form.useForm<ReqType>();
  // 上传图片
  const [bannerTypeValue, setBannerTypeValue] = useState(0);
  // 是否有效
  const [validTime, setValidTime] = useState<number>(0);
  // 关闭弹窗
  const handleCancel = () => {
    setBannerTypeValue(0);
    form.resetFields();
    closed();
  };
  // 确认事件
  const handleOk = () => {
    form
      .validateFields()
      .then(async (values) => {
        await handleSubmit(values as ReqType & { timeRange: string[] });
      })
      .catch((err) => {
        message
          .warning({
            content: err.errorFields[0].errors[0],
          })
          .then();
      });
  };
  // 提交事件
  const handleSubmit = async (values: ReqType & { timeRange: string[] }) => {
    const res = await CommonAPI[data?.id ? 'updateBannerInfo' : 'insertBannerInfo']({
      ...values,
      startTime: values.timeRange
        ? dayjs(values.timeRange[0]).format('YYYY-MM-DD HH:mm:ss')
        : undefined,
      endTime: values.timeRange
        ? dayjs(values.timeRange[1]).format('YYYY-MM-DD HH:mm:ss')
        : undefined,
      moduleId,
      id: data?.id,
    });
    if (res && res.code === '200') {
      message.success('操作成功');
      handleCancel();
    }
  };
  // componentDidMount
  useEffect(() => {
    if (!open) return;
    if (!data) return;
    form.setFieldsValue(data);
    setBannerTypeValue(data?.bannerType);
    if (data?.endTime && data?.startTime) {
      setValidTime(1);
      form.setFieldValue('validTime', 1);
      form.setFieldValue('timeRange', [dayjs(data?.startTime), dayjs(data?.endTime)]);
    }
    // console.log('data --->', data);
  }, [open]);
  return (
    <Modal open={open} title={title} onCancel={handleCancel} onOk={handleOk} destroyOnClose>
      <Form
        name='Form'
        form={form}
        labelAlign='right'
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 10 }}
      >
        <Form.Item
          label='名称'
          name='bannerName'
          rules={[{ required: true, message: '请输入名称' }]}
        >
          <Input placeholder={'请输入名称'} maxLength={20} allowClear />
        </Form.Item>
        <Form.Item label='状态' name='using' rules={[{ required: true, message: '请选择状态' }]}>
          <Select
            placeholder={'请选择状态'}
            options={[
              { label: '上架', value: 1 },
              { label: '下架', value: 0 },
            ]}
            allowClear
            onChange={(e) => {
              if (e === 1) {
                form.setFieldValue('timeRange', undefined);
              }
            }}
          />
        </Form.Item>
        <Form.Item label='有效时间' required wrapperCol={{ span: 18 }}>
          <Space.Compact>
            <Form.Item
              name={'validTime'}
              noStyle
              rules={[{ required: true, message: '请选择是否有效' }]}
              initialValue={0}
            >
              <Select
                placeholder='请选择是否有效'
                options={[
                  { label: '永久有效', value: 0 },
                  { label: '有效期限', value: 1 },
                ]}
                style={{ width: '30%' }}
                value={validTime}
                onChange={(e) => {
                  setValidTime(e);
                  if (e === 0) {
                    form.setFieldValue('timeRange', undefined);
                  }
                }}
              />
            </Form.Item>
            <Form.Item
              name={'timeRange'}
              noStyle
              rules={[{ required: validTime === 1, message: '请选择有效期限' }]}
            >
              <DatePicker.RangePicker
                showTime={{ format: 'HH:mm:ss' }}
                format='YYYY-MM-DD HH:mm:ss'
                disabled={validTime === 0}
              />
            </Form.Item>
          </Space.Compact>
        </Form.Item>
        <Form.Item
          label='封面图'
          name='bannerImg'
          rules={[{ required: true, message: '请上传封面图' }]}
        >
          <Uploader
            listType={'picture-card'}
            fileUpload
            fileLength={1}
            fileSize={10}
            fileType={['image/png', 'image/jpeg', 'image/jpg', 'image/gif', 'image/bmp']}
            onChange={(e) => form.setFieldValue('bannerImg', e[0].url)}
            defaultFileList={data?.bannerImg ? [{ url: data?.bannerImg }] : []}
          >
            <PlusOutlined />
          </Uploader>
        </Form.Item>
        <Form.Item
          label='详情类型'
          name='bannerType'
          rules={[{ required: true, message: '请选择详情类型' }]}
          // initialValue={0}
        >
          <Select
            placeholder={'请选择详情类型'}
            options={bannerType}
            allowClear
            onChange={setBannerTypeValue}
            value={bannerTypeValue}
          />
        </Form.Item>
        {[2, 9, 10].includes(bannerTypeValue) && (
          <Form.Item
            label='路由地址'
            name='bannerUrl'
            rules={[{ required: true, message: '请输入路由地址' }]}
          >
            <Input placeholder={'请输入路由地址'} maxLength={100} allowClear />
          </Form.Item>
        )}
        {[3].includes(bannerTypeValue) && (
          <Form.Item
            label='小程序appid'
            name='bannerUrl'
            rules={[{ required: true, message: '请输入小程序appid' }]}
          >
            <Input placeholder={'请输入小程序appid'} maxLength={100} allowClear />
          </Form.Item>
        )}
        {[5].includes(bannerTypeValue) && (
          <Form.Item
            label='纯文本'
            name='bannerUrl'
            rules={[{ required: true, message: '请输入纯文本' }]}
          >
            <Input placeholder={'请输入纯文本'} maxLength={100} allowClear />
          </Form.Item>
        )}
        {[11].includes(bannerTypeValue) && (
          <Form.Item
            label='富文本'
            name='textContent'
            rules={[{ required: true, message: '请输入富文本' }]}
            wrapperCol={{ span: 20 }}
          >
            <RichText
              // eslint-disable-next-line @typescript-eslint/ban-ts-comment
              // @ts-ignore
              value={form.getFieldValue('textContent')}
              onChange={(e) => form.setFieldValue('textContent', e)}
              height={250}
            />
          </Form.Item>
        )}
        {[1].includes(bannerTypeValue) && (
          <Form.Item
            label='详情海报'
            name='bannerPoster'
            rules={[{ required: true, message: '请上传详情海报' }]}
          >
            <Uploader
              listType={'picture-card'}
              fileUpload
              fileLength={1}
              fileSize={10}
              fileType={['image/png', 'image/jpeg', 'image/jpg', 'image/gif', 'image/bmp']}
              onChange={(e) => form.setFieldValue('bannerPoster', e[0].url)}
              defaultFileList={data?.bannerPoster ? [{ url: data?.bannerPoster }] : []}
            >
              <PlusOutlined />
            </Uploader>
          </Form.Item>
        )}
        {[8].includes(bannerTypeValue) && (
          <Form.Item
            label='链接地址'
            name='bannerUrl'
            rules={[
              { required: true, message: '请输入链接地址' },
              { pattern: /^[^\s]*$/, message: '地址不能包含空格' },
            ]}
          >
            <Input placeholder={'请输入链接地址'} maxLength={100} allowClear />
          </Form.Item>
        )}
      </Form>
    </Modal>
  );
};

export default AddEditModal;
