// pages/vehicleMonitoring/failureAlert/failureAlert.ts
import { getAction } from '../../../api/base';

Page({
  /**
   * 页面的初始数据
   */
  data: {
    tabActive: 0,
    startDate: '',
    endDate: '',
    startDateTmp: '',
    endDateTmp: '',
    selectDate: 'startDate',
    showDateSelect: false,
    dateList: {
      years: [2023, 2024, 2025],
      months: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
      date: [
        1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
        21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31
      ]
    },
    dateValue: [0, 0, 0],
    loading: false,
    current: 1,
    isLast: false,
    plateNumber: '',
    showSelect: {
      projectSelectShow: false,
      statusSelectShow: false
    },
    projectOptions: [
      {
        value: '',
        text: '全部'
      }
    ] as any,
    selectProjectIndex: 0,
    statusOptions: [
      {
        value: '',
        text: '全部'
      },
      {
        value: '1',
        text: '已结束'
      },
      {
        value: '0',
        text: '未结束'
      }
    ],
    selectStatusIndex: 2,
    selectProject: {} as any,
    listTotal: 0,
    fenceAlarmList: [],
    speedAlarmlistTotal: 0,
    overTimeAlarmlistTotal: 0,
    speedAlarmList: [],
    overTimeAlarmList: []
  },
  toSearch() {
    wx.setStorageSync('isGlobal', '');
    wx.navigateTo({
      url: '../component/vehicleSearch/vehicleSearch',
      fail: e => {
        console.log(e);
      }
    });
  },
  // 日期相关--------------
  showDate(e: any) {
    // selectDate
    let clickDate = null as any;
    if (e.currentTarget.dataset.key == 'startDate') {
      clickDate = this.data.startDate;
    } else {
      clickDate = this.data.endDate;
    }
    let y = this.data.dateList.years.findIndex(
      (x: number) => x == Number(clickDate.split('-')[0])
    );
    let m = this.data.dateList.months.findIndex(
      (x: number) => x == Number(clickDate.split('-')[1])
    );
    let d = this.data.dateList.date.findIndex(
      (x: number) => x == Number(clickDate.split('-')[2])
    );
    // console.log(this.data.startDate.split('-'))
    console.log([y, m, d]);
    this.setData({
      showDateSelect: true,
      selectDate: e.currentTarget.dataset.key,

      startDateTmp: this.data.startDate,
      endDateTmp: this.data.endDate,
      dateValue: [y, m, d]
    });
  },
  hideDate() {
    this.setData({
      showDateSelect: false
    });
  },
  changeSelectDate(e: any) {
    this.setData({
      selectDate: e.currentTarget.dataset.key,
      current: 1,
      isLast: false,
      fenceAlarmList: [],
      speedAlarmList: [],
      overTimeAlarmList: []
    });
  },
  selectDate(e: any) {
    console.log(e.detail.value);
    let y: string | number = this.data.dateList.years[e.detail.value[0]];
    let m: string | number = this.data.dateList.months[e.detail.value[1]];
    let d: string | number = this.data.dateList.date[e.detail.value[2]];
    y = y < 10 ? '0' + y : y;
    m = m < 10 ? '0' + m : m;
    d = d < 10 ? '0' + d : d;
    if (this.data.selectDate == 'startDate') {
      this.setData({
        startDateTmp: `${y}-${m}-${d}`
      });
    } else {
      this.setData({
        endDateTmp: `${y}-${m}-${d}`
      });
    }
  },
  changeDate(e: any) {
    console.log(
      new Date(this.data.startDateTmp).getTime(),
      new Date(this.data.endDateTmp).getTime()
    );
    if (
      new Date(this.data.startDateTmp).getTime() >
      new Date(this.data.endDateTmp).getTime()
    ) {
      wx.showToast({
        title: '结束时间不能早于开始时间',
        icon: 'none'
      });
      return;
    }
    this.setData({
      startDate: this.data.startDateTmp,
      endDate: this.data.endDateTmp,
      showDateSelect: false
    });
  },
  // 日期相关--------------end
  tabOnClick(event: any) {
    console.log(event.detail.name);
    // 看情况要不要重置查询条件
    this.setData({
      current: 1,
      isLast: false,
      fenceAlarmList: [],
      speedAlarmList: [],
      overTimeAlarmList: [],
      tabActive: event.detail.name
      // selectProjectIndex: 0
    });
    // 查询
    if (event.detail.name == 0) {
      this.getFenceAlarmList();
    } else if (event.detail.name == 1) {
      this.getSpeedAlarmList();
    } else if (event.detail.name == 2) {
      this.getOverTimeAlarmList();
    }
  },

  getNextList() {
    if (this.data.loading) return;
    if (!this.data.isLast) {
      this.setData({
        current: this.data.current + 1
      });
      this.getFenceAlarmList();
    } else {
      wx.showToast({
        title: '告警信息已加载完毕',
        duration: 1000,
        icon: 'none'
      });
    }
  },
  searchList() {
    this.setData({
      current: 1,
      isLast: false,
      fenceAlarmList: [],
      speedAlarmList: [],
      overTimeAlarmList: [],
      listTotal: 0,
      speedAlarmlistTotal: 0,
      overTimeAlarmlistTotal: 0
    });
    // 查询
    if (this.data.tabActive == 0) {
      this.getFenceAlarmList();
    } else if (this.data.tabActive == 1) {
      this.getSpeedAlarmList();
    } else if (this.data.tabActive == 2) {
      this.getOverTimeAlarmList();
    }
  },
  getFenceAlarmList() {
    let parms = {
      status: this.data.statusOptions[this.data.selectStatusIndex].value,
      projectId: this.data.projectOptions[this.data.selectProjectIndex].value,
      plateNumber: this.data.plateNumber,
      startTime: this.data.startDate + ' 00:00:00',
      endTime: this.data.endDate + ' 23:59:59',
      pageNo: this.data.current,
      pageSize: 10
    };
    this.setData({
      loading: true
    });
    wx.showLoading({
      title: '加载中'
    });
    getAction('api/monitor/fenceAlarm/list', parms)
      .then((res: any) => {
        wx.hideLoading();
        this.setData({
          loading: false
        });
        if (res.code == 200) {
          let tmpArr = this.data.fenceAlarmList.concat(res.result.records);
          this.setData({
            listTotal: res.result.total,
            fenceAlarmList: tmpArr
          });
          if (res.result.total == tmpArr.length) {
            // tmpArr 目前只是调试流程用
            this.setData({
              isLast: true
            });
          }
        } else {
          wx.showToast({
            title: res.message,
            icon: 'none'
          });
        }
      })
      .catch((err: any) => {
        this.setData({
          loading: false
        });
        wx.showToast({
          title: err.message,
          icon: 'none'
        });
      });
  },
  getSpeedAlarmList() {
    let parms = {
      status: this.data.statusOptions[this.data.selectStatusIndex].value,
      projectId: this.data.projectOptions[this.data.selectProjectIndex].value,
      plateNumber: this.data.plateNumber,
      startTime: this.data.startDate + ' 00:00:00',
      endTime: this.data.endDate + ' 23:59:59',
      pageNo: this.data.current,
      pageSize: 10
    };
    this.setData({
      loading: true
    });
    wx.showLoading({
      title: '加载中'
    });
    getAction('api/monitor/speedAlarm/list', parms)
      .then((res: any) => {
        wx.hideLoading();
        this.setData({
          loading: false
        });
        if (res.code == 200) {
          let tmpArr = this.data.speedAlarmList.concat(res.result.records);
          this.setData({
            speedAlarmlistTotal: res.result.total,
            speedAlarmList: tmpArr
          });
          if (res.result.total == tmpArr.length) {
            // tmpArr 目前只是调试流程用
            this.setData({
              isLast: true
            });
          }
        } else {
          wx.showToast({
            title: res.message,
            icon: 'none'
          });
        }
      })
      .catch((err: any) => {
        this.setData({
          loading: false
        });
        wx.showToast({
          title: err.message,
          icon: 'none'
        });
      });
  },
  // 获取停车超时数据
  getOverTimeAlarmList() {
    let parms = {
      status: this.data.statusOptions[this.data.selectStatusIndex].value,
      projectId: this.data.projectOptions[this.data.selectProjectIndex].value,
      plateNumber: this.data.plateNumber,
      startTime: this.data.startDate + ' 00:00:00',
      endTime: this.data.endDate + ' 23:59:59',
      pageNo: this.data.current,
      pageSize: 10
    };
    this.setData({
      loading: true
    });
    wx.showLoading({
      title: '加载中'
    });
    getAction('api/monitor/stopAlarm/list', parms)
      .then((res: any) => {
        wx.hideLoading();
        this.setData({
          loading: false
        });
        if (res.code == 200) {
          console.log(res.result);
          let tmpArr = this.data.overTimeAlarmList.concat(res.result.records);
          this.setData({
            overTimeAlarmlistTotal: res.result.total,
            overTimeAlarmList: tmpArr
          });
          if (res.result.total == tmpArr.length) {
            // tmpArr 目前只是调试流程用
            this.setData({
              isLast: true
            });
          }
        } else {
          wx.showToast({
            title: res.message,
            icon: 'none'
          });
        }
      })
      .catch((err: any) => {
        this.setData({
          loading: false
        });
        wx.showToast({
          title: err.message,
          icon: 'none'
        });
      });
  },
  getProjectOptions() {
    getAction('api/projects/list').then((res: any) => {
      if (res.code == 200) {
        res.result.unshift({
          id: '',
          projectName: '全部'
        });
        let arr = [] as any;
        res.result.forEach((item: any) => {
          arr.push({
            text: item.projectName,
            value: item.id
          });
        });
        this.setData({
          projectOptions: arr,
          selectProjectIndex: 0,
          selectProject: arr[0]
        });
      } else {
        wx.showToast({
          title: res.message,
          icon: 'none'
        });
      }
    });
  },
  toDetail(e: any) {
    wx.setStorageSync('selectCar', e.currentTarget.dataset.inf);
    if (this.data.tabActive == 0) {
      wx.navigateTo({
        url: '../realtime/realtime',
        fail: e => {
          console.log(e);
        }
      });
    } else {
      console.log('跳转到超速详情');
    }
  },
  bindPickerProject(e: any) {
    console.log(e);
    let index = Number(e.detail.value);
    this.setData({
      selectProject: this.data.projectOptions[index],
      selectProjectIndex: index,
      current: 1,
      isLast: false,
      listTotal: 0,
      speedAlarmlistTotal: 0,
      overTimeAlarmlistTotal: 0,
      fenceAlarmList: [],
      speedAlarmList: [],
      overTimeAlarmList: []
    });
    // 查询
    if (this.data.tabActive == 0) {
      this.getFenceAlarmList();
    } else if (this.data.tabActive == 1) {
      this.getSpeedAlarmList();
    } else if (this.data.tabActive == 2) {
      this.getOverTimeAlarmList();
    }
  },
  pickerChange(event: any) {
    //下拉框切换是否展示
    let fieldName: any = event.currentTarget.dataset.fieldname;
    let data: any = { ...this.data };
    data.showSelect[fieldName] = true;
    this.setData(data);
  },
  hidePicker() {
    let showSelect = this.data.showSelect;
    showSelect = {
      projectSelectShow: false,
      statusSelectShow: false
    };
    this.setData({
      showSelect: showSelect
    });
  },
  pickerConfirm(event: any) {
    console.log(event);
    //下拉框点击确认
    let { fieldname, fieldindex } = event.currentTarget.dataset;
    let detail = event.detail;
    let data: any = { ...this.data };
    // if (fieldname === 'projectId') {
    //   data.params[fieldname] = detail.value.value;
    //   data[fieldindex] = detail.index;

    // } else {
    data[fieldname] = this.data.projectOptions[detail.index];
    data[fieldindex] = detail.index;
    // }
    console.log(this.data);
    this.setData(data);
    this.hidePicker();
    this.setData({
      current: 1,
      isLast: false,
      fenceAlarmList: [],
      speedAlarmList: [],
      overTimeAlarmList: [],
      listTotal: 0,
      speedAlarmlistTotal: 0,
      overTimeAlarmlistTotal: 0
    });
    // 查询
    if (this.data.tabActive == 0) {
      this.getFenceAlarmList();
    } else if (this.data.tabActive == 1) {
      this.getSpeedAlarmList();
    } else if (this.data.tabActive == 2) {
      this.getOverTimeAlarmList();
    }
  },
  clearValue() {
    this.setData({
      plateNumber: ''
    });
  },
  // 日期初始化
  initDate() {
    let year = new Date().getFullYear();
    let mon = (new Date().getMonth() + 1) as any;
    let day =
      new Date().getDate() < 10
        ? '0' + new Date().getDate()
        : new Date().getDate();
    let years = [] as any;

    let sy = mon > 1 ? year : year - 1;
    let smon = mon > 1 ? mon - 1 : (12 as any);
    mon = mon < 10 ? '0' + mon : mon;
    smon = smon < 10 ? '0' + smon : smon;
    for (let i = -3; i < 6; i++) {
      years.push(year + i);
    }
    this.setData({
      dateList: {
        years: years,
        months: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
        date: [
          1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
          21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31
        ]
      },
      dateValue: [0, 0, 0],

      startDate: `${sy}-${smon}-${day}`,
      endDate: `${year}-${mon}-${day}`,
      startDateTmp: `${sy}-${smon}-${day}`,
      endDateTmp: `${year}-${mon}-${day}`
    });
  },
  lower(e: any) {
    console.log(e.detail.direction == 'bottom');
    if (this.data.isLast) {
      wx.showToast({
        title: '已经是最后一页',
        icon: 'none'
      });
      return;
    }
    if (e.detail.direction == 'bottom' && !this.data.loading) {
      // this.data.current += 1
      this.setData({
        loading: true,
        current: (this.data.current += 1)
      });
      // 查询
      if (this.data.tabActive == 0) {
        this.getFenceAlarmList();
      } else if (this.data.tabActive == 1) {
        this.getSpeedAlarmList();
      } else if (this.data.tabActive == 2) {
        this.getOverTimeAlarmList();
      }
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {},

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    this.initDate();
    this.getProjectOptions();
    this.getFenceAlarmList();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // this.initDate();
    let plateNumber = wx.getStorageSync('selectCarInf').plateNumber;
    this.setData({
      plateNumber: plateNumber ? plateNumber : this.data.plateNumber,
      current: 1,
      isLast: false,
      fenceAlarmList: [],
      speedAlarmList: [],
      overTimeAlarmList: [],
      listTotal: 0,
      speedAlarmlistTotal: 0,
      overTimeAlarmlistTotal: 0
    });
    console.log(this.data);
    wx.removeStorageSync('selectCarInf');
    if (this.data.tabActive == 0) {
      this.getFenceAlarmList();
    } else if (this.data.tabActive == 1) {
      this.getSpeedAlarmList();
    } else if (this.data.tabActive == 2) {
      this.getOverTimeAlarmList();
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    wx.setStorageSync('selectCarInf', '');
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    wx.setStorageSync('selectCarInf', '');
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.initDate();
    this.getProjectOptions();
    this.setData({
      plateNumber: '',
      current: 1,
      isLast: false,
      fenceAlarmList: [],
      speedAlarmList: [],
      overTimeAlarmList: []
    });
    if (this.data.tabActive == 0) {
      this.getFenceAlarmList();
    } else if (this.data.tabActive == 1) {
      this.getSpeedAlarmList();
    } else if (this.data.tabActive == 2) {
      this.getOverTimeAlarmList();
    }

    //停止下拉刷新
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {}
});
