// import React from "react";
import { useState, useEffect } from "react";
import { View, Image, Text, Button } from "@tarojs/components";
import Taro, { useRouter } from "@tarojs/taro";
import classnames from "classnames";
import dayjs from "dayjs";
import "dayjs/locale/zh-cn";
import { generatePosterImage, delay } from "@/utils";
import { withAuth } from "@/components";
import GeneralNavbar from "@/components/GeneralNavbar";
import DetailService from "@/services/detailService";
import DownloadIcon from "@/static/detail/download_icon.svg";
import WechatLogo from "@/static/detail/wechat_icon.svg";
import WechatTimeline from "@/static/detail/wechat_timeline.svg";
import { useUserActions } from "@/store/userStore";
import { DayOfWeekMap } from "../detail/config";
import {
  genNTRPRequirementText,
  genGameLength,
  formatGameStartTime,
} from "@/utils/helper";
import { waitForAuthInit } from "@/utils/authInit";
import { OSS_BASE } from "@/config/api";
import styles from "./index.module.scss";

dayjs.locale("zh-cn");

function SharePoster(props) {
  const [url, setUrl] = useState("");
  const { fetchUserInfo } = useUserActions();
  const { id } = useRouter().params;

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

  async function fetchDetail() {
    const res = await DetailService.getDetail(Number(id));
    handleGenPoster(res.data);
  }
  async function handleGenPoster(detail) {
    const {
      id,
      play_type,
      skill_level_max,
      skill_level_min,
      start_time,
      end_time,
      location_name,
      image_list,
      title,
    } = detail || {};
    // 先等待静默登录完成
    await waitForAuthInit();
    const userInfo = await fetchUserInfo();
    const { avatar_url, nickname } = userInfo;
    const startTime = dayjs(start_time);
    const endTime = dayjs(end_time);
    const dayofWeek = DayOfWeekMap.get(startTime.day());
    const gameLength = genGameLength(startTime, endTime);
    Taro.showLoading({ title: "生成中..." });
    const qrCodeUrlRes = await DetailService.getQrCodeUrl({
      page: "game_pages/detail/index",
      scene: `id=${id}`,
    });
    const qrCodeUrl = qrCodeUrlRes.data.ossPath;
    // const qrCodeUrl = await base64ToTempFilePath(
    //   qrCodeUrlRes.data.qr_code_base64
    // );
    // debugger
    await delay(100);
    const url = await generatePosterImage({
      playType: play_type,
      ntrp: `NTRP ${genNTRPRequirementText(skill_level_min, skill_level_max)}`,
      mainCoursal:
        image_list[0] && image_list[0].startsWith("http")
          ? image_list[0]
          : `${OSS_BASE}/front/ball/images/0621b8cf-f7d6-43ad-b852-7dc39f29a782.png`,
      nickname,
      avatarUrl: avatar_url,
      title,
      locationName: location_name,
      date: `${startTime.format("M月D日")} (${dayofWeek})`,
      time: `${formatGameStartTime(startTime)} ${gameLength}`,
      qrCodeUrl,
    });
    Taro.hideLoading();
    setUrl(url);
  }
  function handleShare() {
    Taro.showShareImageMenu({
      path: url,
    });
  }

  return (
    <>
      <GeneralNavbar title="生成分享图" className={styles.navbar} />
      {url && (
        <View className={styles.posterContainer}>
          <View className={styles.posterWrap}>
            <View className={styles.imageContainer}>
              <Image className={styles.poster} src={url} mode="widthFix" />
            </View>
          </View>
          <View className={styles.sharePoster}>
            <Button
              className={styles.shareItem}
              plain={true}
              onClick={handleShare}
            >
              <View className={styles.icon}>
                <Image className={styles.download} src={DownloadIcon} />
              </View>
              <Text>保存至手机</Text>
            </Button>
            <Button
              className={styles.shareItem}
              plain={true}
              onClick={handleShare}
            >
              <View className={classnames(styles.icon, styles.wechatIcon)}>
                <Image className={styles.wechat} src={WechatLogo} />
              </View>
              <Text>微信好友</Text>
            </Button>
            <Button
              className={styles.shareItem}
              plain={true}
              onClick={handleShare}
            >
              <View className={styles.icon}>
                <Image className={styles.timeline} src={WechatTimeline} />
              </View>
              <Text>朋友圈</Text>
            </Button>
          </View>
        </View>
      )}
    </>
  );
}

export default withAuth(SharePoster);
