// index.ts
// 获取应用实例
const app = getApp<IAppOption>();
import { getAction, postAction } from '../../api/base';
var QQMapWX = require('../../utils/qqmap-wx-jssdk.min.js');
// 实例化API核心类
var qqmapsdk = new QQMapWX({
  key: 'KDEBZ-EV5KH-XN5DU-WYZGD-SN3YK-WZBZI'
});

Page({
  data: {
    dateString: '--年--月--日',
    dateTimeString: '00:00:00',
    timer: null as any,
    selectCar: {} as any,
    selectProject: {} as any,
    selectCarIndex: 0,
    selectProjectIndex: 0,
    signInType: 1, // 1:签到 2:签退
    projectOptions: [] as any,
    carOptions: [] as any,
    signInAddress: '',
    driverName: '',
    loading: false,
    getAddressSuccess: true
  },
  // 登出
  logOut: function () {
    // 清除缓存
    wx.removeStorageSync('token');
    wx.removeStorageSync('userInfo');
    wx.reLaunch({
      url: '/pages/login/login'
    });
  },
  // 选中项目、车辆
  bindPickerProject(e: any) {
    console.log();
    this.setData({
      selectProject: this.data.projectOptions[e.detail.value],
      selectProjectIndex: Number(e.detail.value)
    });

    this.getCarOptions({
      projectId: this.data.projectOptions[e.detail.value].id
    });
  },
  bindPickerChange: function (e: any) {
    this.setData({
      selectCar: this.data.carOptions[e.detail.value],
      selectCarIndex: Number(e.detail.value)
    });
  },
  // 签到、签退
  signIn: function () {
    console.log(1);
    // 调用接口
    if (this.data.signInType == 1) {
      // 签到
      console.log('签到');
    } else {
      // 签退
      console.log('签退');
    }
    if (!this.data.signInAddress) {
      wx.showToast({
        title: '位置信息获取失败，请重试',
        icon: 'none'
      });
      return;
    }
    if (this.data.selectProject.id == -1) {
      wx.showToast({
        title: '请选择签到项目',
        icon: 'none'
      });
      return;
    }
    if (this.data.selectCar.id == -1) {
      wx.showToast({
        title: '请选择签到车辆',
        icon: 'none'
      });
      return;
    }
    let parms = {
      projectId: this.data.selectProject.id,
      projectName: this.data.selectProject.projectName,
      vehicleId: this.data.selectCar.id,
      plateNumber: this.data.selectCar.plateNumber,
      signInType: this.data.signInType,
      signInAddress: this.data.signInAddress,
      timeString: ''
    };
    postAction('api/driverSignIn/add', parms)
      .then((res: any) => {
        if (res.code == 200) {
          wx.setStorageSync('signInInfo', res.result);
          wx.navigateTo({
            url: './page/signInFeedback/signInFeedback',
            fail: e => {
              console.log(e);
            }
          });
        } else {
          console.log('失败');
          wx.showToast({
            title: res.message,
            icon: 'none'
          });
        }
      })
      .catch(err => {
        wx.showToast({
          title: err.message,
          icon: 'none'
        });
      });
  },
  showSignInReocrd() {
    wx.navigateTo({
      url: './page/signInReocrd/signInReocrd',
      fail: e => {
        console.log(e);
      }
    });
  },
  toMaintenance() {
    wx.navigateTo({
      url: '../maintenanceIndex/maintenanceIndex',
      fail: e => {
        console.log(e);
      }
    });
  },
  getNowDateTime: function () {
    let y = new Date().getFullYear();
    let m = new Date().getMonth();
    let d = new Date().getDate();

    let h = new Date().getHours();
    let min = new Date().getMinutes();
    let sec = new Date().getSeconds();

    this.setData({
      dateString: `${y}年${m < 10 ? '0' + m : m}月${d < 10 ? '0' + d : d}日`,
      dateTimeString: `${h}:${min < 10 ? '0' + min : min}:${
        sec < 10 ? '0' + sec : sec
      }`
    });
  },

  // 轮询接口 30秒一次
  setTimer() {
    if (this.data.timer != null) {
      clearInterval(this.data.timer);
    }
    let timer = setInterval(() => {
      this.getNowDateTime();
    }, 1 * 1000);
    this.setData({
      timer: timer
    });
  },
  getProjectOptions() {
    getAction('api/projects/list').then((res: any) => {
      if (res.code == 200) {
        res.result.unshift({
          id: -1,
          projectName: '请选择签到项目'
        });
        this.setData({
          projectOptions: res.result,
          selectProjectIndex: 0,
          selectProject: res.result[0]
        });
        this.getCarOptions({
          projectId: res.result[0].id
        });
      } else {
        wx.showToast({
          title: res.message,
          icon: 'none'
        });
      }
    });
  },
  getCarOptions(parms: any) {
    getAction('api/vehicle/listByProjectId', parms).then((res: any) => {
      if (res.code == 200) {
        res.result.unshift({
          id: -1,
          plateNumber: '请选择车辆'
        });
        this.setData({
          carOptions: res.result,
          selectCarIndex: 0,
          selectCar: res.result[0]
        });
      } else {
        wx.showToast({
          title: res.message,
          icon: 'none'
        });
      }
    });
  },
  // 获取签到状态
  getCheckStatus() {
    if (!this.data.signInAddress) {
      return;
    }
    getAction('api/driverSignIn/getLastSignIn').then((res: any) => {
      if (res.code == 200) {
        if (res.result) {
          let selectProject = {
            id: res.result.projectId,
            projectName: res.result.projectName
          };
          let selectCar = {
            id: res.result.vehicleId,
            plateNumber: res.result.plateNumber
          };
          this.setData({
            signInType: !!res.result ? 2 : 1,
            signInAddress: res.result.signInAddress,
            driverName: res.result.driverName,
            carOptions: [selectCar],
            selectCar: selectCar,
            selectCarIndex: 0,
            projectOptions: [selectProject],
            selectProject: selectProject,
            selectProjectIndex: 0
          });
        } else {
          this.getProjectOptions();
          this.setData({
            signInType: 1
          });
        }
      } else {
        wx.showToast({
          title: res.message,
          icon: 'none'
        });
      }
    });
  },
  getAddress() {
    wx.showLoading({
      title: '位置信息获取中'
    });
    let _this = this;
    wx.getLocation({
      isHighAccuracy: true, // 开启高精度定位
      success: function (res1: any) {
        console.log(res1);

        qqmapsdk.reverseGeocoder({
          location: {
            latitude: res1.latitude,
            longitude: res1.longitude
          },
          success: function (res: any) {
            if (res.status == 0) {
              //成功后的回调
              console.log(res.result.address);
              // var res = res.result;
              _this.setData({
                signInAddress: res.result.address,
                getAddressSuccess: true
              });
              _this.getCheckStatus();
            } else {
              // 位置信息获取失败
              wx.showToast({
                title: '位置信息获取失败,请重试',
                icon: 'none'
              });
              _this.setData({
                getAddressSuccess: false
              });
            }
          }
        });
      },
      fail: function () {
        // 位置信息获取失败
        wx.showToast({
          title: '位置信息获取失败,请重试',
          icon: 'none'
        });
        _this.setData({
          getAddressSuccess: false
        });
      },
      complete: function () {
        wx.hideLoading();
        console.log('获取结束');
      }
    });
  },
  getUserInf() {
    this.setData({
      driverName: wx.getStorageSync('userInfo').realname
    });
  },

  toPage(e: any) {
    console.log(e.currentTarget.dataset.type);
    if (e.currentTarget.dataset.type == 'apply') {
      wx.navigateTo({
        url: '../vehicleMaintenance/operation/maintainApply/maintainApply',
        fail: e => {
          console.log(e);
        }
      });
    } else if (e.currentTarget.dataset.type == 'record') {
      wx.navigateTo({
        url: '../vehicleMaintenance/maintainRecord/maintainRecord',
        fail: e => {
          console.log(e);
        }
      });
    } else if (e.currentTarget.dataset.type == 'report') {
      wx.navigateTo({
        url: '../vehicleMaintenance/maintainRecord/maintainRecord',
        fail: e => {
          console.log(e);
        }
      });
    } else if (e.currentTarget.dataset.type == 'eventReportRecord') {
      wx.navigateTo({
        url: '../eventReport/eventReportRecord/eventReportRecord',
        fail: e => {
          console.log(e);
        }
      });
    }
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    if (this.data.signInAddress) {
      this.getCheckStatus();
    } else {
      this.getAddress();
    }
    this.getNowDateTime();
    this.setTimer();
  },

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

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    this.getProjectOptions();
    this.getNowDateTime();
    this.setTimer();
    this.getAddress();
    this.getUserInf();
    // this.getCheckStatus();
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    if (this.data.timer) {
      clearInterval(this.data.timer);
    }
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    if (this.data.timer) {
      clearInterval(this.data.timer);
    }
  },

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

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

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