import Taro from "@tarojs/taro";
import dayjs, { Dayjs } from "dayjs";
import "dayjs/locale/zh-cn";
import { calculateDistance } from "@/utils";
import { View, Image, Text, Map } from "@tarojs/components";
import img from "@/config/images";
import styles from "./index.module.scss";

dayjs.locale("zh-cn");

function genGameLength(startTime: Dayjs, endTime: Dayjs) {
  if (!startTime || !endTime) {
    return "";
  }
  const hours = endTime.diff(startTime, "hour");
  if (Math.floor(hours / 24) >= 1) {
    const leftHours = Math.floor(hours % 24);
    return `${Math.floor(hours / 24)}天${
      leftHours !== 0 ? `${leftHours}小时` : ""
    }`;
  }
  return `${hours}小时`;
}

function genGameRange(startTime: Dayjs, endTime: Dayjs) {
  if (!startTime || !endTime) {
    return "";
  }
  // 如果跨天（自然日）
  if (!startTime.isSame(endTime, "day")) {
    return `${startTime.format("HH:mm")} - ${endTime.format("MM月DD日 HH:mm")}`;
  }
  return `${startTime.format("HH:mm")} - ${endTime.format("HH:mm")}`;
}

// 球局信息
export default function GameInfo(props) {
  const { detail, currentLocation } = props;
  const {
    latitude,
    longitude,
    location,
    location_name,
    start_time,
    end_time,
    weather,
  } = detail || {};

  const [{ iconDay, tempMax, tempMin }] = weather || [{}];

  const openMap = () => {
    Taro.openLocation({
      latitude, // 纬度（必填）
      longitude, // 经度（必填）
      name: location_name, // 位置名（可选）
      address: location, // 地址详情（可选）
      scale: 15, // 地图缩放级别（1-28）
    });
  };

  const [c_latitude, c_longitude] = currentLocation;
  const distance =
    latitude && longitude
      ? calculateDistance(c_latitude, c_longitude, latitude, longitude) / 1000
      : 0;

  const startTime = dayjs(start_time);
  const endTime = dayjs(end_time);
  const game_length = genGameLength(startTime, endTime);

  const startMonth = startTime.format("M");
  const startDay = startTime.format("D");
  const theDayOfWeek = startTime.format("dddd");
  const startDate = `${startMonth}月${startDay}日 ${theDayOfWeek}`;
  const gameRange = genGameRange(startTime, endTime);

  return (
    <View className={styles["detail-page-content-game-info"]}>
      {/* Date and Weather */}
      <View className={styles["detail-page-content-game-info-date-weather"]}>
        {/* Calendar and Date time */}
        <View
          className={
            styles["detail-page-content-game-info-date-weather-calendar-date"]
          }
        >
          {/* Calendar */}
          <View
            className={
              styles[
                "detail-page-content-game-info-date-weather-calendar-date-calendar"
              ]
            }
          >
            <View className={styles.month}>{startMonth}月</View>
            <View className={styles.day}>{startDay}</View>
          </View>
          {/* Date time */}
          <View
            className={
              styles[
                "detail-page-content-game-info-date-weather-calendar-date-date"
              ]
            }
          >
            <View className={styles.date}>{startDate}</View>
            <View className={styles["venue-time"]}>
              {gameRange} ({game_length})
            </View>
          </View>
        </View>
        {/* Weather */}
        <View
          className={
            styles["detail-page-content-game-info-date-weather-weather"]
          }
        >
          {/* Weather icon */}
          <View
            className={
              styles["detail-page-content-game-info-date-weather-weather-icon"]
            }
          >
            {/*<Image className="weather-icon" src={img.ICON_WEATHER_SUN} />*/}
            <i className={`qi-${iconDay}`}></i>
          </View>
          {/* Weather text and temperature */}
          <View
            className={
              styles[
                "detail-page-content-game-info-date-weather-weather-text-temperature"
              ]
            }
          >
            {tempMin && tempMax && (
              <Text>
                {tempMin}℃ - {tempMax}℃
              </Text>
            )}
          </View>
        </View>
      </View>
      {/* Place */}
      <View className={styles["detail-page-content-game-info-place"]}>
        {/* venue location message */}
        <View className={styles["location-message"]}>
          {/* location icon */}
          <View className={styles["location-message-icon"]}>
            <Image
              className={styles["location-message-icon-image"]}
              src={img.ICON_DETAIL_MAP}
            />
          </View>
          {/* location message */}
          <View className={styles["location-message-text"]}>
            {/* venue name and distance */}
            {distance ? (
              <View
                className={styles["location-message-text-name-distance"]}
                onClick={openMap}
              >
                <Text>{location_name || "-"}</Text>
                <Text>·</Text>
                <Text>{distance.toFixed(1)}km</Text>
                <Image
                  className={
                    styles["location-message-text-name-distance-arrow"]
                  }
                  src={img.ICON_DETAIL_ARROW_RIGHT}
                />
              </View>
            ) : (
              ""
            )}
            {/* venue address */}
            <View className={styles["location-message-text-address"]}>
              <Text>{location || "-"}</Text>
            </View>
          </View>
        </View>
        {/* venue map */}
        <View className={styles["location-map"]}>
          {longitude && latitude && (
            <Map
              className={styles["location-map-map"]}
              longitude={c_longitude}
              latitude={c_latitude}
              markers={[
                {
                  id: 1,
                  latitude,
                  longitude,
                  iconPath: require("@/static/detail/icon-stark.svg"),
                  width: 16,
                  height: 16,
                },
              ]}
              includePoints={[
                { latitude, longitude },
                { latitude: c_latitude, longitude: c_longitude },
              ]}
              includePadding={{ left: 50, right: 50, top: 50, bottom: 50 }}
              onError={() => {}}
              // hide business msg
              showLocation
              theme="dark"
            />
          )}
        </View>
      </View>
    </View>
  );
}
