// pages/statement/reportStatement/reportStatement.ts
import { getAction } from '../../../api/base';

const dayjs = require('dayjs');
Page({
  /**
   * 页面的初始数据
   */
  data: {
    tabActive: 0,
    dateOptions: [
      {
        name: '按月',
        dateType: 'month'
      },
      {
        name: '按年',
        dateType: 'year'
      },
      {
        name: '按季度',
        dateType: 'season'
      }
    ] as any,
    dateOptionIndex: 0,
    currentDate: new Date().getTime(),
    currentDateStr: dayjs(new Date()).format('YYYY-MM-DD'),
    showDateSeasonSelect: false,
    dateList: {
      years: [2023, 2024, 2025],
      season: ['第一', '第二', '第三', '第四']
    },
    dateValue: [0, 0],
    dateSeason: '',
    tmpDate: '',
    showMoreSearch: false,
    projectOptions: ['全部'] as Array<string>,
    selectProjectIndex: 0,
    vehicleTypeOptions: ['全部'] as Array<string>,
    selectVehicleTypeIndex: 0,

    chartList: [],
    tableData: [],
    tableDefaultData: []
  },
  tabOnClick(event: any) {
    // console.log(event.detail.name);
    // 看情况要不要重置查询条件
    this.setData({
      tabActive: event.detail.name
    });
    this.initDateSeason();
    // 查询
    this.getList();
  },
  bindPickerType(e: any) {
    // console.log(e.detail.value);
    this.setData({
      dateOptionIndex: e.detail.value
    });
    if (e.detail.value == 2) {
      this.initDateSeason();
    } else {
      this.initDate();
    }
    this.getList();
  },
  bindPickerDate(e: any) {
    let time = new Date(e.detail.value).getTime();
    let str =
      this.data.dateOptionIndex == 0
        ? dayjs(new Date(e.detail.value)).format('YYYY-MM') + '月'
        : e.detail.value;
    this.setData({
      currentDate: time,
      currentDateStr: str
    });
    this.getList();
  },
  showDateSeasonSelect() {
    this.data.showDateSeasonSelect = true;
    this.setData({
      showDateSeasonSelect: true
    });
  },

  // 日期初始化
  initDateSeason() {
    let year = new Date().getFullYear();
    let month = new Date().getMonth() + 1;
    let nowSeason = Math.floor(month / 3);
    let years = [];
    for (let i = -3; i < 6; i++) {
      years.push(year + i);
    }
    let nowYear = years.indexOf(year);
    this.setData({
      dateList: {
        years: years,
        season: this.data.dateList.season
      },
      dateValue: [nowYear, nowSeason],
      tmpDate: `${year}年${this.data.dateList.season[nowSeason]}季`,
      dateSeason: `${year}年${this.data.dateList.season[nowSeason]}季`
    });
  },
  hideDate() {
    this.setData({
      showDateSeasonSelect: false
    });
  },
  changeDate() {
    this.setData({
      dateSeason: this.data.tmpDate,
      showDateSeasonSelect: false
    });
    this.getList();
  },
  selectDate(e: any) {
    // console.log(e.detail.value);
    let year: string | number = this.data.dateList.years[e.detail.value[0]];
    let season: string | number = this.data.dateList.season[e.detail.value[1]];
    this.setData({
      dateValue: e.detail.value,
      tmpDate: `${year}年${season}季`
    });
  },
  initDate() {
    let dateStr = '';
    if (this.data.dateOptionIndex == 0) {
      dateStr = dayjs(new Date(this.data.currentDate)).format('YYYY-MM') + '月';
    } else if (this.data.dateOptionIndex == 1) {
      dateStr = dayjs(new Date(this.data.currentDate)).format('YYYY');
    } else {
    }
    this.setData({
      currentDateStr: dateStr
    });
    this.getList();
  },
  getList() {
    let startDate = '';
    if (this.data.dateOptionIndex == 0) {
      startDate = dayjs(new Date(this.data.currentDate))
        .startOf('month')
        .format('YYYY-MM-DD');
    } else if (this.data.dateOptionIndex == 1) {
      startDate = dayjs(new Date(this.data.currentDate))
        .startOf('year')
        .format('YYYY-MM-DD');
    } else {
      let month = (this.data.dateValue[1] + 1) * 3 - 2;
      let date =
        this.data.dateList.years[this.data.dateValue[0]] +
        '/' +
        month +
        '/' +
        '01';
      startDate = dayjs(new Date(date)).startOf('month').format('YYYY-MM-DD');
      console.log(startDate);
    }
    let parms = {
      startTime: startDate,
      statisType: Number(this.data.dateOptionIndex) + 2
    };
    let url = '';
    if (this.data.tabActive == 0) {
      url = 'api/report/reportChart';
    } else {
      url = 'api/report/reportList';
    }
    this.setData({
      loading: true
    });
    getAction(url, parms)
      .then((res: any) => {
        this.setData({
          loading: false
        });
        if (res.code == 200) {
          if (this.data.tabActive == 0) {
            res.result.forEach((item: any) => {
              item.scale = [
                0,
                (item.totalCount * 0.2).toFixed(1),
                (item.totalCount * 0.4).toFixed(1),
                (item.totalCount * 0.6).toFixed(1),
                (item.totalCount * 0.8).toFixed(1),
                item.totalCount
              ];
            });
            this.setData({
              chartList: res.result
            });
          } else {
            let tmpArr = ['全部'] as Array<string>;
            let tmpArr2 = ['全部'] as Array<string>;
            res.result.forEach((item: any) => {
              if (tmpArr.filter(x => x == item.projectName).length == 0) {
                tmpArr.push(item.projectName);
              }
              if (
                tmpArr2.filter(x => x == item.vehicleType_dictText).length == 0
              ) {
                tmpArr2.push(item.vehicleType_dictText);
              }
            });
            this.setData({
              tableData: res.result,
              tableDefaultData: res.result,
              projectOptions: tmpArr,
              vehicleTypeOptions: tmpArr2,
              selectProjectIndex: 0,
              selectVehicleTypeIndex: 0
            });
          }
        } else {
          wx.showToast({
            title: res.message,
            icon: 'none'
          });
        }
      })
      .catch((err: any) => {
        this.setData({
          loading: false
        });
        wx.showToast({
          title: err.message,
          icon: 'none'
        });
      });
  },

  // 切换显示 更多条件
  filterShow() {
    this.setData({
      showMoreSearch: true
    });
  },
  filterHide() {
    this.setData({
      showMoreSearch: false
    });
  },
  bindPickerProject(e: any) {
    // console.log(e);
    let index = Number(e.detail.value);
    this.setData({
      selectProjectIndex: index
    });
  },
  bindPickerVehicleType(e: any) {
    // console.log(e);
    let index = Number(e.detail.value);
    this.setData({
      selectVehicleTypeIndex: index
    });
  },
  restList() {
    this.setData({
      selectProjectIndex: 0,
      selectVehicleTypeIndex: 0
    });
    // this.filterTableList();
    this.getList();
  },
  filterTableList() {
    let tmpArr = this.data.tableDefaultData;
    if (this.data.selectProjectIndex != 0) {
      tmpArr = tmpArr.filter(
        (x: any) =>
          x.projectName ==
          this.data.projectOptions[this.data.selectProjectIndex]
      );
    }
    if (this.data.selectVehicleTypeIndex != 0) {
      tmpArr = tmpArr.filter(
        (x: any) =>
          x.vehicleType_dictText ==
          this.data.vehicleTypeOptions[this.data.selectVehicleTypeIndex]
      );
    }
    this.setData({
      tableData: tmpArr,
      showMoreSearch: false
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {},

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    if (this.data.dateOptionIndex == 2) {
      this.initDateSeason();
    } else {
      this.initDate();
    }
    this.getList();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

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

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