import { DatePicker, Form, FormInstance, Input } from "antd";
import dayjs from "dayjs";
import { RangePickerProps } from "antd/es/date-picker";
import {
  DageMap,
  DageUpload,
  DageMapEvent,
  DageMapMethods,
  DageUploadProvider,
  DageUploadConsumer,
} from "@dage/web-components";
import { MemoSpinLoding, FormPageFooter } from "@/components";
import { useCallback, useEffect, useRef, useState } from "react";
import { useLocation, useNavigate, useParams } from "react-router-dom";
import { overviewApi } from "@/api";
import { formatDate } from "@/utils/date";

const disabledDate: RangePickerProps["disabledDate"] = (current) => {
  return current && current > dayjs().endOf("day");
};

export default function OverviewCreateOrEdit() {
  const navigate = useNavigate();
  const params = useParams();
  const location = useLocation();
  const formRef = useRef<FormInstance>(null);
  const dageMapRef = useRef<DageMapMethods>(null);
  const readonly = useRef(location.pathname.split("/")[2].indexOf("view") > -1);
  const [loading, setLoading] = useState(false);

  const [position, setPosition] = useState([121.473581, 31.230536]);
  const [address, setAddress] = useState("上海市人民政府");

  const getDetail = useCallback(async () => {
    setLoading(true);
    try {
      const {
        data: {
          entity: { createDay, longitude, latitude, address, ...rest },
          file,
        },
      } = await overviewApi.getDetail(params.id as string);
      formRef.current?.setFieldsValue({
        ...rest,
        address,
        createDay: dayjs(createDay),
        fileIds: file.map((i) => ({
          uid: i.id + "",
          url: `${process.env.REACT_APP_BACKEND_URL}${i.filePath}`,
          name: i.fileName,
        })),
      });
      setPosition([longitude, latitude]);
      setAddress(address);

      dageMapRef.current?.mapRef?.setCenter([longitude, latitude]);
    } finally {
      setLoading(false);
    }
  }, [params.id]);

  const handleCancel = useCallback(() => {
    navigate(-1);
  }, [navigate]);

  const handleSubmit = useCallback(async () => {
    if (!(await formRef.current?.validateFields())) return;

    const { createDay, fileIds, ...rest } = formRef.current?.getFieldsValue();

    if (params.id) {
      rest.id = params.id;
    }

    await overviewApi.save({
      ...rest,
      createDay: formatDate(createDay),
      latitude: position[1],
      longitude: position[0],
      address,
      fileIds: fileIds
        .map((i: any) => (!!i.response ? i.response.id : i.uid))
        .join(),
    });

    handleCancel();
  }, [handleCancel, params.id, position, address]);

  const handleMapChange = useCallback((data: DageMapEvent) => {
    if (data.lng && data.lat) {
      setPosition([data.lng, data.lat]);
    }
    setAddress(data.address || "");
  }, []);

  useEffect(() => {
    !!params.id && getDetail();
  }, [getDetail, params.id]);

  return (
    <div className="overview-edit">
      {loading && <MemoSpinLoding />}
      <DageUploadProvider>
        <DageUploadConsumer>
          {(data) => {
            return (
              <>
                <Form
                  ref={formRef}
                  initialValues={{ address }}
                  labelCol={{ span: 3 }}
                >
                  <Form.Item
                    label="企业名称"
                    name="name"
                    rules={[{ required: true, message: "请输入" }]}
                  >
                    <Input
                      readOnly={readonly.current}
                      className="w450"
                      placeholder="请输入内容"
                      maxLength={30}
                      showCount
                    />
                  </Form.Item>
                  <Form.Item label="简介" name="description">
                    <Input.TextArea
                      readOnly={readonly.current}
                      className="w450"
                      placeholder="请输入内容"
                      maxLength={200}
                      showCount
                    />
                  </Form.Item>
                  <Form.Item label="图片" name="fileIds">
                    <DageUpload
                      disabled={readonly.current}
                      tips="支持png、jpg和jpeg格式；最多9张，最大5M"
                      action={
                        process.env.REACT_APP_BACKEND_URL +
                        "/api/cms/history/upload"
                      }
                    />
                  </Form.Item>
                  <Form.Item label="企业类型" name="type">
                    <Input
                      readOnly={readonly.current}
                      className="w450"
                      placeholder="请输入内容"
                      maxLength={30}
                      showCount
                    />
                  </Form.Item>
                  <Form.Item
                    label="成立日期"
                    name="createDay"
                    rules={[{ required: true, message: "请选择" }]}
                  >
                    <DatePicker
                      disabled={readonly.current}
                      className="w450"
                      format="YYYY-MM-DD"
                      disabledDate={disabledDate}
                    />
                  </Form.Item>
                  <Form.Item
                    label="地址"
                    name="address"
                    rules={[{ required: true, message: "请选择" }]}
                  >
                    <DageMap
                      disabled={readonly.current}
                      ref={dageMapRef}
                      longitude={position[0]}
                      latitude={position[1]}
                      address={address}
                      city={310000}
                      inputTipsApi="/api/cms/goods/mapSearch/"
                      onChange={handleMapChange}
                    />
                  </Form.Item>
                </Form>

                <FormPageFooter
                  showSubmit={!readonly.current}
                  disabled={data?.uploading}
                  onSubmit={handleSubmit}
                  onCancel={handleCancel}
                />
              </>
            );
          }}
        </DageUploadConsumer>
      </DageUploadProvider>
    </div>
  );
}
