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 { Toast } from "@antmjs/vantui";
// const Toast_ = Toast.createOnlyToast();

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

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

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

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

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

    if (!Taro.getStorageSync("token")) {
      await this.WCUserLogin();
      Taro.setStorageSync("isWelcome", true);
      await this.initData();
    } else {
      // this.setBg();
      go("/pages/entry/entry");
    }
  }
  componentDidMount() {}

  componentWillUnmount() {}

  componentDidShow() {}

  componentDidHide() {}

  async initData() {
    const { data } = await MpSplashDetail({
      pageNum: 1,
      pageSize: 5,
      type: 1,
    });
    if (data.code === 200) {
      let url = "";
      if (data.rows.length) {
        Taro.setStorageSync("MpSplashDetail_type1", JSON.stringify(data.rows));
      }

      let bgObj = data.rows.find((item: any) => item.fileSuffix === "video");
      if (bgObj) {
        url = bgObj.filePath;
        this.setState({ url });
      }
    } else {
      msg("获取首页视频失败！");
    }
  }

  setBg() {
    let bgData = Taro.getStorageSync("MpSplashDetail_type1");
    bgData = JSON.parse(bgData);
    let bgObj = bgData.find((item: any) => item.fileSuffix === "video");
    if (bgObj) {
      this.setState({ url: bgObj.filePath });
    }
  }

  async WCUserLogin() {
    const { code } = await Taro.login();
    const { data } = await WCUserLogin({ code });
    if (data.code === 200) {
      Taro.setStorageSync("token", data.data.token);
      Taro.setStorageSync("mobile", data.data.mobile);
      this.props.userRefresh(data.data);
    }
  }

  touchstart(event) {
    const { clientX, clientY } = event.changedTouches[0];
    this.setState({ touchX: clientX, touchY: clientY });
  }
  touchend(event) {
    const { clientX, clientY } = event.changedTouches[0];
    const { touchX, touchY } = this.state;
    if (clientX - touchX < -30 && Math.abs(clientY - touchY) < 30) {
      this.onEnded();
    }
  }
  onEnded = () => {
    let timeOut: any = null;
    clearTimeout(timeOut);
    timeOut = setTimeout(() => {
      go("/pages/entry/entry");
    }, 300);
  };

  render() {
    let { menu, url } = this.state;
    return (
      <Block>
        <View
          className="logo"
          style={{
            top: (menu?.top != undefined ? menu?.top : 44) + "px",
            height: menu?.height + "px",
            background: "transparent",
          }}
        >
          <Image
            src={require("../../img/welcome/top-logo.png")}
            mode="widthFix"
          />
        </View>
        <View
          className="main"
          onTouchStart={this.touchstart.bind(this)}
          onTouchEnd={this.touchend.bind(this)}
        >
          <Swiper className="absolutely">
            <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
                  className="bg_item"
                  src={url}
                  initialTime={0}
                  controls={true}
                  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,
  token: state.global.token,
});
const mapDispatchToProps = (dispatch) => ({
  userRefresh(value) {
    dispatch(userRefresh(value));
  },
});
export default connect(mapStateToProps, mapDispatchToProps)(Initiate);
