import { Component, PropsWithChildren, useEffect, useState } from "react";
import Taro from "@tarojs/taro";
// 引入 Swiper, SwiperItem 组件
import { View, Text, Image } from "@tarojs/components";

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

import "taro-ui/dist/style/components/button.scss"; // 按需引入
import "./shop.less";

import { GetOtherSetting } from "../../utils/Interface";

import type CustomTabBar from "../../custom-tab-bar";
class Shop extends Component<any, any> {
  pageCtx = Taro.getCurrentInstance().page;
  constructor(props) {
    super(props);
    this.state = {
      name: "shop",
      otherSetting: {
        ...this.props.otherSetting,
      },
    };
  }

  async onLoad() {}
  componentDidMount() {}

  componentWillUnmount() {}

  componentDidShow() {
    const tabbar = Taro.getTabBar<CustomTabBar>(this.pageCtx);
    tabbar?.setSelected(3);
    this.showInit();
  }

  componentDidHide() {}

  async initData() {}

  showInit() {
    let { otherSetting } = this.state;
    if (otherSetting.skipAppid) {
      this.goMiniProgram();
    } else {
      this.GetOtherSetting(); // 获取小程序设置：商城地址和版本
    }
  }

  goMiniProgram() {
    let { otherSetting } = this.state;
    Taro.navigateToMiniProgram({
      appId: otherSetting.skipAppid,
      path: otherSetting.skipPath,
      // sysVersion: otherSetting.sysVersion,
      success(res) {
        // 打开成功
        Taro.switchTab({
          url: "/pages/index/index",
        });
      },
      fail(res) {
        Taro.switchTab({
          url: "/pages/index/index",
        });
      },
    });
  }

  // 获取小程序设置
  GetOtherSetting = async () => {
    Taro.showLoading({
      title: "请求中...",
      mask: true,
    });
    let res = await GetOtherSetting();
    Taro.hideLoading();
    if (res.data.code === 200) {
      this.props.otherSettingRefresh(res.data.data);

      let { otherSetting } = this.state;
      otherSetting.skipAppid = res.data.data.skipAppid;
      otherSetting.skipPath = res.data.data.skipPath;
      otherSetting.sysVersion = res.data.data.sysVersion;
      this.setState({ otherSetting });
      this.goMiniProgram();
    }
  };

  render() {
    return <View></View>;
  }
}

const mapStateToProps = (state) => ({
  otherSetting: state.otherSetting,
});
const mapDispatchToProps = (dispatch) => ({
  otherSettingRefresh(data) {
    dispatch(otherSettingRefresh(data));
  },
});
export default connect(mapStateToProps, mapDispatchToProps)(Shop);
