import {
  Checkbox,
  CheckboxProps,
  Form,
  Input,
  Modal,
  ModalProps,
  Radio,
} from "antd";
import { FC, useEffect, useMemo, useState } from "react";
import style from "./index.module.scss";
import {
  DageFileResponseType,
  DageUpload,
  DageUploadConsumer,
  DageUploadProvider,
  DageUploadType,
} from "@dage/pc-components";
import { uniqueId } from "lodash";
import { FILE_TYPE_ENUM } from "./constants";

export interface FileTemplateForm {
  id: string;
  name: string;
  required: number;
  file?: DageFileResponseType[];
  types?: string[];
}

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

export const FileTemplateModal: FC<FileTemplateModalProps> = ({
  item,
  open,
  onOk,
  onCancel,
  ...rest
}) => {
  const [form] = Form.useForm<FileTemplateForm>();
  const [fields, setFields] = useState<any[]>([
    {
      name: "required",
      value: 0,
    },
  ]);
  const typesVal = Form.useWatch("types", form);

  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: FileTemplateForm) => {
    onOk?.(
      {
        // @ts-ignore
        id: item?.id || uniqueId("template"),
        ...values,
      },
      Boolean(item)
    );
    handleCancel();
  };

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

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

    form.setFieldsValue(item);
  }, [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
              fields={fields}
              labelCol={{ span: 4, offset: 1 }}
              form={form}
              onFieldsChange={(_, newFields) => {
                setFields(newFields);
              }}
              onFinish={handleSubmit}
            >
              <Form.Item
                label="资料名称"
                rules={[{ required: true }]}
                name="name"
              >
                <Input
                  placeholder="请输入内容，最多20字"
                  showCount
                  autoComplete="off"
                  maxLength={20}
                />
              </Form.Item>
              <Form.Item label="填报指标时必须上传" name="required">
                <Radio.Group
                  size="large"
                  options={[
                    {
                      label: "是",
                      value: 1,
                    },
                    {
                      label: "否",
                      value: 0,
                    },
                  ]}
                  optionType="button"
                  buttonStyle="solid"
                />
              </Form.Item>
              <Form.Item label="资料模板" name="file">
                <DageUpload
                  action="/api/cms/goods/upload"
                  dType={DageUploadType.DOC}
                  maxCount={1}
                  tips="最多1个附件"
                />
              </Form.Item>
              <Form.Item label="资料格式">
                <Checkbox
                  checked={checkAll}
                  indeterminate={indeterminate}
                  onChange={onCheckAllChange}
                >
                  全部
                </Checkbox>

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