import {
  FC,
  ForwardedRef,
  forwardRef,
  useState,
  useImperativeHandle,
} from "react";
import {
  DatePicker,
  Form,
  Input,
  message,
  Modal,
  Radio,
  Select,
  Upload,
} from "antd";
import { PlusOutlined } from "@ant-design/icons";
import type { UploadFile } from "antd/es/upload/interface";
import dayjs from "dayjs";

import { RangePickerProps } from "antd/es/date-picker";
import { PropsType } from "~/common/interface/modal";
import { CommonAPI } from "~/api";
import { SplitCouponItemType } from "~/api/interface/couponManage";
import { addActivityItemType } from "~/api/interface/activityManage";
import {ActivityManageAPI} from "~/api/modules/activityManage";

interface selfProps {
  couponData: SplitCouponItemType[];
  activityTypeChangeEvent: (value: number) => void;
  ref: ForwardedRef<any>;
}

const AddOrEditModal: FC<PropsType & selfProps> = forwardRef(
  (
    {
      isModalVisible,
      handleOk,
      handleCancel,
      couponData,
      activityTypeChangeEvent,
      title,
    },
    ref
  ) => {
    const [createActivityForm] = Form.useForm<
      Exclude<
        addActivityItemType,
        {
          startTime: string;
          endTime: string;
          helpType: number;
          shareNum: number;
        }
      >
    >();
    const [activityId, setActivityId] = useState<number>(-1);
    const [currentActivityType, setCurrentActivityType] = useState<number>(1);
    // 文件
    const [fileList, setFileList] = useState<UploadFile[]>([]);
    const handleOkEvent = () => {
      createActivityForm.validateFields().then((value: any) => {
        const splitCouponItem = couponData.find(
          (v) => v.id === value.bindingCouponId
        );
        const startTime = `${dayjs(value.time[0]).format(
          "YYYY-MM-DD"
        )} 00:00:00`;
        const endTime = `${dayjs(value.time[1]).format("YYYY-MM-DD")} 23:59:59`;
        delete value.time;
        ActivityManageAPI[
          activityId === -1 ? "createActivity" : "editActivity"
        ]({
          id: activityId === -1 ? undefined : activityId,
          ...value,
          limitNum: Number(value.limitNum),
          helpType:
            splitCouponItem?.beSharedCoupon?.userTag ||
            splitCouponItem?.userTag,
          shareNum:
            currentActivityType === 1
              ? splitCouponItem?.peopleNumber
              : undefined,
          startTime,
          endTime,
        }).then(({ code }) => {
          if (code === "200") {
            message.success(activityId ? "编辑成功" : "新增成功");
            createActivityForm.resetFields();
            setFileList([]);
            handleOk();
          }
        });
      });
    };
    const handleCancelEvent = () => {
      handleCancel();
      createActivityForm.resetFields();
      setFileList([]);
    };
    // 上传
    const beforeUpload = (file: UploadFile) => {
      const reg = /\/(png|jpg|gif|jpeg|webp)$/;
      const isType = reg.test(file.type as string);
      if (!isType) {
        message.warning("文件格式错误");
      }
      return isType;
    };
    const customRequest = (value: any) => {
      const formData = new FormData();
      formData.append("uploadFile", value.file);
      CommonAPI.commonUpload(formData).then((res: any) => {
        if (res.code === "200") {
          setFileList([
            {
              uid: "uid",
              name: "image",
              url: res.result[0],
              status: "done",
            },
          ]);
          createActivityForm.setFieldValue("activityImg", res.result[0]);
        }
      });
    };
    const onRemove = (file: UploadFile) => {
      const list = fileList.filter((v: UploadFile) => v.uid !== file.uid);
      setFileList(list);
      setTimeout(() => {
        createActivityForm.setFieldValue("activityImg", undefined);
      });
    };
    // 活动类型改变
    const activityTypeChange = (e: any) => {
      createActivityForm.setFieldValue("bindingCouponId", undefined);
      setCurrentActivityType(e.target.value);
      activityTypeChangeEvent(e.target.value);
    };
    // 正则
    const negativeNumberValidator = (
      rule: any,
      value: string,
      callback: (error?: string) => void
    ) => {
      if (!value) {
        return Promise.reject(new Error(`请输入参与次数!`));
      }
      const reg = /^\+?[1-9][0-9]*$/;
      if (!reg.test(value)) {
        return Promise.reject(new Error(`参与次数为非零的正整数!`));
      }
      if (Number(value) > 5) {
        return Promise.reject(new Error("参与次数最大值为5!"));
      }
      // const bindingCouponId =
      //   createActivityForm.getFieldValue("bindingCouponId");
      // if (bindingCouponId) {
      //   const splitCouponObj = couponData.find(
      //     (v) => v.id === bindingCouponId
      //   );
      //   if (splitCouponObj && Number(value) > splitCouponObj.restrictedAccess) {
      //     return Promise.reject("参与次数不能大于关联优惠券每人限领张数");
      //   }
      // }
      return Promise.resolve();
    };
    // rangPicker disabledDate
    const disabledDate: RangePickerProps["disabledDate"] = (currentDate) => {
      // const bindingCouponId = createActivityForm.getFieldValue("bindingCouponId");
      // const couponObj = couponData.find((v) => v.id === bindingCouponId);
      // const activityType = createActivityForm.getFieldValue("activityType");
      // if (bindingCouponId) {
      //   switch (activityType) {
      //     case 1:
      //       return !(
      //         currentDate.isBefore(couponObj?.useEndTime) &&
      //         currentDate.isAfter(couponObj?.useStartTime)
      //       );
      //     case 2:
      //       return (
      //         couponObj?.isFixedTime === 0 &&
      //         !(
      //           currentDate.isBefore(couponObj?.useEndTime) &&
      //           currentDate.isAfter(couponObj?.useStartTime)
      //         )
      //       );
      //   }
      // }
      return currentDate < dayjs().subtract(1, "day");
    };
    useImperativeHandle(ref, () => ({
      getForm: () => createActivityForm,
      setFileList: (fileList: UploadFile[]) => {
        setFileList(fileList);
      },
      setId: (id: number) => {
        setActivityId(id);
      },
    }));
    return (
      <Modal
        open={isModalVisible}
        onOk={handleOkEvent}
        onCancel={handleCancelEvent}
        title={title}
      >
        <Form
          labelCol={{ span: 5 }}
          wrapperCol={{ span: 14 }}
          form={createActivityForm}
          initialValues={{ show: 1, activityType: 1 }}
        >
          <Form.Item
            label="活动标题"
            name="activityName"
            rules={[{ required: true, message: "请输入活动标题!" }]}
          >
            <Input placeholder="请输入活动标题" maxLength={25} />
          </Form.Item>
          <Form.Item label="活动类型" name="activityType">
            <Radio.Group onChange={activityTypeChange}>
              <Radio value={1}>裂变活动</Radio>
              <Radio value={2}>普通活动</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item label="活动中心展示" name="show">
            <Radio.Group>
              <Radio value={1}>是</Radio>
              <Radio value={0}>否</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item
            label="推广简图"
            name="activityImg"
            rules={[{ required: true, message: "请上传推广简图!" }]}
          >
            <Upload
              listType="picture-card"
              fileList={fileList}
              beforeUpload={beforeUpload}
              customRequest={customRequest}
              onRemove={onRemove}
              accept="image/*"
            >
              {fileList.length < 1 && <PlusOutlined />}
            </Upload>
          </Form.Item>
          <Form.Item label="关联优惠券" name="bindingCouponId">
            <Select
              placeholder="请选择关联优惠券"
              showSearch
              filterOption={(input, option: any) =>
                (option!.children as unknown as string)
                  .toLowerCase()
                  .includes(input.toLowerCase())
              }
            >
              {couponData.map((v) => (
                <Select.Option value={v.id} key={v.id}>
                  {v.couponName}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
          {currentActivityType === 1 && (
            <Form.Item
              label="参与次数"
              name="limitNum"
              rules={[{ required: true, validator: negativeNumberValidator }]}
            >
              <Input placeholder="请输入参与次数" suffix="次" />
            </Form.Item>
          )}

          <Form.Item
            label="生效时间"
            rules={[{ required: true, message: "请选择生效时间!" }]}
            name="time"
          >
            <DatePicker.RangePicker disabledDate={disabledDate} />
          </Form.Item>
        </Form>
      </Modal>
    );
  }
);
export default AddOrEditModal;
