import dayjs from "dayjs";
import { MpSplashDetail, WCUserLogin } from "../../utils/Interface";
import { Component, PropsWithChildren, useEffect, useState } from "react";
import Taro from "@tarojs/taro";
// 引入 Swiper, SwiperItem 组件
import {
  Block,
  View,
  Text,
  Image,
  Video,
  Swiper,
  SwiperItem,
} from "@tarojs/components";

import Navbar from "../../components/navbar/navbar";

/*** redux ***/
import { connect } from "react-redux";
import { userRefresh, tokenRefresh } from "../../store/features/userInfo";
/*** redux end ***/

import "taro-ui/dist/style/components/button.scss"; // 按需引入
import "./initiate.less";
import { go, msg, setStorageSync, getStorageSync } from "../../utils/traoAPI";

class Initiate extends Component<any, any> {
  constructor(props) {
    super(props);
    this.state = {
      title: "hello world",
      menu: {
        top: 44,
        height: 0,
      },
      url: "",
    };
  }

  async onLoad() {
    Taro.setNavigationBarColor({
      frontColor: "#ffffff",
      backgroundColor: "#58585A",
      animation: {
        duration: 300,
        timingFunc: "easeIn",
      },
    });

    const menu = Taro.getMenuButtonBoundingClientRect();
    this.setState({ menu });

    if (!getStorageSync("token")) {
      await this.WCUserLogin();
    } else {
      go("/pages/entry/entry");
    }
  }
  componentDidMount() {}

  componentWillUnmount() {}

  componentDidShow() {}

  componentDidHide() {}

  async initData() {
    Taro.showLoading({
      title: "请求中...",
      mask: true,
    });
    const { data } = await MpSplashDetail({
      pageNum: 1,
      pageSize: 5,
      type: 1,
    });
    Taro.hideLoading();
    if (data.code === 200) {
      let url = "";
      if (data.rows.length) {
        Taro.setStorageSync("MpSplashDetail_type1", JSON.stringify(data.rows));
        // 1.判断是否设置登录页视频，有则正常显示视频
        let bgObj = data.rows.find((item: any) => item.fileSuffix === "video");
        if (bgObj) {
          url = bgObj.filePath;
          this.setState({ url });
        } else {
          // 1-2.判断是否设置介绍页图片，有则跳转介绍登录页
          let imgList = data.rows.filter(
            (item: any) => item.fileSuffix === "images"
          );
          if (imgList.length > 0) {
            go("/pages/entry/entry");
            return;
          } else {
            // 1-3.如果介绍页图片也没有，直接跳转首页
            Taro.switchTab({
              url: "/pages/index/index",
            });
          }
        }
      } else {
        Taro.switchTab({
          url: "/pages/index/index",
        });
      }
    } else {
      msg("请求失败，请联系管理员");
    }
  }

  async WCUserLogin() {
    Taro.showLoading({
      title: "请求中...",
      mask: true,
    });
    const { code } = await Taro.login();
    const { data } = await WCUserLogin({ code });
    Taro.hideLoading();
    if (data.code === 200) {
      Taro.setStorageSync("isWelcome", true);
      Taro.setStorageSync("mobile", data.data.mobile);
      this.props.tokenRefresh(data.data);

      setTimeout(() => {
        this.initData();
      }, 300);
    } else {
      msg("请求失败,尝试重新请求");
      this.WCUserLogin();
    }
  }

  onFinish(event) {
    // const { current } = event.detail;
    // const { toRight, isClick, welcomeList } = this.state;
    // if (current === welcomeList.length - 1) {
    //   if (toRight || isClick) {
    //     this.setState({ toRight: false, isClick: false });
    //   } else {
    //     // this.toHomePage();
    //   }
    // }
    this.onEnded();
  }
  onEnded = () => {
    let token = getStorageSync("token");
    if (token) {
      let data = Taro.getStorageSync("MpSplashDetail_type1") || undefined;
      if (data) {
        let detail = JSON.parse(data);
        let list = detail.filter((item: any) => item.fileSuffix === "images");
        if (list.length === 0) {
          Taro.switchTab({
            url: "/pages/index/index",
          });
          return;
        }
      }

      let timeOut: any = null;
      clearTimeout(timeOut);
      timeOut = setTimeout(() => {
        go("/pages/entry/entry");
      }, 300);
    } else {
      msg("请求中，请稍候");
    }
  };

  render() {
    let { menu, url } = this.state;
    return (
      <Block>
        <Navbar transparent={true} isWhite={true}></Navbar>
        <View className="main">
          <Swiper
            className="absolutely"
            onAnimationFinish={this.onFinish.bind(this)}
          >
            <SwiperItem
              className="absolutely"
              onClick={this.onEnded}
              style="background: #ccc"
            >
              <View className="middle">
                <Image
                  className="logo_middle"
                  src={require("../../img/welcome/top-logo.png")}
                  mode="aspectFill"
                ></Image>
                <View className="title">欢迎来到花至小程序</View>
              </View>
              <View className="bg">
                <Video
                  id="initvideo"
                  className="bg_item"
                  src={url}
                  initialTime={0}
                  controls={false}
                  autoplay={true}
                  loop={true}
                  muted={true}
                  showProgress={false}
                  showFullscreenBtn={false}
                  showPlayBtn={false}
                  showCenterPlayBtn={false}
                  enableProgressGesture={false}
                  objectFit="cover"
                />
              </View>
            </SwiperItem>
          </Swiper>
        </View>
      </Block>
    );
  }
}

const mapStateToProps = (state) => ({
  mobile: state.userInfo.mobile,
});
const mapDispatchToProps = (dispatch) => ({
  userRefresh(value) {
    dispatch(userRefresh(value));
  },
  tokenRefresh(value) {
    dispatch(tokenRefresh(value));
  },
});
export default connect(mapStateToProps, mapDispatchToProps)(Initiate);
