// pages/vehicleMaintenance/maintainRecord/maintainRecord.ts
import { getAction } from '../../../api/base';

Page({
  /**
   * 页面的初始数据
   */
  data: {
    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],

    projectOptions: [
      {
        id: '',
        projectName: '全部'
      }
    ],
    selectProjectIndex: 0,
    selectProject: {} as any,

    tabList: [] as any,
    active: 0,
    showMoreSearch: false,
    plateNumberOrOrderNo: '',

    repairShopsOptions: [] as any,

    flowStatus: -1,
    current: 1,
    isLast: false,
    loading: false,
    recordList: []
  },
  toSearch() {},
  // 切换显示 更多条件
  filterShow() {
    this.setData({
      showMoreSearch: true
    });
  },
  filterHide() {
    this.setData({
      showMoreSearch: false
    });
  },

  // 日期相关--------------
  showDate(e: any) {
    // selectDate
    let clickDate = null as any;
    if (e.currentTarget.dataset.key == 'startDate') {
      clickDate = this.data.startDate;
    } else {
      clickDate = this.data.endDate;
    }
    if (!clickDate) {
      let year = new Date().getFullYear();
      let mon =
        new Date().getMonth() + 1 < 10
          ? '0' + (new Date().getMonth() + 1)
          : new Date().getMonth() + 1;
      let day =
        new Date().getDate() < 10
          ? '0' + new Date().getDate()
          : new Date().getDate();
      clickDate = `${year}-${mon}-${day}`;
    }
    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])
    );
    this.setData({
      showDateSelect: true,
      selectDate: e.currentTarget.dataset.key,

      startDateTmp:
        e.currentTarget.dataset.key == 'startDate'
          ? clickDate
          : this.data.startDate,
      endDateTmp:
        e.currentTarget.dataset.key == 'endDate'
          ? clickDate
          : this.data.endDate,
      dateValue: [y, m, d]
    });
  },
  hideDate() {
    this.setData({
      showDateSelect: false
    });
  },
  changeSelectDate(e: any) {
    this.setData({
      selectDate: e.currentTarget.dataset.key
    });
  },
  selectDate(e: any) {
    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) {
    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
    });
  },

  // 日期初始化
  initDate() {
    let year = new Date().getFullYear();
    let mon =
      new Date().getMonth() + 1 < 10
        ? '0' + (new Date().getMonth() + 1)
        : new Date().getMonth() + 1;
    let day =
      new Date().getDate() < 10
        ? '0' + new Date().getDate()
        : new Date().getDate();
    let years = [];
    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: `${year}-${mon}-${day}`,
      // endDate: `${year}-${mon}-${day}`,
      // startDateTmp: `${year}-${mon}-${day}`,
      // endDateTmp: `${year}-${mon}-${day}`
    });
  },
  // 日期相关--------------end
  // 项目选择--------------
  getProjectOptions() {
    getAction('api/vehicles/repair/queryProjects').then((res: any) => {
      if (res.code == 200) {
        let tmpArr = [
          {
            id: '',
            projectName: '全部'
          }
        ];
        // res.result.unshift();
        res.result.forEach((item: any) => {
          tmpArr.push({
            id: item.projectId,
            projectName: item.projectName
          });
        });
        this.setData({
          projectOptions: tmpArr,
          selectProjectIndex: 0,
          selectProject: tmpArr[0]
        });
      } else {
        wx.showToast({
          title: res.message,
          icon: 'none'
        });
      }
    });
  },
  bindPickerProject(e: any) {
    let index = Number(e.detail.value);
    this.setData({
      selectProject: this.data.projectOptions[index],
      selectProjectIndex: index
    });
  },
  // 项目选择--------------end
  // 维修厂选择---------
  getRepairShops() {
    getAction('api/vehicles/repair/getRepairShop').then((res: any) => {
      if (res.code == 200) {
        res.result.forEach((item: any) => {
          item.check = false;
        });
        this.setData({
          repairShopsOptions: res.result
        });
      } else {
        wx.showToast({
          title: res.message,
          icon: 'none'
        });
      }
    });
  },
  checkRepairShop(e: any) {
    let tmpArr = this.data.repairShopsOptions;
    let index = e.currentTarget.dataset.index;
    tmpArr.forEach((item: any, i: number) => {
      if (i == index) {
        item.check = true;
      } else {
        item.check = false;
      }
    });
    // tmpArr[index].check = !tmpArr[index].check
    this.setData({
      repairShopsOptions: tmpArr
    });
  },
  // 维修厂选择---------
  tabOnChange(e: any) {
    this.setData({
      plateNumberOrOrderNo: this.data.plateNumberOrOrderNo,
      active: e.detail.index,
      flowStatus: this.data.tabList[e.detail.index].flowStatus,
      current: 1,
      isLast: false,
      recordList: []
    });
    this.getList();
  },
  getTabList() {
    let tmpArr = this.data.repairShopsOptions.filter((x: any) => x.check);
    let repairShop = tmpArr[0] ? tmpArr[0].repairShop : '';
    let parms = {
      startTime: this.data.startDate,
      endTime: this.data.endDate,
      plateNumberOrOrderNo: this.data.plateNumberOrOrderNo,
      projectId: this.data.selectProject.id,
      repairShop: repairShop
    };
    getAction('api/vehicles/repair/getRepairPageStatic', parms).then(
      (res: any) => {
        if (res.code == 200) {
          this.setData({
            tabList: res.result
          });
        } else {
          wx.showToast({
            title: res.message,
            icon: 'none'
          });
        }
      }
    );
  },
  restList() {
    let tmpArr = this.data.repairShopsOptions;
    tmpArr.forEach((item: any) => {
      item.check = false;
    });
    // this.initDate();
    this.setData({
      current: 1,
      isLast: false,
      recordList: [],
      plateNumberOrOrderNo: '',
      selectProject: this.data.projectOptions[0],
      selectProjectIndex: 0,
      repairShopsOptions: tmpArr,
      showMoreSearch: false,
      startDate: '',
      endDate: '',
      startDateTmp: '',
      endDateTmp: ''
    });
    this.getTabList();
    this.getList();
  },
  changePlateNumberOrOrderNo(e: any) {
    this.setData({
      plateNumberOrOrderNo: e.detail.value,
      current: 1,
      isLast: false,
      recordList: []
    });
    this.getTabList();
    this.getList();
  },
  getListByMoreParms() {
    this.setData({
      current: 1,
      isLast: false,
      recordList: [],
      showMoreSearch: false
    });
    this.getTabList();
    this.getList();
  },
  getList() {
    let parms: any;
    // if (this.data.showMoreSearch) {
    let tmpArr = this.data.repairShopsOptions.filter((x: any) => x.check);
    let repairShop = tmpArr[0] ? tmpArr[0].repairShop : '';
    parms = {
      startTime: this.data.startDate,
      endTime: this.data.endDate,
      plateNumberOrOrderNo: this.data.plateNumberOrOrderNo,
      projectId: this.data.selectProject.id,
      repairShop: repairShop,
      flowStatus: this.data.flowStatus,
      pageNo: this.data.current,
      pageSize: 10
    };
    // } else {
    //   parms = {
    //     plateNumberOrOrderNo: this.data.plateNumberOrOrderNo,
    //     flowStatus: this.data.flowStatus,
    //     pageNo: this.data.current,
    //     pageSize: -1//10
    //   };
    // }
    this.setData({
      loading: true
    });
    wx.showLoading({
      title: '加载中',
      icon: 'none'
    });
    getAction('api/vehicles/repair/list', parms)
      .then((res: any) => {
        this.setData({
          loading: false
        });
        wx.hideLoading();
        if (res.code == 200) {
          let tmpArr = this.data.recordList.concat(res.result.records);
          this.setData({
            listTotal: res.result.total,
            recordList: tmpArr
          });
          if (res.result.total == tmpArr.length) {
            // tmpArr 目前只是调试流程用
            this.setData({
              isLast: true
            });
          }
          // if (1) {
          //   this.setData({
          //     // isLast: true,
          //     listTotal: res.result.total,
          //     recordList: res.result.records //之后放出来
          //   });
          // }
        } else {
          wx.showToast({
            title: res.message,
            icon: 'none'
          });
        }
      })
      .catch((err: any) => {
        this.setData({
          loading: false
        });
        wx.showToast({
          title: err.message,
          icon: 'none'
        });
      });
  },
  // 跳转到对应的维修详情页
  toDetailPage(e: any) {
    wx.setStorageSync('selectMaintain', e.currentTarget.dataset.inf);
    let url = '';
    switch (e.currentTarget.dataset.inf.flowStatus) {
      case 2:
        url = '../maintainSend/maintainSend';
        break;
      case 3:
        url = '../maintainSend/maintainSend';
        break;
      case 4:
        url = '../maintainCheck/maintainCheck';
        break;
      case 5:
        url = '../maintainCheck/maintainCheck';
        break;
      case 6:
        url = '../maintainProcedure/maintainProcedure';
        break;
      case 7:
        url = '../maintainProcedure/maintainProcedure';
        break;
      case 8:
        url = '../maintainResult/maintainResult';
        break;
      case 9:
        url = '../maintainResult/maintainResult';
        break;
      case 10:
        url = '../maintainCheck/maintainCheck';
        break;
    }
    let that = this;
    wx.navigateTo({
      url: url,
      events: {
        // 编辑过后刷新页面
        refresh: function () {
          console.log('动了');

          that.initDate();
          that.restList();
        }
      },
      fail: e => {
        console.log(e);
      }
    });
  },
  lower(e: any) {
    // return
    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)
      });
      this.getList();
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    this.initDate();
    this.restList();
  },

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

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

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

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    console.log(getApp().EventChannel);
    getApp().EventChannel = null;
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.initDate();
    this.restList();
    //停止下拉刷新
    wx.stopPullDownRefresh();
  },

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

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