import { MpSplashDetail, WCUserLogin } from "../../utils/Interface";
import { Component, PropsWithChildren, useEffect, useState } from "react";
import dayjs from "dayjs";
import Taro from "@tarojs/taro";
import {
  Block,
  View,
  Text,
  Image,
  Button,
  ScrollView,
} from "@tarojs/components";

/** 自定义组件 **/
import Navbar from "../../components/navbar/navbar";
/** 自定义组件 **/

// import { PullToRefresh, IPullToRefreshProps } from "@antmjs/vantui";
import { Loading } from "@antmjs/vantui";
import "@antmjs/vantui/es/loading/index.css";

import { GetHasBeenRead, GetMessageList } from "../../utils/Interface";
import { goJump } from "../../utils/traoAPI";

import "./message.less";

export default class Message extends Component<any, any> {
  constructor(props) {
    super(props);
    this.state = {
      name: "message",
      list: [],
      pageNum: 1,
      pageSize: 10,
      total: 0,
      scrollTop: 0,
      isBottom: false, // 是否触底
      start_p: {},
      scrollY: true,
      dargState: 0, //刷新状态 0不作操做 1刷新 -1加载更多
    };
  }

  async onLoad() {
    this.initData(); // 每次进入清空所有消息
  }
  componentDidMount() {}

  componentWillUnmount() {}

  componentDidShow() {}

  componentDidHide() {}

  async initData() {
    this.GetHasBeenRead();
    this.GetMessageList();
  }

  // 跳转
  godetail = (item) => {
    console.log("godetail", item);
    goJump(item);
  };

  // 获取消息分页
  GetMessageList = async () => {
    let { list } = this.state;
    let res = await GetMessageList({
      pageNum: this.state.pageNum,
      pageSize: this.state.pageSize,
    });
    if (res.data.code === 200) {
      if (res.data.rows.length) {
        let data = res.data.rows.map((item: any) => {
          item.createTime = item.createTime
            ? dayjs(item.createTime).format("YYYY-MM-DD")
            : "";
          return item;
        });

        let newList = [].concat(list, data);
        setTimeout(() => {
          this.setState({ list: newList, dargState: 0, total: res.data.total });
        }, 400);
      }
    }
  };

  // 清除所有消息数
  GetHasBeenRead = async () => {
    let res = await GetHasBeenRead();
    if (res.data.code === 200) {
      Taro.setStorageSync("messageCount", res.data.data);
    }
  };

  /*** 上拉加载 ***/
  reduction = () => {
    //还原初始设置
    // const time = 0.5;
    this.setState({
      scrollY: true,
    });
  };
  touchStart = (e) => {
    this.setState({
      start_p: e.touches[0],
    });
  };
  touchmove = (e) => {
    let move_p = e.touches[0], //移动时的位置
      deviationX = 0.3, //左右偏移量(超过这个偏移量不执行下拉操做)
      deviationY = 70, //拉动长度（低于这个值的时候不执行）
      maxY = 100; //拉动的最大高度

    let start_x = this.state.start_p.clientX,
      start_y = this.state.start_p.clientY,
      move_x = move_p.clientX,
      move_y = move_p.clientY;

    //获得偏移数值
    let dev = Math.abs(move_x - start_x) / Math.abs(move_y - start_y);
    if (dev < deviationX) {
      //当偏移数值大于设置的偏移数值时则不执行操做
      let pY = Math.abs(move_y - start_y) / 3.5; //拖动倍率（使拖动的时候有粘滞的感受--试了不少次 这个倍率恰好）
      if (move_y - start_y > 0) {
        //下拉操做
        if (pY >= deviationY) {
          // this.setState({ dargState: 1, downText: "释放刷新" });
        } else {
          // this.setState({ dargState: 0, downText: "下拉刷新" });
        }
        if (pY >= maxY) {
          pY = maxY;
        }
        this.setState({
          scrollY: false, //拖动的时候禁用
        });
      }
      if (start_y - (move_y + 100) > 0) {
        //上拉操做
        // console.log("上拉操做");
        if (pY >= deviationY) {
          this.setState({ dargState: -1 });
        }
      }
    }
  };
  pull = () => {
    //上拉
    console.log("上拉");
    let { list, total, pageNum, dargState } = this.state;
    if (dargState === -1) {
      if (list.length < total) {
        this.setState({ pageNum: pageNum + 1 });
        setTimeout(() => {
          this.GetMessageList();
        }, 100);
      }
    }
  };
  down = () => {
    //下拉
    console.log("下拉");
    // this.props.onDown()
  };
  ScrollToUpper = () => {
    //滚动到顶部事件
    console.log("滚动到顶部事件");
    // this.props.Upper()
  };
  ScrollToLower = () => {
    //滚动到底部事件
    console.log("滚动到底部事件");
    // this.props.Lower()
  };
  touchEnd = (e) => {
    if (this.state.dargState === 1) {
      this.down();
    } else if (this.state.dargState === -1) {
      this.pull();
    }
    // this.reduction();
  };
  /*** 上拉加载 ***/

  // onPullDownRefresh = (e) => {
  //   console.log("onPullDownRefresh", e);
  // };

  render() {
    let { total, list, dargState } = this.state;
    return (
      <Block>
        <Navbar isBack={true} titleSlot="消息中心"></Navbar>

        <View style="padding-top: 13rpx">
          <ScrollView
            onTouchMove={this.touchmove}
            onTouchEnd={this.touchEnd}
            onTouchStart={this.touchStart}
            onScrollToUpper={this.ScrollToUpper}
            onScrollToLower={this.ScrollToLower}
            className="dragUpdata"
            scrollY={this.state.scrollY}
            scrollWithAnimation
          >
            <View>
              <View className="message">
                <View style="height:13rpx"></View>
                {list.map((item: any) => {
                  return (
                    <View
                      className="infobox1"
                      onClick={this.godetail.bind(this, item)}
                      key={item.id}
                    >
                      <View className="info1 flex aitems sb">
                        <View className="left flex aitems">
                          <View className="icon">
                            <Image
                              src={require("../../img/logos.png")}
                              mode="aspectFill"
                            />
                          </View>
                          <View className="tip1">系统通知</View>
                        </View>
                        <View className="right">{item.createTime}</View>
                      </View>
                      <View className="info2">
                        <View className="content">
                          <Text>
                            [{item.titile}]: {item.content ? item.content : ""}
                          </Text>
                        </View>
                      </View>
                    </View>
                  );
                })}
              </View>
              <View style="height: 20rpx"></View>
            </View>
          </ScrollView>

          {list.length > 0 && list.length < total && (
            <View className="upDragBox">
              {dargState === 0 ? (
                <Text style="color: #666">上拉加载更多</Text>
              ) : (
                <Loading size="24px">加载中...</Loading>
              )}
            </View>
          )}

          {list.length > 0 && list.length === total && (
            <View style="margin: 10rpx 0;text-align: center;">
              <Text style="color: #666;">已到底部</Text>
            </View>
          )}
        </View>

        <View style="height: 100rpx;"></View>

        {list.length == 0 && <View className="nodata">暂无相关消息</View>}
      </Block>
    );
  }
}
