import { dateFormat, gendUrl, throttle } from "@/util";
import * as URL from "./URL";
import {
  basePath,
  errorHook,
  gHeaders,
  gParams,
  gPaths,
  lifeHook,
  Param,
} from "./state";
import { ElMessage } from "element-plus";
import {
  Relics,
  Scene,
  ScenePoint,
  ResPage,
  UserInfo,
  Device,
  // PolygonsAttrib,
} from "./type";

const error = throttle((msg: string) => ElMessage.error(msg), 2000);

type Other = { params?: Param; paths?: Param, useResult?: boolean };
export const sendFetch = <T>(
  url: string,
  init: RequestInit,
  other?: Other
): Promise<T> => {
  const headers = init.headers as Record<string, string>;
  let sendUrl = url;

  if (other) {
    if (other.paths) {
      sendUrl = gendUrl(url, { ...gPaths, ...other.paths });
    }

    if (other.params) {
      sendUrl =
        sendUrl + "?" + new URLSearchParams({ ...gParams, ...other.params });
    }
  }
  lifeHook.forEach(({ start }) => start());

  return fetch(basePath + sendUrl, {
    ...init,
    headers: headers
      ? {
        ...headers,
        ...gHeaders,
      }
      : gHeaders,
  })
    .then((res) => {
      lifeHook.forEach(({ end }) => end());
      if (res.status === 200) {
        return res.json();
      } else {
        ElMessage.error("请求错误");
        throw "请求错误";
      }
    })
    .then((data) => {
      if (data.code !== 0) {
        error(data.message);
        errorHook.map((err) => {
          err(data.code, data.msg);
        });
        throw data.message;
      } else {
        if (other && other.useResult) {
          return data
        } else {
          return data.data;
        }

      }
    });
};

export type LoginProps = {
  password: string;
  phoneNum: string;
};
export const loginFetch = (props: LoginProps) =>
  sendFetch<{ user: UserInfo; token: string }>(URL.login, {
    method: "post",
    body: JSON.stringify(props),
  });

export const userInfoFetch = () =>
  sendFetch<UserInfo>(URL.getUserInfo, { method: "post" });

export type PageProps<T> = {
  pageNum: number;
  pageSize: number;
} & T;

export type RelicsPageProps = PageProps<{
  name?: string;
  category?: number;
  level?: number;
}>;
export const relicsPageFetch = (body: RelicsPageProps) =>
  sendFetch<ResPage<Relics>>(URL.getRelicsPage, {
    method: "post",
    body: JSON.stringify(body),
  });

export const relicsInfoFetch = (relicsId: number) =>
  sendFetch<Relics>(
    URL.getRelicsInfo,
    {
      method: "post",
      body: JSON.stringify({}),
    },
    { paths: { relicsId } }
  );

export const relicsSelfCheckFetch = (relicsId: number) =>
  sendFetch<Relics>(
    URL.relicsSelfCheck,
    {
      method: "post",
      body: JSON.stringify({}),
    },
    { paths: { relicsId } }
  );

export const addRelicsFetch = (relics: Relics) => {
  return sendFetch(URL.addRelics, {
    method: "post",
    body: JSON.stringify({ ...relics, relicsId: null }),
  });
};

export const delRelicsFetch = (relicsId: number) =>
  sendFetch(URL.delRelics, {
    method: "post",
    body: JSON.stringify({ relicsId }),
  });

export const updateRelicsFetch = (relics: Relics) =>
  sendFetch(URL.updateRelicsName, {
    method: "post",
    body: JSON.stringify(relics),
  });

export const relicsScenesFetch = async (relicsId: number) => {
  const scenes = await sendFetch<Scene[]>(
    URL.getRelicsScenes,
    { method: "post", body: JSON.stringify({}) },
    { paths: { relicsId } }
  );

  scenes.forEach((scene) => {
    scene.sceneId = scene.id;
  });
  return scenes;
};
export const addRelicsScenesFetch = (
  relicsId: number,
  scenes: Pick<Scene, "sceneCode" | "id">[]
) =>
  sendFetch(
    URL.addRelicsScene,
    { method: "post", body: JSON.stringify(scenes) },
    { paths: { relicsId } }
  );
export const delRelicsScenesFetch = (
  relicsId: number,
  scenes: Pick<Scene, "sceneCode" | "id">[]
) =>
  sendFetch(
    URL.delRelicsScene,
    { method: "post", body: JSON.stringify(scenes) },
    { paths: { relicsId } }
  );
export const updateRelicsScenePosNameFetch = (posId: number, name: string) =>
  sendFetch(URL.updateRelicsScenePosName, {
    method: "post",
    body: JSON.stringify({ id: posId, name }),
  });

export const relicsScenePosInfoFetch = (posId: number) =>
  sendFetch<ScenePoint>(
    URL.getRelicsScenePosInfo,
    {
      method: "post",
      body: JSON.stringify({}),
    },
    { paths: { posId } }
  );

// export const relicsPolyginsFetch = () => {
//   return new Promise<PolygonsAttrib>((resolve) => {
//     setTimeout(() => {
//       resolve({
//         lines: [
//           {
//             id: "1",
//             pointIds: ["2666", "2667"],
//           },
//           {
//             id: "2",
//             pointIds: ["2667", "2669"],
//           },
//           {
//             id: "3",
//             pointIds: ["2669", "2674"],
//           },
//           {
//             id: "4",
//             pointIds: ["2674", "2675"],
//           },
//           {
//             id: "5",
//             pointIds: ["2675", "2676"],
//           },
//           {
//             id: "6",
//             pointIds: ["2676", "2673"],
//           },
//           {
//             id: "7",
//             pointIds: ["2673", "2672"],
//           },
//           {
//             id: "8",
//             pointIds: ["2672", "2670"],
//           },
//           {
//             id: "9",
//             pointIds: ["2677", "2678"],
//           },
//           {
//             id: "10",
//             pointIds: ["2678", "2679"],
//           },
//           {
//             id: "11",
//             pointIds: ["2679", "2680"],
//           },
//           {
//             id: "12",
//             pointIds: ["2680", "2681"],
//           },
//         ],
//         polygons: [
//           {
//             id: "1",
//             lineIds: ["1", "2", "3", "4", "5", "6", "7", "8"],
//           },
//           {
//             id: "2",
//             lineIds: ["9", "10", "11", "12"],
//           },
//         ],
//         points: [
//           {
//             rtk: false,
//             x: 115.949835199646,
//             y: 30.0971239995873,
//             id: "2666",
//           },
//           {
//             rtk: false,
//             x: 115.949706558269,
//             y: 30.0975243383135,
//             id: "2667",
//           },
//           {
//             rtk: false,
//             x: 115.950002555619,
//             y: 30.0977552558535,
//             id: "2668",
//           },
//           {
//             rtk: false,
//             x: 115.949968744193,
//             y: 30.097862045865,
//             id: "2669",
//           },
//           {
//             rtk: true,
//             x: 115.950063977564,
//             y: 30.0978879318173,
//             id: "2670",
//           },
//           {
//             rtk: true,
//             x: 115.949964417593,
//             y: 30.0978650571868,
//             id: "2671",
//           },
//           {
//             rtk: true,
//             x: 115.950300839723,
//             y: 30.0976756336231,
//             id: "2672",
//           },
//           {
//             rtk: true,
//             x: 115.950437426448,
//             y: 30.097269657442,
//             id: "2673",
//           },
//           {
//             rtk: false,
//             x: 115.95025353664198,
//             y: 30.097554052476422,
//             id: "2674",
//           },
//           {
//             rtk: false,
//             x: 115.95021286828855,
//             y: 30.09733715459145,
//             id: "2675",
//           },
//           {
//             rtk: false,
//             x: 115.95031589478391,
//             y: 30.097000962869746,
//             id: "2676",
//           },
//           {
//             rtk: false,
//             x: 115.95100324233627,
//             y: 30.09844929254667,
//             id: "2677",
//           },
//           {
//             rtk: false,
//             x: 115.95233898242569,
//             y: 30.098492207890907,
//             id: "2678",
//           },
//           {
//             rtk: false,
//             x: 115.95227997382736,
//             y: 30.097059908276954,
//             id: "2679",
//           },
//           {
//             rtk: false,
//             x: 115.95076720794296,
//             y: 30.0971403745474,
//             id: "2680",
//           },
//           {
//             rtk: false,
//             x: 115.95056336005783,
//             y: 30.098095240956702,
//             id: "2681",
//           },
//         ],
//       });
//     }, 500);
//   });
// };

export type ScenePageProps = PageProps<{
  sceneCode?: string;
  sceneName?: string;
  title?: string;
  cameraType?: number;
  algorithmTime?: [Date, Date];
  shootTime?: [Date, Date];
  endTime?: string;
  sceneSource?: number;
  snCode?: string;
  startTime?: string;
  userName?: string;
}>;
export const scenePageFetch = (props: ScenePageProps) =>
  sendFetch<ResPage<Scene>>(URL.getScenesPage, {
    method: "post",
    body: JSON.stringify({
      ...props,
      algorithmTime: null,
      startTime:
        props.shootTime &&
        dateFormat(props.shootTime[0], "yyyy-MM-dd 00:00:00"),
      endTime:
        props.shootTime &&
        dateFormat(props.shootTime[1], "yyyy-MM-dd 23:59:59"),
    }),
  });

export const delSceneFetch = (sceneId: number) =>
  sendFetch(
    URL.delScene,
    {
      method: "post",
      body: JSON.stringify({}),
    },
    { paths: { sceneId } }
  );

export type DevicePageProps = PageProps<{
  cameraSn?: string;
  cameraType?: number;
}>;
export const devicePageFetch = (props: DevicePageProps) =>
  sendFetch<ResPage<Device>>(URL.getDevicePage, {
    method: "post",
    body: JSON.stringify(props),
  });

export const delDeviceFetch = (deviceId: number) =>
  sendFetch(
    URL.delDevice,
    {
      method: "post",
      body: JSON.stringify({}),
    },
    { paths: { deviceId } }
  );
export const addDeviceFetch = (sn: string) =>
  sendFetch(URL.addDevice, {
    method: "post",
    body: JSON.stringify({ cameraSn: sn }),
  });



export const getTokenFetch = (num: string) =>
  sendFetch(URL.getFdTokenByNum + num, {
    method: "get",
  });

export * from './organization'
export * from './users'