import classnames from "classnames";
import dayjs from "dayjs";
import Taro from "@tarojs/taro";
import { Component } from "react";
import {
  Block,
  View,
  Text,
  Image,
  Swiper,
  SwiperItem,
} from "@tarojs/components";

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

/** 自定义组件 **/
import AtCalendar from "../../components/calendar";
import PopupPrivacy from "../../components/popup/popup-privacy";
import PopupBinding from "../../components/popup/popup-binding";
// import PopupPrivacyTest from "../../components/popup/popup-privacy-test";

import PopupSiteSwiper from "../../components/popup/popup-site-swiper";
import PopupAlert from "../../components/popup/popup-alert";
import type CustomTabBar from "../../custom-tab-bar";
import Navbar from "../../components/navbar/navbar";
/** 自定义组件 **/

import {
  RefreshWxUserInfo,
  GetNoReadMessageNum,
  GetSitePopupList,
  GetSiteCarousel,
  GetSiteAddTag,
  InstrumentInfo,
  WCUserLogin,
} from "../../utils/Interface";

// css引入
import "taro-ui/rn/style/components/calendar.scss";
import "./index.less";
import {
  go,
  goJump,
  msg,
  getStorageSync,
  setStorageSync,
} from "@/utils/traoAPI";

class Index extends Component<any, any> {
  // pageCtx = Taro.getCurrentInstance().page;
  $instance = Taro.getCurrentInstance();

  constructor(props) {
    super(props);
    this.state = {
      isRegisterBoolean: false, // 是否已登录
      isShowPrivacyPopup: false,
      isShowSiteSwiper: false,
      isNotRegister: false, // 是否未注册
      isDev: false, // 正在开发提示
      sitePopupList: [], // 站点管理列表
      // imgUrl: this.app.globalData.imgUrl,
      userinfo: {
        mobile: this.props.mobile,
      },
      connectInstrument: {},
      yiqiinfo: {},
      list: [],
      params: "",
      messageCount: Taro.getStorageSync("messageCount") || 0,
      offlineDialogType: 1, //1离线弹窗 2升级弹窗
      offlineDialogForce: 0, //0可选是否升级  1强制升级
      versioninfo: {}, //仪器版本号,
      info: {}, // 护理推荐点击参与活动的信息
      weekinfo: undefined,
      // 日历
      currentDate: dayjs().format("YYYY-MM-DD"),
      calendarComplete: [
        dayjs().subtract(1, "day").format("YYYY-MM-DD"),
        dayjs().subtract(3, "day").format("YYYY-MM-DD"),
      ],
      calendarInComplete: [
        dayjs().add(1, "day").format("YYYY-MM-DD"),
        dayjs().add(8, "day").format("YYYY-MM-DD"),
      ],
      // 横幅轮播
      bannerList: [],
      bannerCurrent: 0,

      /** 绑定仪器 */
      isVisibleBinding: false, // 绑定弹窗
      isBindingError: false, // 绑定失败
      isBeforeBinding: false, // 已绑定弹窗
      typeBinding: 0,
      instrumentList: [], // 仪器列表
      instrumentInfo: {
        // 扫码获得的序列号仪器
        bindingStatus: 0, // 0已绑定，1未绑定，2已解绑
        createBy: null,
        createTime: "2024-01-19 17:46:10",
        exportFields: [],
        id: 4,
        instrumentId: 82,
        instrumentIdArray: null,
        instrumentName: "研发测试FR380",
        instrumentSerialIdList: [],
        queryInstrumentIds: null,
        remark: null,
        serial: "", // 设备序列号
        source: "导入",
        status: 0, // 0正常 1停用
        updateBy: null,
        updateTime: null,
        validStatus: 1, // 1有效，0无效
      },
      /** 绑定仪器 End */
    };
  }

  async onLoad() {
    // 仅非扫码进入页面时，校验跳转欢迎页
    if (!this.$instance.router?.params?.q) {
      const isFirst = Taro.getStorageSync("isWelcome");
      if (!isFirst) {
        go("/pages/initiate/initiate");
      }
    }
  }

  componentDidMount() {}

  componentWillUnmount() {}

  componentDidShow() {
    const tabbar = Taro.getTabBar<CustomTabBar>(this.$instance.page);
    tabbar?.setSelected(0);

    this.showInit();
  }

  componentDidHide() {}

  showInit() {
    // 判断是否登录
    let mobile = Taro.getStorageSync("mobile");
    if (mobile) {
      this.setState({ isRegisterBoolean: true });
    }
    // 非扫码进入小程序，需判断是否跳转欢迎页；扫码进入小程序，先缓存序列号，再检测隐私弹窗
    let url = this.$instance.router?.params?.q || "";
    if (!url) {
      // 非扫码进入
      Taro.setStorageSync("isScan", false);
      const isFirst = Taro.getStorageSync("isWelcome");
      if (isFirst) {
        this.checkShowPrivacyPopup();
      }
    } else {
      // 扫码进入
      Taro.setStorageSync("isScan", true);
      if (url) {
        let _url = decodeURIComponent(url);
        if (_url.indexOf("?")) {
          let ids = _url.split("?");
          if (ids.length > 1) {
            let serial = ids[1];
            Taro.setStorageSync("serial", serial);
          }
        }
      }
      this.checkShowPrivacyPopup();
    }
  }

  // 检测是否弹出隐私协议
  checkShowPrivacyPopup() {
    Taro.getPrivacySetting({
      success: (res) => {
        // console.log("检测是否弹出隐私协议", res); // 返回结果为: res = { needAuthorization: true/false, privacyContractName: '《xxx隐私保护指引》' }
        if (res.needAuthorization) {
          this.setState({ isShowPrivacyPopup: true });
        } else {
          // 用户已经同意过隐私协议，所以不需要再弹出隐私协议，也能调用隐私接口
          // this.initData();
          this.isSancQrcodeEnter();
        }
      },
      fail: () => {},
      complete: () => {
        // 授权完成运行页面初始化
      },
    });
  }

  // 页面初始化
  async initData() {
    let token = getStorageSync("token");
    if (!token) {
      // 如果token过期，先登录，登录完成后自动初始化
      await this.WCUserLogin();
    } else {
      // token没过期，直接请求数据
      this.initPageData();
    }
  }

  async initPageData() {
    const mobile = Taro.getStorageSync("mobile");
    this.GetSiteCarousel();

    if (mobile) {
      this.GetNoReadMessageNum(); // 查询是否有消息
      await this.bindingInstrumentList(); // 获取已绑定设备
      await this.getInstrumentInfoBySerial(); // 扫码序列号查询：注册后才调用，因为扫码未注册直接跳转注册页

      if (!this.props.isShowIndexFlag) {
        this.GetSitePopupList();
        // 全局内存缓存，仅初次进入首页运行
        this.props.setIndexFlag(true);
        // 小程序切到后台，则清除弹窗缓存
        Taro.onAppHide((res) => {
          console.log("小程序进入后台：", res);
          this.props.setIndexFlag(false);
        });
      }
    }
  }

  // 刷新用户信息
  RefreshWxUserInfo = async () => {
    let res = await RefreshWxUserInfo();
    if (res.data.code === 200) {
      this.props.userRefresh(res.data.data);
    }
  };

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

  // 获取站点管理-弹窗列表 1-首页 2-发现模块 3-活动模块
  GetSitePopupList = async () => {
    let res = await GetSitePopupList(1);
    if (res.data.code === 200) {
      if (res.data.data) {
        if (res.data.data.length) {
          this.setState({
            sitePopupList: res.data.data,
            isShowSiteSwiper: true,
          });
        }
      }
    }
  };

  // 获取站点管理-广告轮播列表
  GetSiteCarousel = async () => {
    let res = await GetSiteCarousel();
    if (res.data.code === 200) {
      if (res.data.data) {
        this.setState({ bannerList: res.data.data });
      }
    }
  };

  GetSiteAddTag = async (id) => {
    let res = await GetSiteAddTag(id);
    if (res.data.code === 200) {
      console.log("点击自动上报，不需要逻辑处理");
    }
  };

  goRegister() {
    go("/pages/register/register");
  }

  // 新增设备
  addNewDevice = () => {
    if (this.isRegister("addNewDevice")) {
      // todo
      go("/pages/instrument/instrument");
    }
  };

  // 是否已注册
  isRegister(type = "") {
    if (type === "addNewDevice") {
      Taro.setStorageSync("isInstrumentJump", "true"); // 判断是否点击新增设备按钮，用于信息完善页判断跳转逻辑
    } else {
      Taro.setStorageSync("isInstrumentJump", "false"); // 重置
    }
    if (!this.state.isRegisterBoolean) {
      this.alertRegister();
      return false;
    }
    return true;
  }

  showPrivacy = () => {
    this.setState({ isShowPrivacyPopup: true });
  };

  closePrivacy = () => {
    this.setState({ isShowPrivacyPopup: false });
    this.initData();
  };

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

  public alertRegister = () => {
    this.setState({ isNotRegister: true }); // 打开弹窗
  };

  onTimeChange = (value) => {
    console.log("onTimeChange", value);
    this.setState({ currentDate: value });
  };

  // 护理记录
  toNursingRecords = () => {
    go("/pages/recording/recording");
  };

  gourl = (e) => {
    const { url } = e.currentTarget.dataset;
    if (this.isRegister()) {
      go(url);
    }
  };

  closeDev = () => {
    this.setState({ isDev: false });
  };

  closeSiteSwiper = () => {
    this.setState({ isShowSiteSwiper: false });
  };

  bannerSwiperchange() {}

  gobanner(item) {
    // 跳转类型：0无跳转、1跳转内部链接、3跳转外部链接、4跳转小程序、5导向视频号、6导向视频号直播间',
    /**
     *  `link`  ： '跳转链接（跳转外部链接、跳转内部链接）',
        `link_params` ： '跳转链接参数（跳转内部链接）',
        `redirect_appid` ： '外链小程序appid（跳转小程序）',
        `redirect_url` ： '外链小程序url（跳转小程序）',
        `video_no` ： '视频号（导向视频号、导向视频号直播间）',
        `feed_id` ： '视频号feedId（导向视频号）',
    */
    let { id } = item;
    this.GetSiteAddTag(id);

    goJump(item);
  }

  /* 仪器与是否扫码进入逻辑 */
  // 获取已绑定仪器列表
  bindingInstrumentList = async () => {
    Taro.showLoading({
      title: "请求中...",
      mask: true,
    });
    let { data: res } = await InstrumentInfo.bindingInstrumentList();
    Taro.hideLoading();
    if (res.code === 200) {
      this.setState({ instrumentList: res.data });
    } else {
      // 仪器列表失败todo
    }
  };
  // 是否扫码进入小程序
  isSancQrcodeEnter = async () => {
    let instance = Taro.getCurrentInstance();
    let q = instance.router?.params?.q;
    if (q) {
      // 扫码进入强制重新登录
      this.WCUserLogin();
    } else {
      this.initData();
    }
  };
  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);

      this.initPageData();
    } else {
      msg("请求失败,尝试重新请求");
      this.WCUserLogin();
    }
  }
  closeBinding = () => {
    Taro.removeStorageSync("isScan"); // 扫码弹窗显示完后，不需要再判断是否扫码
    Taro.removeStorageSync("serial"); // 扫码弹窗显示完后，删除缓存的扫码序列号
    this.setState({ isVisibleBinding: false });
  };
  confirmBinding = () => {
    let { isExchangeBinding } = this.state;

    if (!isExchangeBinding) {
      // 绑定仪器
      this.bindingInstrument();
    } else {
      // 换绑仪器
      this.exchangeBinding();
    }
  };
  // 根据扫码的序列号获取仪器信息
  getInstrumentInfoBySerial = async () => {
    let url = this.$instance.router?.params?.q || "";
    let isScan = Taro.getStorageSync("isScan"); // 判断是否扫码进入
    let serial = Taro.getStorageSync("serial"); // 扫码可能跳转注册页，所以先缓存
    if (url || isScan) {
      let { data } = await InstrumentInfo.getInstrumentInfoBySerial({
        serial: serial,
      });
      if (data.code === 200) {
        let instrumentInfo = data.data;
        // 更新扫码进入仪器信息
        this.setState({ instrumentInfo: instrumentInfo });

        // 1有效 0无效
        if (instrumentInfo.validStatus === 0) {
          this.setState({ isBindingError: true });
          return;
        }
        // 0已绑定 1未绑定  2已解绑
        if (instrumentInfo.bindingStatus === 0) {
          // 选择仪器有误
          this.setState({
            isBeforeBinding: true,
          });
          return;
        } else if (
          instrumentInfo.bindingStatus === 1 ||
          instrumentInfo.bindingStatus === 2
        ) {
          setTimeout(() => {
            this.isBindingSerial();
          }, 100);
        }
      } else {
        // 获取失败和绑定失败一个弹窗
        this.setState({ isBindingError: true });
      }
    }
  };

  isBindingSerial = async () => {
    Taro.showLoading({
      title: "请求中...",
      mask: true,
    });
    let { instrumentInfo } = this.state;
    let res = await InstrumentInfo.isBindingSerial({
      serial: instrumentInfo.serial,
    });
    console.log("isBindingSerial", res);
    if (res.data.code === 201) {
      // 绑定
      this.setState({ isExchangeBinding: false, isVisibleBinding: true });
    } else if (res.data.code === 202) {
      // 换绑
      this.setState({ isExchangeBinding: true, isVisibleBinding: true });
    }
    Taro.hideLoading();
  };
  // 绑定仪器
  bindingInstrument = async () => {
    Taro.showLoading({
      title: "请求中...",
      mask: true,
    });
    let { instrumentInfo } = this.state;
    let { data } = await InstrumentInfo.binding({
      serial: instrumentInfo.serial,
    });
    Taro.hideLoading();
    this.closeBinding();
    if (data.code === 200) {
      msg("绑定成功");
      setTimeout(() => {
        go("/pages/instrument/intro?id=" + instrumentInfo.id);
      }, 2000);
      return;
    } else if (data.code === 202) {
      // 换绑操作
      this.setState({ isExchangeBinding: true, isVisibleBinding: true });
    } else if (data.code === 201) {
      // 跳转联系客服
      this.setState({ isBindingError: true });
    } else {
      this.setState({ isBindingError: true });
    }
  };

  exchangeBinding = async () => {
    Taro.showLoading({
      title: "请求中...",
      mask: true,
    });
    let { instrumentInfo } = this.state;
    let { data } = await InstrumentInfo.exchangeBinding({
      serial: instrumentInfo.serial,
    });
    console.log("exchangeBinding", data);
    Taro.hideLoading();
    this.closeBinding();
    if (data.code === 200) {
    } else {
      this.closeBinding();
      this.setState({ isBindingError: true });
    }
  };
  // 仪器绑定失败弹窗
  onBindErrorClose = () => {
    Taro.removeStorageSync("isScan"); // 扫码弹窗显示完后，不需要再判断是否扫码
    Taro.removeStorageSync("serial"); // 扫码弹窗显示完后，删除缓存的扫码序列号
    this.setState({ isBindingError: false });
  };
  onBindErrorConfirm = () => {
    this.onBindErrorClose();
    go("/pages/consultant/consultant");
  };
  onBeforeBindClose = () => {
    Taro.removeStorageSync("isScan"); // 扫码弹窗显示完后，不需要再判断是否扫码
    Taro.removeStorageSync("serial"); // 扫码弹窗显示完后，删除缓存的扫码序列号
    this.setState({ isBeforeBinding: false });
  };
  onBeforeBindConfirm = () => {
    this.setState({ isBeforeBinding: false });
  };

  // 跳转仪器介绍页
  goNursing = (item) => {
    console.log("goNursing", item);
    setStorageSync("instrument_item", JSON.stringify(item));
    go("/pages/instrument_clickin_upload/index?id=" + item.id);
    // go("/pages/instrument/intro?id=" + item.id);
  };
  /* 扫码进入逻辑 */

  render() {
    let {
      calendarComplete,
      calendarInComplete,
      currentDate,
      messagecount,
      sitePopupList,
      isShowPrivacyPopup,
      isNotRegister,
      isShowSiteSwiper,
      isDev,

      bannerList,
      bannerCurrent,
      // 绑定弹窗
      isVisibleBinding,
      isBindingError,
      isBeforeBinding,
      isRegisterBoolean,
      isExchangeBinding,
      typeBinding,
      instrumentInfo,
      instrumentList,
    } = this.state;

    return (
      <Block>
        <PopupAlert
          isShow={isNotRegister}
          isClose={true}
          title="提示"
          content="暂未授权注册，请点击注册"
          confirmButtonText="确定"
          textAlgin="center"
          type="1"
          close={this.closeAlert}
          confirm={this.closeAlert}
        />
        <PopupAlert
          isShow={isDev}
          title="提示"
          content="页面正在开发中"
          confirmButtonText="确定"
          textAlgin="center"
          close={this.closeDev}
          confirm={this.closeDev}
        />
        <PopupPrivacy
          isShow={isShowPrivacyPopup}
          closePrivacy={this.closePrivacy}
        />

        <PopupBinding
          type={instrumentInfo.bindingStatus}
          isShow={isVisibleBinding}
          isRegisterBoolean={isRegisterBoolean}
          isExchangeBinding={isExchangeBinding}
          data={instrumentInfo}
          close={this.closeBinding}
          confirm={this.confirmBinding}
        />
        <PopupAlert
          isShow={isBindingError}
          title="提示"
          content={
            <Block>
              <View>序列号信息仍在更新，请联系微信小助理</View>
              <View>协助您绑定仪器</View>
            </Block>
          }
          confirmButtonText="知道了"
          textAlgin="center"
          isClose={false}
          close={this.onBindErrorClose}
          confirm={this.onBindErrorConfirm}
        ></PopupAlert>
        <PopupAlert
          isShow={isBeforeBinding}
          title="提示"
          content="您选择的仪器有误，请重新确认选择"
          confirmButtonText="知道了"
          textAlgin="center"
          isClose={false}
          close={this.onBeforeBindClose}
          confirm={this.onBeforeBindConfirm}
        ></PopupAlert>

        {/* <PopupPrivacyTest
          closePrivacy={this.closePrivacy.bind(this)}
          initData={this.initData.bind(this)}
        ></PopupPrivacyTest> */}

        <PopupSiteSwiper
          isShow={isShowSiteSwiper}
          siteData={sitePopupList}
          size="middle"
          confirmButtonText="确定"
          textAlgin="center"
          close={this.closeSiteSwiper}
          confirm={this.closeSiteSwiper}
        />
        <Navbar
          leftSlot={
            <Block>
              <View
                className="message"
                onClick={this.gourl}
                data-url="/pages/message/message"
              >
                <Image
                  className="message-img"
                  src={require("../../img/index/message.png")}
                  mode="aspectFill"
                />
                {messagecount ? <View className="tip" /> : ""}
              </View>
            </Block>
          }
        />
        <View className="index">
          <View className="date-title" onClick={this.toNursingRecords}>
            <Text className="text">护理记录</Text>
            <Image
              src={require("../../img/index/right.png")}
              style="width: 20rpx;height: 20rpx;"
            />
          </View>
          <View className="bg-while">
            <AtCalendar
              hideArrow={true}
              isSwiper={false}
              currentDate={currentDate}
              complete={calendarComplete}
              incomplete={calendarInComplete}
              maxDate={Date.now()}
              onTimeChange={this.onTimeChange}
            />
          </View>
        </View>
        <View className="infobox5">
          {instrumentList.length > 0 && (
            <Block>
              <View className="nurse_plan_box flex  aitems sb">
                <View className="title">前往护理</View>
                <View
                  className="txt_box flex jcenter aitems"
                  data-url="/pages/instrument/instrument"
                  onClick={this.gourl}
                >
                  <Image
                    className="right_icon"
                    src={require("../../img/black-add.png")}
                    mode="aspectFill"
                  />
                  <View className="txt">添加新设备</View>
                </View>
              </View>
              <View style="overflow-x: auto;">
                <View className="device_list flex">
                  {instrumentList.map((item, index) => {
                    if (item.status === 0) {
                      return (
                        <View
                          key={"instrumentList" + index}
                          className="device_item"
                          onClick={this.goNursing.bind(this, item)}
                        >
                          <Image
                            className="banner_img"
                            src={item.banner}
                            mode="aspectFill"
                          />
                          <View className="device_name ellipsis1">
                            {item.name}
                          </View>
                        </View>
                      );
                    }
                  })}
                </View>
              </View>
            </Block>
          )}
          {instrumentList.length === 0 && (
            <Block>
              <View className="nurse_plan_box flex aitems sb">
                <View className="title">前往护理</View>
              </View>
              <View className="add_device flex jcenter aitems bg-while">
                <View className="add_device_btn">
                  <View className="txt_box flex jcenter aitems">
                    <View
                      className="at-icon at-icon-add"
                      style="color: #fff;font-size: 30rpx;"
                    ></View>
                    <View className="txt" onClick={this.addNewDevice}>
                      添加新设备
                    </View>
                  </View>
                </View>
                <View className="tips">您暂时还没有绑定任何设备</View>
              </View>
            </Block>
          )}
        </View>

        <View className="infobox3">
          <Swiper
            autoplay={true}
            onAnimationFinish={this.bannerSwiperchange.bind(this)}
            current={bannerCurrent}
          >
            {bannerList.map((item, index) => {
              return (
                <SwiperItem
                  key={"banner_" + index}
                  onClick={this.gobanner.bind(this, item)}
                >
                  <Image style="width:100%;height:100%" src={item.fileUrl} />
                </SwiperItem>
              );
            })}
          </Swiper>
        </View>
        <View style="height:200rpx"></View>
      </Block>
    );
  }
}

const mapStateToProps = (state) => ({
  background: state.navigation.background,
  mobile: state.userInfo.mobile,
  isShowIndexFlag: state.globalStore.isShowIndexFlag,
});
const mapDispatchToProps = (dispatch) => ({
  userRefresh(data) {
    dispatch(userRefresh(data));
  },
  tokenRefresh(data) {
    dispatch(tokenRefresh(data));
  },
  setIndexFlag(data) {
    dispatch(setIndexFlag(data));
  },
});
export default connect(mapStateToProps, mapDispatchToProps)(Index);
