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

import { go, loading, msg } from "../../utils/traoAPI";

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

import { RefreshWxUserInfo, GetNoReadMessageNum } from "../../utils/Interface";

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

import type CustomTabBar from "../../custom-tab-bar";
import Navbar from "../../components/navbar/navbar";

import PopupAlert from "../../components/popup/popup-alert";
import PopupDrawer from "../../components/popup/popup-drawer";

class User extends Component<any, any> {
  pageCtx = Taro.getCurrentInstance().page;
  constructor(props) {
    super(props);
    this.state = {
      name: "user",
      userInfo: {
        ...this.props.userInfo,
      },
      otherSetting: {
        ...this.props.otherSetting,
      },
      MerchMobile: "",
      count: 0,
      year: new Date().getFullYear(),
      lastDay: dayjs().endOf("year").endOf("month").format("YYYY-MM-DD"),
      messagecount: Taro.getStorageSync("messageCount") || 0,
      isNotRegister: false, // 是否未注册
      isShowCustomerService: false, // 反馈留言
      messageInfo: "", // 用户留言
      isDev: false,
    };
  }

  async onLoad() {
    this.initData();
  }
  componentDidMount() {}

  componentWillUnmount() {}

  componentDidShow() {
    this.setState({ userInfo: this.props.userInfo });

    let messagecount = Taro.getStorageSync("messageCount");
    this.setState({ messagecount: messagecount });

    const tabbar = Taro.getTabBar<CustomTabBar>(this.pageCtx);
    tabbar?.setSelected(4);
  }

  componentDidHide() {}

  async initData() {
    this.RefreshWxUserInfo();
    this.GetNoReadMessageNum();
  }

  // 获取消息数量
  GetNoReadMessageNum = async () => {
    let res = await GetNoReadMessageNum();
    if (res.data.code === 200) {
      Taro.setStorageSync("messageCount", res.data.data);
      this.setState({ messagecount: res.data.data });
    }
  };

  // 刷新用户信息
  RefreshWxUserInfo = async () => {
    let res = await RefreshWxUserInfo();
    console.log("res", res);
    if (res.data.code === 200) {
      this.props.userRefresh(res.data.data);
      this.setState({ userInfo: res.data.data });
    }
  };

  postSaveMessage = async () => {
    let { messageInfo } = this.state;
    let params = {
      source: 1,
      messageInfo: messageInfo,
    };
    let res = await SaveMessage(params);
    if (res.data.code === 200) {
      msg("提交成功！");
    } else {
      msg("提交失败！");
    }
  };

  gourl = (e) => {
    let mobile = Taro.getStorageSync("mobile");
    if (!mobile) {
      this.setState({ isNotRegister: true }); // 打开弹窗
      return;
    }
    let url = e.currentTarget.dataset.url;
    Taro.navigateTo({
      url,
    });
  };

  // 开发中弹窗
  devOpen = (e) => {
    this.setState({ isDev: true });
  };

  // 不检查登录跳转
  goUrlNoRegister = (e) => {
    let url = e.currentTarget.dataset.url;
    Taro.navigateTo({
      url,
    });
  };

  gourls = (e) => {
    let url = e.currentTarget.dataset.url;
    Taro.navigateTo({
      url,
    });
  };

  gominiapp() {
    Taro.navigateToMiniProgram({
      appId: "wx438760012de48d74",
      path: "/pages/home/home",
      envVersion: "release",
      success(res) {
        // 打开成功
        // console.log("res", res);
      },
    });
  }

  showCustomerService = () => {
    let mobile = Taro.getStorageSync("mobile");
    if (!mobile) {
      this.setState({ isNotRegister: true });
      return;
    }
    this.setState({ isShowCustomerService: true });
  };

  confirmCustomerService = () => {
    let { messageInfo } = this.state;
    if (messageInfo.length) {
      this.postSaveMessage();
      this.closeCustomerService();
    } else {
      msg("留言内容不能为空！");
      // Toast_.fail({
      //   message: "留言内容不能为空！",
      // });
    }
  };
  closeCustomerService = () => {
    this.setState({ isShowCustomerService: false });
  };

  closeRegisterAlert = () => {
    this.setState({ isNotRegister: false });
  };

  onInputTextarea = (e) => {
    this.setState({ messageInfo: e.detail.value });
  };
  closeDev = () => {
    this.setState({ isDev: false });
  };

  render() {
    let {
      userInfo,
      count,
      lastDay,
      messagecount,
      isNotRegister,
      isShowCustomerService,
      isDev,
    } = this.state;

    return (
      <Block>
        {/* <PopupAlert
          isShow={isDev}
          isClose={true}
          title="提示"
          content="页面正在开发中"
          confirmButtonText="确定"
          textAlgin="center"
          close={this.closeDev}
          confirm={this.closeDev}
        /> */}
        <PopupAlert
          isShow={isNotRegister}
          isClose={true}
          title="提示"
          content="暂未授权注册，请点击注册"
          confirmButtonText="确定"
          textAlgin="center"
          type="1"
          close={this.closeRegisterAlert}
          confirm={this.closeRegisterAlert}
        />
        <Navbar transparent={true}></Navbar>
        <View className="user_bg_card">
          <Image
            src={require("../../img/user/user-bg.png")}
            mode="aspectFill"
          ></Image>
        </View>
        <View className="info_box">
          <View className="infobox1">
            <View
              className="img"
              data-url="/pages/userInfoDetail/userInfoDetail"
              onClick={this.gourl}
            >
              {userInfo.headimg ? (
                <Image src={userInfo.headimg} mode="widthFix" />
              ) : (
                // <Image
                //   className="default-img"
                //   src={require("../../img/user/user.png")}
                //   mode="widthFix"
                // />
                <Image
                  className="avatar"
                  src={require("../../img/welcome/avatar.png")}
                />
              )}
            </View>
            <View
              className="info1 flex aitems"
              data-url="/pages/userInfoDetail/userInfoDetail"
              onClick={this.gourl}
            >
              <View className="tipbox flex aitems">
                <View className="tip1 flex aitems">
                  <View className="name">
                    {userInfo.nickname
                      ? userInfo.nickname
                      : "用户" + (userInfo.id || "001")}
                  </View>
                </View>
                {userInfo.id ? (
                  <View className="tip2">用户编号 : {userInfo.id}</View>
                ) : (
                  <View className="tip2">用户编号 : 001</View>
                )}
              </View>
            </View>
            <View className="info2 flex aitems sa">
              <View
                className="block"
                data-url="/pages/instrument_manage/index?isback=1"
                onClick={this.goUrlNoRegister}
                // onClick={this.devOpen}
              >
                <Image
                  className="bg_img"
                  src={require("../../img/device_bg.png")}
                  mode="aspectFill"
                ></Image>
                <View className="tip flex aitems">
                  <View className="tip1">我的设备</View>
                  <View className="right">
                    <Image src="/img/my_right.png" mode="aspectFill" />
                  </View>
                </View>
                <View className="num">{count}</View>
                <View className="txt">查看绑定设备详情</View>
              </View>
              <View
                className="block"
                onClick={this.goUrlNoRegister}
                data-url="/pages/integral_list/integral_list"
              >
                <Image
                  className="bg_img"
                  src={require("../../img/point_bg.png")}
                  mode="aspectFill"
                ></Image>
                <View className="tip flex aitems">
                  <View className="tip1">我的积分</View>
                  <View className="right">
                    <Image
                      src={require("../../img/my_right.png")}
                      mode="aspectFill"
                    />
                  </View>
                </View>
                <View className="num">{userInfo.credit}</View>
                {/* <View className="txt"></View> */}
                <View className="txt">查看积分详情</View>
              </View>
            </View>
            <View className="info3">
              {lastDay} 过期积分: {userInfo.expireCredit}
            </View>
          </View>

          <View className="infobox2">
            <View className="title">会员服务</View>
            <View className="info flex aitems">
              <View
                className="block flex aitems"
                data-url="/pages/userInfoDetail/userInfoDetail"
                onClick={this.gourl}
              >
                <View className="img">
                  <Image src={require("../../img/1.png")} mode="aspectFill" />
                </View>
                <View className="tip1">个人信息</View>
              </View>
              <View className="block flex aitems" onClick={this.gominiapp}>
                <View className="img">
                  <Image src={require("../../img/2.png")} mode="aspectFill" />
                </View>
                <View className="tip1">查验正伪</View>
              </View>
              <View
                className="block flex aitems"
                onClick={this.goUrlNoRegister}
                data-url="/pages/integral_list/integral_list"
              >
                <View className="img">
                  <Image src={require("../../img/3.png")} mode="aspectFill" />
                </View>
                <View className="tip1">积分明细</View>
              </View>
              <View
                className="block flex aitems message"
                data-url="/pages/message/message"
                onClick={this.gourl}
              >
                <View className="img">
                  <Image src={require("../../img/4.png")} mode="aspectFill" />
                  {messagecount ? <View className="tip"></View> : ""}
                </View>
                <View className="tip1">消息中心</View>
              </View>
            </View>
            <View className="title2">其它服务</View>
            <View className="info flex aitems">
              <View
                className="block flex aitems"
                data-url="/pages/consultant/consultant"
                onClick={this.goUrlNoRegister}
              >
                <View className="img">
                  <Image src={require("../../img/5.png")} mode="aspectFill" />
                </View>
                <View className="tip1">联系客服</View>
              </View>
              <View
                className="block flex aitems"
                onClick={this.showCustomerService}
              >
                <View className="img">
                  <Image src={require("../../img/6.png")} mode="aspectFill" />
                </View>
                <View className="tip1">意见反馈</View>
              </View>
              <View
                className="block flex aitems"
                data-url="/pages/about/about"
                onClick={this.goUrlNoRegister}
              >
                <View className="img">
                  <Image src={require("../../img/7.png")} mode="aspectFill" />
                </View>
                <View className="tip1">更多设置</View>
              </View>
              {/* <View
                className="block flex aitems"
                data-url="/pages/privacyPolicy/privacyPolicy"
                onClick={this.goUrlNoRegister}
              >
                <View className="img">
                  <Image src={require("../../img/8.png")} mode="aspectFill" />
                </View>
                <View className="tip1">隐私政策</View>
              </View> */}
            </View>
          </View>
        </View>

        <PopupDrawer
          isShow={isShowCustomerService}
          isClose={true}
          title="留言反馈"
          content={
            <Block>
              <Textarea
                className="service-textarea"
                maxlength={100}
                showCount={true}
                placeholder="请在此处写下您的意见与反馈"
                placeholderStyle="font-weight: 400;font-size:28rpx;"
                onInput={this.onInputTextarea}
              ></Textarea>
            </Block>
          }
          confirmButtonText="提交"
          textAlgin="left"
          close={this.closeCustomerService}
          confirm={this.confirmCustomerService}
        />
        {/* <Toast_ /> */}
      </Block>
    );
  }
}

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