import {
  View,
  Map,
  MapProps,
  Input,
  Image,
  ScrollView,
  BaseEventOrig,
} from "@tarojs/components";
import "./index.less";
import { useMemo, useState } from "react";
import Taro, { useDidShow } from "@tarojs/taro";
import { Search } from "@taroify/icons";
import icon31 from "@/assets/icon/icon31.png";
import icon32 from "@/assets/icon/icon32.png";
import icon33 from "@/assets/icon/icon33.png";
import icon34 from "@/assets/icon/icon34.png";
import { Empty, Space, Tag } from "@taroify/core";
import services from "@/services";

const ListItem = ({ data }: { data: API.PointInfoDto }) => {
  return (
    <View className="list-item">
      <Space align="center">
        <View className="list-title">{data.locationTitle}</View>
        <Tag
          style={{
            backgroundColor: "rgba(227, 235, 255, 1)",
            color: "rgba(46, 108, 255, 1)",
          }}
        >
          {data.workTypeText}
        </Tag>
      </Space>
      <View>{data.address ?? "暂无地址"}</View>
      <View>工作时间：{data.workTime}</View>
    </View>
  );
};

export default function () {
  const [selectedMarkerId, setSelectedMarkerId] = useState<number>();
  const [modeType, setModeType] = useState<"map" | "list">("map");
  const params = Taro.getCurrentInstance().router?.params;
  const typeId = params?.typeId;
  const [curLocation, setCurLocation] = useState<{
    latitude: number;
    longitude: number;
  }>({
    latitude: 0,
    longitude: 0,
  });
  const [pointList, sePointList] = useState<API.PointInfoDto[]>([]);

  const getData = (searchText = "") => {
    Taro.getLocation({
      type: "gcj02",
      success: function (res) {
        setCurLocation(res);
        services.common
          .getMapMakersByType({
            categoryType: typeId!,
            longitude: String(res.longitude),
            latitude: String(res.latitude),
            searchText: searchText,
          })
          .then((res) => {
            if (res.code === 200) {
              sePointList(res.data);
            }
          });
      },
    });
  };

  useDidShow(() => {
    getData();
  });

  const makers = useMemo(() => {
    return pointList.map((item, index) => {
      return {
        id: index,
        latitude: Number(item.latitude),
        longitude: Number(item.longitude),
        meta: { ...item },
        callout: {
          content: item.locationTitle,
          color: selectedMarkerId === index ? "#fff" : "#000",
          fontSize: 14,
          bgColor: selectedMarkerId === index ? "#2E6CFF" : "#fff",
          padding: 8,
          display: "ALWAYS",
          textAlign: "center",
          anchorX: 0,
          anchorY: 0,
          borderRadius: 10,
          borderWidth: 0,
          borderColor: "#000",
        },
        width: 0,
        height: 0,
        iconPath: "",
      };
    }) as (MapProps.marker & { meta: API.PointInfoDto })[];
  }, [selectedMarkerId, pointList]);

  const onCalloutTap = (e: any) => {
    const markerId = e.detail.markerId;
    setSelectedMarkerId(markerId);
  };

  const search = (e: any) => {
    const value = e.detail.value;
    setSelectedMarkerId(undefined);
    getData(value);
  };
  return (
    <View className="map-container">
      <View className="map-action">
        <View className="inputWrap">
          <Search />
          <Input placeholder="输入内容" onInput={search}></Input>
        </View>
        <View
          className="switchBtn"
          onTap={() => {
            setModeType("map");
            setSelectedMarkerId(undefined);
          }}
        >
          <Image src={modeType === "map" ? icon31 : icon33}></Image>
        </View>
        <View
          className="switchBtn"
          onTap={() => {
            setModeType("list");

            setSelectedMarkerId(undefined);
          }}
        >
          <Image src={modeType === "map" ? icon32 : icon34}></Image>
        </View>
      </View>
      {selectedMarkerId !== undefined && (
        <View className="mapMakerCard">
          <View>{makers[selectedMarkerId]?.meta.locationTitle}</View>
          <View>{makers[selectedMarkerId]?.meta.address ?? "暂无"}</View>
          <View>{makers[selectedMarkerId]?.meta.workTime}</View>
        </View>
      )}

      {modeType === "list" ? (
        <>
          <View className="searchView"></View>
          <ScrollView scrollY className="listWrap">
            {pointList.length === 0 && (
              <Empty>
                <Empty.Description>暂无数据</Empty.Description>
              </Empty>
            )}
            {pointList.map((v) => {
              return <ListItem key={v.id} data={v} />;
            })}
          </ScrollView>
        </>
      ) : (
        <Map
          markers={makers}
          onCalloutTap={onCalloutTap}
          longitude={curLocation.longitude}
          latitude={curLocation.latitude}
          onClick={() => {
            setSelectedMarkerId(undefined);
          }}
          scale={15}
          onError={function (event: BaseEventOrig<MapProps.point>): void {
            throw new Error("Function not implemented.");
          }}
        />
      )}
    </View>
  );
}
