// pages/clock/clock.js
import {
  punchClockNeedInfo,
  savePunchClock
} from '../../services/index.js'
import {
  imgServerUrl
} from '../../config/config.js'
import { transformFromWGSToGCJ } from '../../utils/util'
import loading from '../../utils/loading.js'
let clickStatus = true
let locationStatus = true
let nowTime = 0
Page({

  /**
   * 页面的初始数据
   */
  data: {
    latitude: '',
    longitude: '',
    approveStatus: false,
    showCover: true,
    settingVisible: false,
    imgServerUrl,
    navigation: [
      {
        image: '/images/clock/clock-tongji.png',
        text: '统计'
      },
      {
        image: '/images/clock/clock-rule-icon.png',
        text: '规则'
      },
      {
        image: '/images/clock/clock-kefu.png',
        text: '客服'
      },
    ],
    clockType: 3,
    statusImage: `${imgServerUrl}/images/clock/clock-beyond.png`,
    statusIcon: `${imgServerUrl}/images/clock/clock-waring.png`,
    statusMessage: `请进入企业后再进行打卡`,
    startPunch: "未完成",
    endPunch: '未完成',
    todayMoney: 0,
    sumDuration: 0,
    sumMoney: 0,
    wsPunchClockId: '',
    actions: [
      {
        name: '取消',
        color: '#007AFF'
      },
      {
        name: '确认',
        color: '#007AFF',
        fontWeight: 600
      }
    ],
    userInfo: '',
    hpMember: ''
  },
  closeSettingVisible(data) {
    const { index } = data.detail;
    if (index === 0) {
      this.setData({
        settingVisible: false
      })
    }
  },
  toRule() {
    wx.navigateTo({
      url: './clock-rule/clock-rule',
    })
  },
  getLocation() {
    return new Promise(reslove => {
      wx.getLocation({
        type: 'gcj02',
        success: data => {
          // const { latitude, longitude } = transformFromWGSToGCJ(data.latitude, data.longitude)
          // reslove(Object.assign(data, { latitude, longitude }))
          reslove(data)
        },
        fail: res => {
          reslove(res)
        }
      })
    })
  },
  location() {
    return new Promise((reslove, reject) => {
      wx.getSetting({
        success: async res => {
          if (res.authSetting['scope.userLocation']) {
            const data = await this.getLocation()
            const info = wx.getSystemInfoSync()
            if (data.errMsg.indexOf('system permission denied') !== -1 || info.locationEnabled === false) {
              wx.showModal({
                content: '请授权微信获取位置信息权限',
                title: '微信未能获取位置信息',
                showCancel: false,
                confirmColor: '#007AFF',
                confirmText: '确认',
              })
              // this.setData({
              //   settingVisible: true
              // })
              reject()
            } else {
              this.setData({
                latitude: data.latitude,
                longitude: data.longitude
              })
              // this.setData({
              //   longitude: '120.35333936646411',
              //   latitude: '31.535590759589642'
              // })
              reslove(data)
            }
          } else {
            wx.authorize({
              scope: 'scope.userLocation',
              success: async () => {
                reslove(await this.getLocation())
              },
              fail: () => {
                wx.showModal({
                  content: '',
                  // confirmText: '去授权',
                  title: '请前往设置打开用户定位权限',
                  confirmColor: '#007AFF',
                  cancelColor: '#007AFF',
                  confirmText: '确认',
                  success: (result) => {
                    if (result.confirm) {
                      wx.openSetting({})
                    } else {
                      this.setData({
                        clockType: 3
                      })
                      reject()
                    }
                  },
                })
              }
            })
          }
        }
      })
    })
  },
  async click() {
    // const data = await this.location()
    if (this.data.clockType === 1 && !this.data.wsPunchClockId) {
      this.clock(this.data.longitude, this.data.latitude)
      // this.clock(120.35333936646411, 31.535590759589642)
    }
    if (this.data.clockType === 1 && this.data.wsPunchClockId) {
      // wx.showModal({
      //   title: '提示',
      //   content: '未到下班时间，请刷新页面获取最新状态',
      //   showCancel: false,
      // })
    }
    if (this.data.clockType === 2 && this.data.wsPunchClockId) {
      this.clock(this.data.longitude, this.data.latitude)
    }
    if (this.data.clockType === 3) {
      // wx.showModal({
      //   title: '提示',
      //   content: '超出范围，请刷新页面获取当前位置',
      //   showCancel: false,
      // })
    }
    if (this.data.clockType === 4) {
      // wx.showModal({
      //   title: '提示',
      //   content: '今日打卡已完成',
      //   showCancel: false,
      // })
    }
  },
  clock(longitude, latitude) {
    if (clickStatus) {
      clickStatus = false
      savePunchClock({ longitude, latitude, clockType: this.data.clockType, wsPunchClockId: this.data.wsPunchClockId }).then(data => {
        wx.showToast({
          title: '打卡成功',
          success: () => {
            clickStatus = true
            wx.navigateTo({
              url: `./clock-success/clock-success?clockType=${this.data.clockType}&&sumMoney=${data.data.sumMoney}&&duration=${data.data.duration}&&todayMoney=${data.data.todayMoney}&&time=${this.data.wsPunchClockId ? data.data.endPunchClock : data.data.startPunchClock}`
            })
          }
        })
      }).catch(data => {
        clickStatus = true
        wx.showModal({
          title: '提示',
          content: data.errmsg,
          showCancel: false,
        })
      })
    } else {
      wx.showToast({
        icon: 'none',
        title: '请勿重复点击',
      })
    }
  },
  navigator(e) {
    const { index } = e.currentTarget.dataset
    if (index === 0) {
      wx.navigateTo({
        url: './clock-tongji/index',
      })
    }
    if (index === 1) {
      wx.navigateTo({
        url: './clock-rule/clock-rule',
      })
    }
    if (index === 2) {
      this.changeCoverStatus()
    }
  },
  callKefu() {
    wx.makePhoneCall({
      phoneNumber: '4006900099',
    })
  },
  changeCoverStatus() {
    this.setData({
      showCover: !this.data.showCover
    })
  },
  async load(showLoading = true) {
    try {
      if (showLoading) {
        wx.showLoading({
          title: '定位中...',
        })
      }
      nowTime = new Date().getTime()
      punchClockNeedInfo({ longitude: this.data.longitude, latitude: this.data.latitude }).then(data => {
        // punchClockNeedInfo({ longitude: 120.3533, latitude: 31.535590759589642 }).then(data => {
        locationStatus = true
        let {
          authenticationStatus,
          startPunch,
          endPunch,
          todayMoney,
          clockType, // 1:上班打卡 2：下班打卡 3：超出范围 4：已完成
          sumDuration,
          sumMoney,
          wsPunchClockId,
          dailyAvailableMinHour
        } = data.data
        this.setData({
          approveStatus: authenticationStatus, // 认证状态（0：未认证 1：等待认证 2：未通过 3：已认证） ,
          startPunch,
          endPunch,
          todayMoney,
          clockType,
          sumDuration,
          sumMoney,
          wsPunchClockId
        })
        if (clockType === 1 && !wsPunchClockId) {
          this.setData({
            statusImage: `${imgServerUrl}/images/clock/clock-in.png`,
            statusIcon: `${imgServerUrl}/images/clock/clock-can.png`,
            statusMessage: '已进入考勤打卡范围'
          })
        }
        if (clockType === 1 && wsPunchClockId) {
          this.setData({
            statusImage: `${imgServerUrl}/images/clock/clock-out-disabled.png`,
            statusIcon: `${imgServerUrl}/images/clock/clock-waring.png`,
            statusMessage: `上班${dailyAvailableMinHour}小时后才能进行下班打卡`,
          })
        }
        if (clockType === 2 && wsPunchClockId) {
          this.setData({
            statusImage: `${imgServerUrl}/images/clock/clock-out.png`,
            statusIcon: `${imgServerUrl}/images/clock/clock-can.png`,
            statusMessage: `已进入考勤打卡范围`,
          })
        }
        if (clockType === 3) {
          this.setData({
            statusImage: `${imgServerUrl}/images/clock/clock-beyond.png`,
            statusIcon: `${imgServerUrl}/images/clock/clock-waring.png`,
            statusMessage: `请进入企业后再进行打卡`,
          })
        }
        if (clockType === 4) {
          this.setData({
            statusImage: `${imgServerUrl}/images/clock/clock-done.png`,
            statusIcon: `${imgServerUrl}/images/clock/clock-can.png`,
            statusMessage: `今日打卡已完成`,
          })
        }
      }).catch(data => {
        locationStatus = true
      }).finally(res => {
        if (showLoading) {
          wx.hideLoading()
        }
      })
    } catch (e) {
      wx.hideLoading()
      locationStatus = true
    }
  },
  reload() {
    if (locationStatus) {
      locationStatus = false
      this.load()
    } else {
      wx.showToast({
        icon: 'none',
        title: '请勿重复点击',
      })
    }
  },
  privacyCancel(){
    wx.switchTab({
      url: '/pages/index/index',
    })
  },
  async privacySubmit(){
    this.setData({
      userInfo: wx.getStorageSync('userInfo'),
      hpMember: wx.getStorageSync('hpMember')
    })
    await this.location()
    this.load()
    wx.onLocationChange((result) => {
      const { latitude, longitude } = result
      this.setData({
        latitude,
        longitude
      }, _ => {
        if (this.data.userInfo && this.data.hpMember && new Date().getTime() - nowTime > 60000) {
          this.load(false)
        }
      })
    })
    wx.startLocationUpdate({
      success: (res) => {
        console.log(res)
      },
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: async function () {

  },

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

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

  },

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

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

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})