import { PlusOutlined } from "@ant-design/icons";
import {
  DrawerForm,
  ProForm,
  ProFormSelect,
  ProFormText,
  ProFormUploadButton,
  ProFormTextArea,
  ProFormMoney,
} from "@ant-design/pro-components";
import { Button, Space, message } from "antd";
import type { FormInstance } from "@ant-design/pro-components";
import { useEffect, useState, useMemo, useRef } from "react";
import Editor from "@/components/Editor";
import { customUploadRequest } from "@/utils";
import { SaveOrUpdateTemplate, GetTemplateDetail } from "@/api/templateStore";
import {
  APPLICATION_SCENARIOS_OPTIONS,
  INDUSTRIE_OPTIONS,
  MODULE_TEMPLATE_TYPE,
} from "@/constants";
import { useRequest } from "umi";

export default ({
  onSuccess,
  editData,
  onClose,
}: {
  onSuccess: () => void;
  onClose: () => void;
  editData?: any;
}) => {
  const [drawerVisit, setDrawerVisit] = useState(false);
  const [html, setHtml] = useState("");
  const formRef = useRef<FormInstance>();

  const { run } = useRequest(GetTemplateDetail, {
    manual: true,
    onSuccess: (res) => {
      setHtml(res?.result?.detail || "");
    },
  });

  useEffect(() => {
    setDrawerVisit(!!editData);
    if(editData?.id) {
      run({
        id: editData.id,
      });
    }
  }, [editData]);

  useEffect(() => {
    if (!drawerVisit) {
      onClose();
      setHtml("");
      formRef.current?.resetFields();
    }
  }, [drawerVisit]);

  const initialValues = useMemo(() => {
    if (editData) {
      return {
        ...editData,
        industries: editData.industries ? JSON.parse(editData.industries) : [],
        applicationScenarios: editData.applicationScenarios ? JSON.parse(editData.applicationScenarios) : [],
        icon: editData.icon
          ? [
              {
                uid: editData.icon,
                name: editData.icon,
                status: "done",
                url: `/api/File/Download?fileId=${editData.icon}`,
              },
            ]
          : [],
      };
    }
    return {};
  }, [editData]);

  return (
    <>
      <Space>
        <Button
          type="primary"
          onClick={() => {
            setDrawerVisit(true);
          }}
        >
          <PlusOutlined />
          新增模版
        </Button>
      </Space>

      <DrawerForm
        onOpenChange={setDrawerVisit}
        title="新增模版"
        open={drawerVisit}
        initialValues={initialValues}
        onFinish={async (values: any) => {
          await SaveOrUpdateTemplate({
            ...values,
            id: editData?.id,
            version: editData?.version,
            icon: values?.icon?.[0]?.response.id || values?.icon?.[0].uid || "",
            tags: values.tags?.replaceAll("，", ","),
            detail: html,
            isFree: !editData?.price,
          });
          onSuccess();
          message.success("提交成功");
          return true;
        }}
        drawerProps={{
          maskClosable: false,
          destroyOnClose: true,
        }}
        formRef={formRef}
        size="small"
      >
        <ProForm.Group title="基础信息">
          <ProFormSelect
            width="md"
            name="applicationId"
            label="所属应用"
            placeholder="请选择"
          />

          <ProFormSelect
            width="md"
            name="type"
            label="模版分类"
            placeholder="请选择"
            options={MODULE_TEMPLATE_TYPE}
          />

          <ProFormSelect
            width="md"
            name="moduleId"
            label="选择模版"
            placeholder="请选择"
          />

          <ProFormText
            width="md"
            name="name"
            label="模版名称"
            tooltip="最长为 30 位"
            placeholder="请输入名称"
            rules={[
              { required: true, message: "请输入名称" },
              { max: 30, message: "名称不能超过30个字符" },
            ]}
          />

          <ProFormUploadButton
            max={1}
            fieldProps={{
              multiple: false,
              name: "file",
              listType: "picture-card",
              accept: "image/*",
              customRequest: customUploadRequest,
            }}
            name="icon"
            label="图标"
            rules={[{ required: true, message: "请上传应用图标" }]}
          />
        </ProForm.Group>
        <ProFormTextArea
          name="desc"
          label="模版简介"
          placeholder="请输入简介，1000字以内"
        />
        <ProForm.Group>
          <ProFormSelect
            width="md"
            name="industries"
            label="所属行业"
            placeholder="请选择"
            mode="multiple"
            options={INDUSTRIE_OPTIONS}
          />
          <ProFormSelect
            width="md"
            name="applicationScenarios"
            label="应用场景"
            placeholder="请选择"
            mode="multiple"
            options={APPLICATION_SCENARIOS_OPTIONS}
          />
          <ProFormText
            width="md"
            name="tags"
            label="标签"
            placeholder="多个标签用逗号分隔"
          />
          <ProFormMoney
            width="md"
            name="price"
            label="定价"
            defaultValue={0}
            min={0}
            placeholder="请输入"
            locale="zh-CN"
          />
        </ProForm.Group>
        <ProForm.Group title="详情信息">
          <Editor html={html} onChange={setHtml} />
        </ProForm.Group>
      </DrawerForm>
    </>
  );
};
