import { siteApi } from "@/api";
import { MemoSpinLoding } from "@/components";
import {
  DageUpload,
  DageUploadConsumer,
  DageUploadProvider,
  DageUploadType,
} from "@dage/pc-components";
import { App, Button, Form, FormInstance, Input } from "antd";
import { cloneDeep } from "lodash";
import { useEffect, useRef, useState } from "react";

export default function SitePage() {
  const initialData = useRef<any>(null);
  const { message } = App.useApp();
  const formRef = useRef<FormInstance>(null);
  const [loading, setLoading] = useState(false);
  const [readOnly, setReadOnly] = useState(true);

  useEffect(() => {
    getDetail();
  }, []);

  const getDetail = async () => {
    setLoading(true);
    try {
      const str = await siteApi.get();
      const { fileName, filePath, ...rest } = JSON.parse(str);
      if (fileName) {
        rest.audio = [
          {
            uid: fileName,
            url: `${process.env.REACT_APP_API_URL}${filePath}`,
            name: fileName,
            status: "done",
          },
        ];
      }
      formRef.current?.setFieldsValue(rest);
      initialData.current = cloneDeep(rest);
    } finally {
      setLoading(false);
    }
  };

  const save = async () => {
    if (!formRef.current || !(await formRef.current.validateFields())) return;

    try {
      setLoading(true);

      const { audio, ...rest } = formRef.current.getFieldsValue();

      if (Array.isArray(audio) && audio.length) {
        Object.assign(rest, {
          filePath: audio[0].response.filePath,
          fileName: audio[0].response.fileName,
        });
      }

      await siteApi.save(rest);

      message.success("保存成功");

      initialData.current = cloneDeep(formRef.current.getFieldsValue());
      setReadOnly(true);
    } finally {
      setLoading(false);
    }
  };

  const cancel = () => {
    formRef.current?.setFieldsValue({
      ...initialData.current,
    });
    setReadOnly(true);
  };

  return (
    <DageUploadProvider>
      <DageUploadConsumer>
        {(data) => (
          <Form
            ref={formRef}
            labelCol={{ flex: "80px" }}
            labelAlign="left"
            colon={false}
          >
            {loading && <MemoSpinLoding />}
            <Form.Item label="背景音乐：" name="audio">
              <DageUpload
                maxCount={1}
                disabled={readOnly}
                action="/api/cms/site/upload"
                dType={DageUploadType.AUDIO}
                maxSize={10}
                tips="仅支持MP3格式的音频文件，大小不得超过10MB"
              />
            </Form.Item>
            <Form.Item label="联系方式：" name="phone">
              <Input
                readOnly={readOnly}
                className="w220"
                placeholder="请输入内容"
              />
            </Form.Item>
            <Form.Item
              label="电子邮箱："
              name="email"
              rules={[{ type: "email" }]}
            >
              <Input
                readOnly={readOnly}
                className="w220"
                placeholder="请输入内容"
              />
            </Form.Item>
            <Form.Item label=" ">
              {readOnly ? (
                <Button onClick={() => setReadOnly(false)}>编辑</Button>
              ) : (
                <>
                  <Button style={{ marginRight: "15px" }} onClick={cancel}>
                    取消
                  </Button>
                  <Button
                    disabled={data?.uploading}
                    type="primary"
                    onClick={save}
                  >
                    保存
                  </Button>
                </>
              )}
            </Form.Item>
          </Form>
        )}
      </DageUploadConsumer>
    </DageUploadProvider>
  );
}
