import {
  Checkbox,
  CheckboxProps,
  Form,
  Input,
  Modal,
  ModalProps,
  Radio,
} from "antd";
import { FC, useEffect, useMemo } from "react";
import style from "./index.module.scss";
import {
  DageUpload,
  DageUploadConsumer,
  DageUploadProvider,
  DageUploadType,
} from "@dage/pc-components";
import { FILE_TYPE_ENUM } from "./constants";
import { IFileTemplateForm, IFileTemplateFormParams } from "@/types";
import { saveAssEntityApi } from "@/api";
import { getBaseURL } from "@dage/service";

export interface FileTemplateModalProps extends ModalProps {
  item?: IFileTemplateFormParams | null;
  module?: "norm" | "assess";
  onCancel?: () => void;
  onOk?: (val: any, isEdit?: boolean) => void;
}

export const FileTemplateModal: FC<FileTemplateModalProps> = ({
  item,
  open,
  module,
  onOk,
  onCancel,
  ...rest
}) => {
  const [form] = Form.useForm<IFileTemplateForm>();
  const typesVal = Form.useWatch("suffix", form);
  const baseUrl = getBaseURL();

  const checkAll = useMemo(
    () => FILE_TYPE_ENUM.length === typesVal?.length,
    [typesVal]
  );
  const indeterminate = useMemo(
    () =>
      (typesVal?.length || 0) > 0 &&
      (typesVal?.length || 0) < FILE_TYPE_ENUM.length,
    [typesVal]
  );

  const handleCancel = () => {
    form.resetFields();
    onCancel?.();
  };

  const handleConfirm = () => {
    form.submit();
  };

  const handleSubmit = async (values: IFileTemplateForm) => {
    const { file, suffix, ...rest } = values;

    const data = await saveAssEntityApi({
      ...rest,
      level: 1,
      module: module as "norm" | "assess",
      fileName: file?.[0].response?.fileName,
      filePath: file?.[0].response?.filePath,
      suffix: suffix?.join(","),
    });

    onOk?.(data, Boolean(item));
    handleCancel();
  };

  const onCheckAllChange: CheckboxProps["onChange"] = (e) => {
    form.setFieldValue("suffix", e.target.checked ? [...FILE_TYPE_ENUM] : []);
  };

  useEffect(() => {
    if (!item) {
      form.resetFields();
      return;
    }

    const { suffix, fileName, filePath, ...rest } = item;
    form.setFieldsValue({
      ...rest,
      file: fileName
        ? [
            {
              name: fileName,
              url: baseUrl + process.env.REACT_APP_IMG_PUBLIC + filePath,
              response: {
                fileName,
                filePath,
              },
            },
          ]
        : undefined,
      suffix: suffix?.split(","),
    });
  }, [item, form]);

  return (
    <DageUploadProvider>
      <DageUploadConsumer>
        {(consumer) => (
          <Modal
            title="上传资料"
            okText="提交"
            cancelText="取消"
            open={open}
            width={640}
            okButtonProps={{
              disabled: consumer?.uploading,
            }}
            onOk={handleConfirm}
            onCancel={handleCancel}
            className={style.modal}
            {...rest}
          >
            <Form
              labelCol={{ span: 4, offset: 1 }}
              form={form}
              onFinish={handleSubmit}
            >
              <Form.Item
                label="资料名称"
                rules={[{ required: true }]}
                name="name"
              >
                <Input
                  placeholder="请输入内容，最多20字"
                  showCount
                  autoComplete="off"
                  maxLength={20}
                />
              </Form.Item>
              <Form.Item
                label="填报指标时必须上传"
                name="isUpload"
                initialValue={0}
              >
                <Radio.Group
                  size="large"
                  options={[
                    {
                      label: "是",
                      value: 1,
                    },
                    {
                      label: "否",
                      value: 0,
                    },
                  ]}
                  optionType="button"
                  buttonStyle="solid"
                />
              </Form.Item>
              <Form.Item
                label="资料模板"
                name="file"
                rules={[{ required: true }]}
              >
                <DageUpload
                  action="/api/cms/norm/file/upload"
                  dType={DageUploadType.DOC}
                  maxCount={1}
                  tips="最多1个附件"
                />
              </Form.Item>
              <Form.Item label="资料格式">
                <Checkbox
                  checked={checkAll}
                  indeterminate={indeterminate}
                  onChange={onCheckAllChange}
                >
                  全部
                </Checkbox>

                <Form.Item name="suffix" noStyle>
                  <Checkbox.Group options={FILE_TYPE_ENUM} />
                </Form.Item>
              </Form.Item>
            </Form>
          </Modal>
        )}
      </DageUploadConsumer>
    </DageUploadProvider>
  );
};
