import { RRule } from "rrule";
import {
  getDynamicList,
  updateMeetingTask,
  getHomeUserSchedule1
} from "../../api/request";
import {
  getDateMap,
  getExcludeDate,
  getNextDateList,
  getWeekNumber,
  getBlankList,
  toLocaleDateString
} from "./schedule.js";
import {
  getFormatDate,
  throttle,
  padZero,
  getCreateShowTime,
  isJSON,
  removeHtml
} from "../../utils/utils";
import { checkFullScren } from "../../utils/checkFullScren";
import create from "dd-store";
import pageStore from '../meetingDetail/store';
import { version } from '../../config';
// const webSocket = require('../../utils/websocket.js');
import { websocketUrl } from '../../config';

const currentDate = new Date();
const minYear = currentDate.getFullYear();
const maxYear = currentDate.getFullYear() + 1;
let DateMap = getDateMap(minYear, maxYear);
const weekList = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
let maxClickCount = 5;

const uuid = Math.random().toString(36).substr(2);
create.Page({
  store: pageStore,
  data: {
    userInfo: {
      username: '明我智会'
    },
    actionLog: {
      "comment_reply": "添加了评论",
      "file_create": "上传了文件",
      "notes_create": "添加了笔记",
      "notes_modify": "更新了笔记",
      "task_create": "添加了任务",
      "task_modify_success": "更新了任务",
      "meeting_create": "添加了会议",
    },
    relatedAppPlatform: null,
    sign: "",
    refresh: false,
    $data: null,
    iconDay: currentDate.getDate(),
    scheduleList: [],
    todayStr: '',
    currentData: toLocaleDateString(currentDate),
    currentDataIndex: 0,
    offset: "stop",
    show: false,
    loading: true,
    traceTime: "1970-03-01 00:00:00",
    isStopBodyScroll: false,
    dynamicList: [],
    current: 1,
    pages: 1,
    listLoading: true,
    isIPX: checkFullScren(),
    more: false,
    moreLoading: false
  },
  scrollTop: 0,
  pageSize: 10,
  totalPages: 1,
  currentPage: 1,
  firstPage: 1,
  scheduleList: [],
  timer: null,
  isNeverShowSchedulePage: true,
  isLoaded: false,
  blankDataLength: 0,
  blankDataLengthAfter: 0,
  minYear: minYear,
  maxYear: maxYear,
  todayIndex: 0,
  onShow() {
    //刷新动态列表
    console.log(this.$store.data.isIndexAffairListNeedUpdate)
    if (this.$store.data.isIndexAffairListNeedUpdate) {
      this.getPages(1);
      this.$store.data.isIndexAffairListNeedUpdate = false;
      this.update();
    }
    //开启一个定时器
    this.timer = setInterval(() => {
      this.getData();
    }, 30000);

    // 设置标题
    dd.setNavigationBar({
      title: this.$store.data.tabBarIndex == 1 ? '安排' : '动态'
    });

    //定位
    if (this.isNeverShowSchedulePage) {
      if (this.$store.data.tabBarIndex == 1) {
        this.backToToday('first')
        this.isNeverShowSchedulePage = false;
      }
    }
    this.connect_start();


    //webSocket.connectSocket();
    //webSocket.onSocketMessageCallback = this.onSocketMessageCallback.bind(this);
  },
  // socket收到的信息回调
  onSocketMessageCallback(event) {
    // 返回一个JSON字符串
    if (isJSON(event)) {
      const dataFromServer = JSON.parse(event);
      if (dataFromServer.reload.indexOf('comment_') !== -1) {
        this.getPages();
      }
    }
  },
  onLoad(query) {

    if (query && query.sn) {
      this.setData({
        listLoading: false
      });
      dd.navigateTo({ url: `./../createMeeting/createMeeting?sn=${query.sn}` });
    } else if (query && JSON.stringify(query) !== "{}" && !query.sn) {
      this.setData({
        listLoading: false
      });
      const scheduleItem = JSON.parse(Object.keys(query)[0].split("=")[1]);
      dd.navigateTo({
        url: `./../meetingDetail/meetingDetail?scheduleItem=${encodeURIComponent(
          JSON.stringify(scheduleItem)
        )}`
      });
    }
    this.isNeverShowSchedulePage = true;
    //获取动态列表s
    this.getPages(1);
    //获取日程列表
    this.getData();

    this.$store.modifyOnceMeetingContent = async (content) => {
      await this.modifyOnceMeetingContent(content);
    }
    this.$store.modifyErpeatMeeting = async () => {
      await this.modifyErpeatMeeting()
    }
    this.$store.addOnceMeeting = async (content) => {
      await this.addOnceMeeting(content)
    }
    this.update();


    // 注意: 回调方法的注册在整个小程序启动阶段只要做一次,调多次会有多次回调
    dd.onSocketOpen((res) => {
      console.log('连接已打开!');

      this.socketTimer = setInterval(() => {
        dd.sendSocketMessage({
          data: 'heartbeat', // 需要发送的内容
          success: (res) => {
            console.log('数据发送!' + 'heartbeat');
          },
        });
      }, 25000)

    });

    dd.onSocketError(function (res) {
      console.log('WebSocket 连接打开失败,请检查!' + res);
    });

    // 注意: 回调方法的注册在整个小程序启动阶段只要做一次,调多次会有多次回调
    dd.onSocketMessage((res) => {
      console.log(res)
      this.onSocketMessageCallback(res.data)
    });

    if (dd.getStorageSync({ key: 'userInfo' }).data) {
      this.setData({
        userInfo: dd.getStorageSync({ key: 'userInfo' }).data
      });
    }
    if (getApp().globalData.userInfo) {
      this.setData({
        userInfo: JSON.parse(getApp().globalData.userInfo)
      });
    }

  },
  connect_start() {
    const userId = dd.getStorageSync({ key: 'mwUserId' }).data;
    if (!userId) {
      return
    }
    dd.connectSocket({
      url: `${websocketUrl}/meet-websocket/websocket/${userId}/${uuid}`,

      success: (res) => {

      },
      fail: () => {
        dd.showToast({
          content: 'fail', // 文字内容
        });
      }
    });
  },
  //添加单次会议
  async addOnceMeeting(content) {
    await this.getData(true);
    this.getScheduleList(content, "once");
    this.setData({
      scheduleList: this.scheduleList.slice(
        this.firstPage * this.pageSize,
        this.currentPage * this.pageSize
      ),
      loading: false
    });
  },
  //修改重复会议
  async modifyErpeatMeeting() {
    await this.getData();
  },
  //修改会议,除单次会议修改成重复会议
  async modifyOnceMeetingContent(content) {
    await this.getData(true);
    //修改数据源 
    for (let i = 0; i < this.data.scheduleList.length; i++) {
      if (typeof this.data.scheduleList[i].value !== 'string') {
        if (this.data.scheduleList[i].value.id === content.id) {
          this.setData({
            [`scheduleList[${i}].value`]: { ...this.data.scheduleList[i].value, ...content }
          })
          break;
        }
      }
    }
    for (let i = 0; i < this.scheduleList.length; i++) {
      if (typeof this.scheduleList[i].value !== 'string') {
        if (this.scheduleList[i].value.id === content.id) {
          this.scheduleList[i].value = { ...this.scheduleList[i].value, ...content };
          break;
        }
      }
    }
  },
  async getData(onlyChangeSign) {
    await getHomeUserSchedule1({
      startTime: "2020-01-01 00:00:00",
      endTime: "2025-12-30 23:59:59"
    }).then(res => {

      //第一次加载
      if (!this.isLoaded) {
        console.log('第一次加载')
        this.getScheduleList(res.data.data);
        this.getPagination(this.scheduleList);
        this.setData({
          scheduleList: this.scheduleList.slice(
            this.firstPage * this.pageSize,
            this.currentPage * this.pageSize
          ),
          sign: res.data.data.sign,
          loading: false
        });
        this.isLoaded = true;
        return;
      }

      //只修改sign, 防止30S后刷新页面
      if (onlyChangeSign) {
        console.log('只修改sign')
        this.setData({
          sign: res.data.data.sign
        })
        return
      }

      //是否刷新页面
      if (res.data.data.sign !== this.data.sign) {
        console.log('刷新页面')
        DateMap = getDateMap(this.minYear, this.maxYear);
        this.getScheduleList(res.data.data);
        this.totalPages = Math.ceil(this.scheduleList.length / this.pageSize);
        this.setData({
          scheduleList: this.scheduleList.slice(
            this.firstPage * this.pageSize,
            this.currentPage * this.pageSize
          ),
          sign: res.data.data.sign
        });
      }
    }).catch(err => {
      if (err && err.refresh) {
        this.setData({
          loading: false,
          refresh: true,
          refreshCode: err.code
        });
      }
    });
  },
  onHide() {
    dd.closeSocket();
    clearInterval(this.timer);
    this.socketTimer && clearInterval(this.socketTimer);
    this.timer = null;
    this.socketTimer = null;
  },
  onUload() {
    dd.closeSocket();
  },
  refresh() {
    //重置数据
    DateMap = getDateMap(this.minYear, this.maxYear);
    this.isNeverShowSchedulePage = true;
    this.isLoaded = false;
    //定位到今天,防止上面的不生效
    this.backToToday('first')
    this.onLoad();
  },
  getPages(current, callBack) {
    getDynamicList({ before: 'yes' })
      .then(res => {
        if (!res.data.data || res.data.data.length === 0) {
          if (res.data.msg === 'yes') {
            getDynamicList({ before: 'no' }).then(res => {
              if (!res.data.data || res.data.data.length === 0) {
                this.setData({
                  listLoading: false,
                  more: false,
                  dynamicList: []
                });
              } else {
                const dynamicList = res.data.data.map((item, index) => {
                  for (let i = 0; i < item.commentListDataModelList.length; i++) {
                    let itemData = item.commentListDataModelList[i];
                    if (itemData.updateTime) {
                      itemData.updateTime = getCreateShowTime(itemData.updateTime);
                    }
                    if (itemData.notes) {
                      itemData.notes = removeHtml(itemData.notes)
                    }

                  }
                  return item;
                });
                this.setData({
                  dynamicList,
                  listLoading: false,
                  more: false,
                });
                if (callBack) {
                  callBack();
                }
              }
            })
          } else {
            this.setData({
              listLoading: false,
              more: false,
              dynamicList: []
            });
          }
          return;
        }

        const dynamicList = res.data.data.map((item, index) => {
          for (let i = 0; i < item.commentListDataModelList.length; i++) {
            let itemData = item.commentListDataModelList[i];
            if (itemData.updateTime) {
              itemData.updateTime = getCreateShowTime(itemData.updateTime);
            }
            if (itemData.notes) {
              itemData.notes = removeHtml(itemData.notes)
            }
          }
          return item;
        });
        const more = res.data.msg === 'yes'
        this.setData({
          dynamicList,
          listLoading: false,
          more,
        });
        if (callBack) {
          callBack();
        }
      })
      .catch(err => {
        if (err && err.refresh) {
          this.setData({
            refresh: true
          });
        }
      });
  },
  getPagesMore(current, callBack) {
    this.setData({
      moreLoading: true,
    });
    getDynamicList({ before: 'no' })
      .then(res => {
        if (!res.data.data || res.data.data.length === 0) {
          return
        }

        let dynamicList = this.data.dynamicList.concat(res.data.data.map((item, index) => {
          for (let i = 0; i < item.commentListDataModelList.length; i++) {
            let itemData = item.commentListDataModelList[i];
            if (itemData.updateTime) {
              itemData.updateTime = getCreateShowTime(itemData.updateTime);
            }
            if (itemData.notes) {
              itemData.notes = removeHtml(itemData.notes)
            }
          }
          return item;
        }))
        dynamicList = dynamicList.filter((el, index) => {
          if (dynamicList.findIndex(ele => ele.meetingId === el.meetingId) === index) {
            return true;
          }
        });
        this.setData({
          dynamicList,
          moreLoading: false,
          more: false
        });
        if (callBack) {
          callBack();
        }
      })
      .catch(err => {
        if (err && err.refresh) {
          this.setData({
            refresh: true
          });
        }
      });
  },
  //动态修改状态
  onChangeTaskStatusOnList(e) {
    const data = {
      meetingId: e.meetingId,
      platform: 'dingTalk',
      taskModifyModel: {
        commentId: e.commentId,
        processState: e.status,
        taskId: e.taskId
      }
    };
    updateMeetingTask(data).then(res => {
      if (res.data.code === 0) {
        let dataIndex1 = "";
        let dataIndex2 = "";
        this.data.dynamicList.forEach((item, index) => {
          if (item.meetingId === e.meetingId) {
            dataIndex1 = index;
            item.commentListDataModelList.forEach((it, index2) => {
              if (it.meetingTaskSimpleViewModel && it.meetingTaskSimpleViewModel.taskId == e.taskId) {
                dataIndex2 = index2;
              }
            });
          }
        });
        const statusKey = `dynamicList[${dataIndex1}].commentListDataModelList[${dataIndex2}].meetingTaskSimpleViewModel.processState`;
        this.setData({
          [statusKey]: e.status
        });
      }
    });
  },
  //日程获取分页数据
  getPagination(scheduleList = []) {
    this.totalPages = Math.ceil(scheduleList.length / this.pageSize);
    for (let i = 0; i < scheduleList.length; i++) {
      if (scheduleList[i].dateStr == toLocaleDateString(currentDate)) {
        const centerPage = Math.floor(i / this.pageSize);
        this.todayIndex = i;
        this.setData({
          currentDataIndex: i
        });
        // firstPage转为4的倍数,一次下拉加载40条
        const firstPage = centerPage - 2;
        this.firstPage =
          firstPage % 4 == 0 ? firstPage : firstPage - (firstPage % 4);
        this.currentPage = centerPage + 2;
        break;
      }
    }
  },

  //生成DateMap值
  setDateMapValue(startTime, endTime, item, type) {
    const pushItem = {
      endTime: endTime,
      startTime: startTime,
      planDate: getFormatDate(startTime, "yyyyMMdd", "-"),
      thisDayStartTime: getFormatDate(startTime, "HH:mm"),
      thisDayEndTime: getFormatDate(endTime, "HH:mm"),
      confirmAttendance: item.confirmAttendance,
      title: item.title,
      id: item.id,
      isBeOverdue: currentDate.getTime() > endTime.getTime() ? true : false
    };
    //模板会议id为空
    if (type == "repeat") {
      pushItem.scheduleTemplateId = item.id;
      pushItem.id = "";
    }

    // 如果是跨天会议,需要手动在起始天以后的其他天 添加会议日程
    const nextDateList = getNextDateList(startTime, endTime); //返回日期包括起始天
    if (nextDateList.length > 1) {
      pushItem.isDaySpan = true;
      pushItem.isFewDays = 1;
      pushItem.isfirstDayOrEndDay = "0"; // 0 第一天,1中间的天,2结束的天
      pushItem.duration = nextDateList.length;
      for (let i = 1; i < nextDateList.length; i++) {
        if (DateMap.has(nextDateList[i])) {
          DateMap.get(nextDateList[i]).push({
            ...pushItem,
            isFewDays: i + 1,
            isfirstDayOrEndDay: nextDateList.length - 1 === i ? "2" : "1" // 0 第一天,1中间的天,2结束的天
          });
        }
      }
    }
    if (DateMap.has(toLocaleDateString(startTime))) {
      DateMap.get(toLocaleDateString(startTime)).push(pushItem);
    }
  },
  // 根据接口返回数据生成填充DateMap
  setDateMapByResponse(response) {
    if (response) {
      // 处理单次会议 scheduleList
      const scheduleListWithTemplateId = [];
      response.scheduleList.forEach(item => {
        // 有scheduleTemplateId则是虚拟会议转成实体会议,需要替换rrule生成的模板会议
        if (item.scheduleTemplateId) {
          scheduleListWithTemplateId.push(item);
        } else {
          this.setDateMapValue(
            new Date(item.startTime.replace(/-/g, "/")),
            new Date(item.endTime.replace(/-/g, "/")),
            item
          );
        }
      });

      // 处理重复会议 templateList
      response.templateList.forEach(item => {
        //日程会议
        const itemScheduleList = scheduleListWithTemplateId.filter(
          it => it.scheduleTemplateId == item.id
        );
        // 生成rrules规则
        const initialTimeList = item.initialTime.split("-");
        const startTimeList = item.startTime.split(":");
        const DTSTART = `${initialTimeList[0]}${initialTimeList[1]}${initialTimeList[2]}T${startTimeList[0]}${startTimeList[1]}00Z`;
        let rule = { all: () => [] };
        if (item.recurrenceModel.recurrenceRule) {
          rule = RRule.fromString(
            `${item.recurrenceModel.recurrenceRule};DTSTART=${DTSTART}`
          );
        }
        const setDateMapValueAll = (startTime, endTime, item) => {
          //如果有日程会议则用日程会议替换
          let replaceItem = [];
          if (itemScheduleList.length > 0) {
            replaceItem = itemScheduleList.filter(
              it => it.planDate == getFormatDate(startTime, "yyyyMMdd", "-")
            );
          }
          if (replaceItem.length > 0) {
            this.setDateMapValue(
              new Date(replaceItem[0].startTime.replace(/-/g, "/")),
              new Date(replaceItem[0].endTime.replace(/-/g, "/")),
              replaceItem[0]
            );
          } else {
            this.setDateMapValue(startTime, endTime, item, "repeat");
          }
        };
        // 需要剔除某一天
        if (item.excludePlanDates) {

          const excludeData = getExcludeDate(item.excludePlanDates.split(","));
          rule.all().forEach(startTime => {
            //修正时间(时间有8小时时差)
            startTime.setHours(startTime.getHours() - 8);
            // 生成结束时间
            const endTime = new Date(startTime);
            endTime.setMinutes(
              endTime.getMinutes() + item.recurrenceModel.duration
            );
            // 剔除规则: 时间小于futureTime 时间不在单个排除日期里面
            if (
              startTime.getTime() < excludeData.minFutureTime &&
              !excludeData.excludeDateList.includes(
                getFormatDate(startTime, "yyyyMMdd", "-")
              )
            ) {
              setDateMapValueAll(startTime, endTime, item);
            }
          });
        }
        // 正常生成数据
        else {
          rule.all().forEach(startTime => {
            //修正时间(时间有8小时时差)
            startTime.setHours(startTime.getHours() - 8);
            // 生成结束时间
            const endTime = new Date(startTime);
            endTime.setMinutes(
              endTime.getMinutes() + item.recurrenceModel.duration
            );
            setDateMapValueAll(startTime, endTime, item);
          });
        }
      });
    }
  },
  //日程数据
  getScheduleList(response, type) {
    if (type == "once") {
      this.setDateMapValue(response.startTime, response.endTime, response);
    } else {
      this.setDateMapByResponse(response);
    }
    // 取出DateMap的value值平铺到DateList
    const DateList = [];
    DateMap.forEach(function (value, key) {
      const keyDate = new Date(key);
      const year = keyDate.getFullYear();
      const month = keyDate.getMonth();
      const date = keyDate.getDate();
      const day = keyDate.getDay();

      // 生成年
      if (month === 0 && date === 1) {
        DateList.push({
          type: "year",
          value: year,
          dateStr: `${year}`
        });
      }
      //生成月
      if (date === 1) {
        DateList.push({
          type: "month",
          value: month + 1,
          dateStr: `${year}/${month + 1}`
        });
      }
      //生成周
      if (day === 0) {
        const rangeDate = new Date(year, month, date + 6);
        const rangeMonth2 = new Date(rangeDate).getMonth();
        const rangeDay2 = new Date(rangeDate).getDate();
        DateList.push({
          type: "week",
          value: `第${getWeekNumber(year, month, date)}周,${month +
            1}月${date}日 - ${
            rangeMonth2 == month ? "" : rangeMonth2 + 1 + "月"
            }${rangeDay2}日`,
          dateStr: `${year}/${month + 1}/${date}-week`
        });
      }
      // 有日程长度
      if (value.length !== 0) {
        value.sort(function (a, b) {
          return a.startTime.getTime() - b.startTime.getTime();
        });
        value.forEach((item, index) => {
          if (index === 0) {
            DateList.push({
              type: key !== toLocaleDateString(currentDate) ? "day" : "today",
              week: weekList[day],
              hasDateLabel: padZero(date),
              value: item,
              dateStr: `${key}`
            });
          } else {
            DateList.push({
              type: "day",
              value: item,
              dateStr: `${key}/${item.id || item.scheduleTemplateId}`
            });
          }
        });
      } else if (
        value.length === 0 &&
        key === toLocaleDateString(currentDate)
      ) {
        DateList.push({
          type: "thisday",
          value: "",
          hasDateLabel: padZero(date),
          week: weekList[day],
          dateStr: key
        });
      }
    });
    this.scheduleList = DateList;
  },
  //日程上拉加载
  lower() {
    if (this.currentPage < this.totalPages) {
      this.currentPage++;
      this.setData({
        scheduleList: this.scheduleList.slice(
          this.firstPage * this.pageSize,
          this.currentPage * this.pageSize
        )
      });
    } else {
      //超出加载一年的数据
      this.maxYear++;
      const yearData = getBlankList(this.maxYear);
      this.blankDataLengthAfter += yearData.length;
      this.scheduleList.push(...yearData);
      this.setData({
        scheduleList: this.scheduleList.slice(this.firstPage * this.pageSize)
      });
    }
  },
  onPullDownRefresh() {
    if (this.$store.data.tabBarIndex == "0") {
      this.getPages(1);
      dd.stopPullDownRefresh();
      return;
    }
    //日程页面到顶部的时候才下拉加载数据,否则定位距离太长
    if (this.$store.data.tabBarIndex == "1" && this.scrollTop !== 0) {
      dd.stopPullDownRefresh();
      return;
    }
    // const todayStr = this.data.scheduleList[0].dateStr;
    if (this.firstPage > 0) {
      this.firstPage -= 4;
      this.currentPage -= 4;
      this.setData(
        {
          todayStr: "",
          scheduleList: this.scheduleList.slice(
            this.firstPage * this.pageSize,
            this.currentPage * this.pageSize
          )
        },
        () => {
          this.setData({
            todayStr: this.data.scheduleList[this.pageSize * 4 - 1].dateStr
          });
          dd.stopPullDownRefresh();
        }
      );
    } else {
      this.minYear--;
      const yearData = getBlankList(this.minYear);
      this.blankDataLength += yearData.length;
      this.todayIndex += yearData.length;
      this.scheduleList.unshift(...yearData);
      this.totalPages = Math.ceil(this.scheduleList.length / this.pageSize);
      this.currentPage = Math.floor((yearData.length * 2) / this.pageSize);
      this.setData(
        {
          todayStr: "",
          scheduleList: this.scheduleList.slice(0, yearData.length * 2)
        },
        () => {
          this.setData({
            //加载一年的数据重定位可能会有点问题,重置一下
            currentData: this.scheduleList[yearData.length - 1].dateStr,
            currentDataIndex: yearData.length - 1,
            todayStr: this.scheduleList[yearData.length - 1].dateStr
          });
          dd.stopPullDownRefresh();
        }
      );
    }
  },
  scroll(e) {
    // 一次性惯性拉到顶速度跟不上,重置
    if (e.detail.scrollTop == 0) {
      this.setData({
        currentData: this.data.scheduleList[0].dateStr,
        currentDataIndex: 0
      });
    }
    //每次计算偏移值
    const offset = this.getScrollOffset(e.detail.scrollTop);
    dd.createSelectorQuery()
      .selectAll(".li")
      .boundingClientRect()
      .exec(rect => {
        //日程的上下箭头
        if (rect[0]) {
          this.setScrollOffset(rect);
        }
        if (offset == "next") {
          for (let i = this.data.currentDataIndex; i < rect[0].length; i++) {
            if (rect[0][i] && rect[0][i].top > 0) {
              if (
                this.data.scheduleList[i].dateStr.split("/")[1] !==
                this.data.currentData.split("/")[1]
              ) {
                this.setData({
                  currentData: this.data.scheduleList[i].dateStr,
                  currentDataIndex: i
                });
              }
              break;
            }
          }
        } else if (offset == "before") {
          let i = Math.min(
            this.data.currentDataIndex,
            this.data.scheduleList.length - 1
          );
          for (; i > 0; i--) {
            if (rect[0][i] && rect[0][i].top < 50) {
              if (
                this.data.scheduleList[i].dateStr.split("/")[1] !==
                this.data.currentData.split("/")[1]
              ) {
                this.setData({
                  currentData: this.data.scheduleList[i].dateStr,
                  currentDataIndex: i
                });
              }
              break;
            }
          }
        }
      });
  },
  //判断滚动方向
  getScrollOffset(scrollTop) {
    let offset = "stop";
    if (scrollTop > this.scrollTop) {
      //向下滚动
      offset = "next";
    } else {
      //向上滚动
      offset = "before";
    }
    this.scrollTop = scrollTop;
    return offset;
  },
  setScrollOffset(rect) {
    if (rect[0][this.todayIndex]) {
      if (
        rect[0][this.todayIndex].top <= 60 &&
        rect[0][this.todayIndex].top >= 30
      ) {
        if (this.data.offset !== "stop") {
          this.setData({ offset: "stop" });
        }
      } else if (rect[0][this.todayIndex].top < 60) {
        if (this.data.offset !== "next") {
          this.setData({ offset: "next" });
        }
      } else if (rect[0][this.todayIndex].top > 30) {
        if (this.data.offset !== "before") {
          this.setData({ offset: "before" });
        }
      }
    } else {
      if (this.data.offset !== "before") {
        this.setData({ offset: "before" });
      }
    }
  },
  closePop() {
    this.setData({
      show: false
    });
  },
  changesidebar() {
    this.setData({
      show: true
    });
  },
  createMeeting() {
    dd.navigateTo({ url: "./../createMeeting/createMeeting" });
  },
  nextDetail: throttle(function (e) {
    const { item, groupId } = e.target.dataset;
    const scheduleItem = { groupId, scheduleId: item.meetingId || item.id, scheduleTemplateId: item.scheduleTemplateId, planDate: item.planDate }
    dd.navigateTo({
      url: `./../meetingDetail/meetingDetail?scheduleItem=${encodeURIComponent(JSON.stringify(scheduleItem))}`
    });
  }, 1000),
  backToToday(type) {
    if (!type) {
      //如果当前的日期还没加载出来点击无效
      const isFind = this.data.scheduleList.findIndex(
        it => it.dateStr == toLocaleDateString(currentDate)
      );
      if (isFind == -1) {
        //去掉头部空数据
        if (this.minYear < minYear) {
          this.scheduleList.splice(0, this.blankDataLength);
          this.minYear = minYear;
        }
        //去掉尾部数据
        if (this.maxYear > maxYear) {
          this.scheduleList.splice(-this.blankDataLengthAfter);
          this.maxYear = maxYear;
        }
        this.getPagination(this.scheduleList);
        this.setData({
          scheduleList: this.scheduleList.slice(
            this.firstPage * this.pageSize,
            this.currentPage * this.pageSize
          )
        });
      }
    }
    //需要先清空todayStr再设置才有效
    this.setData(
      {
        todayStr: ""
      },
      () => {
        this.setData({
          todayStr: toLocaleDateString(currentDate)
        });
      }
    );
  },
  // 修改tabBar
  changeTabBar(e) {
    const { tabbar, title } = e.currentTarget.dataset;
    const lastTimeTabBarIndex = this.$store.data.tabBarIndex;
    this.$store.data.tabBarIndex = tabbar;
    this.update();

    dd.setNavigationBar({
      title: title
    });

    if (this.isNeverShowSchedulePage) {
      this.backToToday("first");
      this.isNeverShowSchedulePage = false;
    }
    if (lastTimeTabBarIndex == tabbar) {
      if (tabbar == "1") {
        this.backToToday();
      }
    } else {
      //切换到动态页面时,日程重置成当前日期
      if (tabbar == "0") {
        this.lastOffset = this.data.offset;
        setTimeout(() => {
          this.setData({
            offset: "stop"
          });
        }, 500)
      } else if (!this.isNeverShowSchedulePage) {
        this.setData({
          offset: this.lastOffset
        });
      }
    }
  },

  onOpenSiderBar() {
    this.setData({
      popupShow: true
    })
  },
  closePopup() {
    this.setData({
      popupShow: false
    })
  },
  onTitleClick() {
    maxClickCount--;
    if (maxClickCount == 0) {
      dd.alert({
        content: version
      });
      maxClickCount = 5;
    }
  }
});