<template>
    <div class="workplace">
      <div class='head'>
        <img class='photo' :src='photo' mode='aspectFill'>
        <div class='info' @tap='punchHelp'>
            <div class='name_vip'>
                <div class='name'>{{name}}</div>
                <img class='vip' src='/static/imgs/verified.png' mode='widthFix'>
            </div>
            <div class='status'>
                <img class='loading' v-if="scheduleState===''" src='/static/imgs/refresh.png'>
                {{scheduleState}}
                <img class='help' v-if="scheduleState && punchTime.length" src='/static/imgs/help.png'>
            </div>
        </div>
        <div class='schedule' :class='{_fade: !canICheckIn}' @tap='canICheckin' hover-class='fade'>{{morning ? '上班' : '下班'}}</div>
        <navigator url='../leaveList/main'>
          <div class="leave">
            请假记录
           <!-- <span :class="{'reddot':hasLeaveMessage}"></span>-->
          </div>
        </navigator>
      </div>
      <div class='nav'>
          <div class='nav-item' v-for='(item,i) in navArray' :key='i' @tap='moveSlide(i+1)'>
              <div class='num'>
                  <span style='color: #AA001A'>{{item.num + ' '}}</span>
                  <span>件</span>
              </div>
              <div class='title'>{{item.title}}</div>
          </div>
          <div class='slide' :class="{'moveToOne':moveToOne,'moveToThree':moveToThree}"></div>
      </div>
      <!--通知公告-->
      <navigator url='../noticeList/main'>
        <div class="notice">
          <div class="titicon"><img src='/static/imgs/notice.png'></div>
          <div class="list">
            <p>{{noticeTitle}}</p>
          </div>
        </div>
      </navigator>
      <!--通知公告-->
      <navigator class='report border-right' url='../affairs/main' hover-class='hover'><img src='/static/imgs/handle.png'><div>事务处理汇报</div></navigator>
      <navigator class='report' url='../releaselecture/main' hover-class='hover'><img src='/static/imgs/lecture.png'><div>讲座汇报</div></navigator>
      <div class='foot-title'>我的信息发布</div>

      <navigator class='foot' v-for='(v,i) in footArray' :key='i' hover-class='hover' :url="'../myrelease/main?type='+v.title">
          <img :src='v.img'>
          <div class='title'>{{v.title}}</div>
      </navigator>
      <div class='foot-title'>工具</div>
      <navigator class='foot' url='../LawsRegulations/main' hover-class='hover'><img src='/static/imgs/lawicon.png'><div class="title">法律法规</div></navigator>
      <!--<navigator class='foot' v-for='(v,i) in ToolArray' :key='i' hover-class='hover' :url="'../LawsRegulations/main?type='+v.title">
          <img :src='v.img'>
          <div class='title'>{{v.title}}</div>
      </navigator>-->
      <div class='red-background'></div>
    </div>
</template>

<script>
let isFirstLoad = true
export default {
  data() {
    return {
      photo: '',
      name: '',
      scheduleState: '',
      morning: true,
      canICheckIn: false,
      warning: '',
      punchTime: [],
      navArray: [
        { num: 0, title: '待回复' },
        { num: 0, title: '已回复' },
        { num: 0, title: '总咨询' }
      ],
      footArray: [
        { img: '/static/imgs/analyse.png', title: '案例分析' },
        { img: '/static/imgs/templet.png', title: '文书模板' },
        { img: '/static/imgs/law_lecture.png', title: '法制讲座' },
        { img: '/static/imgs/law.png', title: '普法动态' }
      ],
      ToolArray: [
        { img: '/static/imgs/lawicon.png', title: '法律法规' }
      ],
      moveToOne: false,
      moveToThree: false,
      hasHandleAuth: false,
      noticeTitle: '',
      hasLeaveMessage: false
    }
  },
  methods: {
    moveSlide(num) {
      switch (num) {
        case 1: {
          this.moveToOne = true
          this.moveToThree = false
          break
        }
        case 2: {
          this.moveToOne = false
          this.moveToThree = false
          break
        }
        case 3: {
          this.moveToThree = true
          this.moveToOne = false
          break
        }
      }
    },
    getLocation(comm_Name,targetPos,LSID) {
      wx.showLoading({ title: '正在打卡' })
      let lat, lng
      wx.getLocation({
        type: 'gcj02',
        success: res => {
          lat = res.latitude
          lng = res.longitude
          let content = ''
          let success = true
          if(targetPos.lng != 0){
            const dis = this.getDistance({lat,lng}, targetPos)
            content = `您与${comm_Name}的距离为:${dis}米\n有效打卡范围：800米`
            success = dis < 800
          }
          if (success) {
            wx.request({
              url: 'https://api.map.baidu.com/geocoder/v2/',
              data: {
                ak: 'AnWpq9Kc3C8cq5CCGAzsq3NxpBkxRnl0',
                location: `${lat},${lng}`,
                coordtype: 'gcj02ll',
                output: 'json'
              },
              success: res => {
                console.log(res)
                const address = res.data.result.sematic_description
                content = `您当前的位置:\n${address}\n` + content
                wx.request({
                  url: this.rootUrl + '/TSheet/punch',
                  header: {'content-type': 'application/x-www-form-urlencoded'},
                  method: 'POST',
                  data: {
                    sessionID: wx.getStorageSync('sessionID'),
                    latit: lat,
                    longi: lng,
                    address,
                    LSID,
                    pType: this.morning ? 'first' : 'second'
                  },
                  success: res => {
                    if (res.statusCode == '500') {
                      this.service.getUnionId(this.rootAvatar, this.rootUrl).then(res => {
                        this.getLocation(comm_Name,targetPos,LSID)
                      })
                    } else if(res.data==1){
                      wx.hideLoading()
                      wx.showModal({
                        title: '打卡成功',
                        content,
                        showCancel: false
                      })
                      this.refreshDuty()
                    }
                  }
                })
              }
            })
          } else {
            wx.hideLoading()
            wx.showModal({
              title: '打卡失败',
              content,
              showCancel: false
            })
          }
        },
        fail: err => {
          let authSetting
          wx.getSetting({
            success: res => {
              authSetting = res.authSetting['scope.userLocation']
              console.log(authSetting)
            },
            complete: () => {
              if (authSetting) {
                if (this.hasHandleAuth) {
                  console.log('nuhu')
                  this.getLocation(comm_Name,targetPos,LSID)
                } else {
                  const realName = wx.getStorageSync('userInfo').nickName
                  this.service.UploadBug(this.rootUrl,'test/getLocation/'+realName,JSON.stringify(err))
                  wx.showModal({
                    title: '打卡失败',
                    content: '微信未获得位置权限\n请在您手机的系统设置-权限管理中，打开微信的位置信息获取权限',
                    showCancel: false,
                    success: res => {
                      if (res.confirm) {
                        wx.hideLoading()
                      }
                    }
                  })
                }
              } else {
                wx.hideLoading()
                wx.showModal({
                  title: '授权请求',
                  content: '您已拒绝小程序获取地理位置，若要使用打卡功能，请重新授权',
                  showCancel: false,
                  success: res => {
                    if (res.confirm) {
                      wx.openSetting({
                        success: res => {
                          if (res.authSetting['scope.userLocation']) {
                            this.hasHandleAuth = true
                            this.getLocation(comm_Name,targetPos,LSID)
                          }
                        }
                      })
                    }
                  }
                })
              }
            }
          })
        }
      })
    },
    canICheckin() {
      wx.showLoading({title:'正在加载'})
      this.refreshDuty().then(res=>{
        if(res.allowed){
          wx.showModal({
            title:'',
            content:'确定要打卡吗？',
            success:res1=>{
              if(res1.confirm){
                this.getLocation(res.obj.comm_Name,res.obj.pos,res.obj.lsid)
              }
            }
          })
        }else{
          wx.showModal({
            title:'打卡失败',
            content: this.warning,
            showCancel: false
          })
        }
      })
    },

    getDistance(point1,point2) {
      const degreeToRad = (degree) => Math.PI * degree / 180 //将度转化为弧度
      const getRange = (v, a, b) => {//将v值限定在a,b之间，纬度使用
        if (a != null) {
          v = Math.max(v, a)
        }
        if (b != null) {
          v = Math.min(v, b)
        }
        return v
      }
      const getLoop = (v, a, b) => {//将v值限定在a,b之间，经度使用
        while (v > b) {
          v -= b - a
        }
        while (v < a) {
          v += b - a
        }
        return v
      }
      point1.lng = getLoop(point1.lng, -180, 180)
      point1.lat = getRange(point1.lat, -74, 74)
      point2.lng = getLoop(point2.lng, -180, 180)
      point2.lat = getRange(point2.lat, -74, 74)

      let x1, x2, y1, y2
      x1 = degreeToRad(point1.lng)
      y1 = degreeToRad(point1.lat)
      x2 = degreeToRad(point2.lng)
      y2 = degreeToRad(point2.lat)

      return parseInt(
        6370996.81 *
        Math.acos(
          Math.sin(y1) * Math.sin(y2) +
          Math.cos(y1) * Math.cos(y2) * Math.cos(x2 - x1)
        )
      )
    },
    refreshInfo() {
      const info = wx.getStorageSync('userInfo')
      if(info){
        this.name = info.nickName
        this.photo = info.avatarUrl
        wx.hideLoading()
      }
    },
    refreshDuty(){
      return new Promise(resolve=>{
        this.morning = new Date().getHours() < 12
        this.warning = ''
        wx.request({
          url: this.rootUrl + '/sch/infobyliid',
          method: 'POST',
          header: {'content-type': 'application/x-www-form-urlencoded'},
          data:{sessionID: wx.getStorageSync('sessionID')},
          success:res=>{
            if (res.statusCode == '500') {
              this.service.getUnionId(this.rootAvatar, this.rootUrl).then(res => {
                this.refreshDuty()
              })
            }else{
              const scheduleArr = res.data
              console.log(scheduleArr)
              if(scheduleArr.length==0){
                this.checkInSetter('非值班日','非值班日不能打卡')
                this.canICheckIn = false
                resolve({allowed:false})
                wx.hideLoading()
              }else {
                const first = scheduleArr[0].first_tsid > 0
                const second = scheduleArr[0].second_tsid > 0
                const canICheckIn = this.StateMachine(this.morning, first, second)
                if(canICheckIn){
                  this.punchTimeCheck().then(res=>{
                    if(!res){
                      this.canICheckIn = false
                      resolve({allowed:false})
                    }else{
                      const obj = {
                        comm_Name: scheduleArr[0].comm_Name,
                        pos: {
                          lat: scheduleArr[0].latit > 0 ? scheduleArr[0].latit : 0,
                          lng: scheduleArr[0].longi > 0 ? scheduleArr[0].longi : 0
                        },
                        lsid: scheduleArr[0].lsid
                      }
                      this.canICheckIn = true
                      resolve({allowed:true, obj})
                    }
                    wx.hideLoading()
                  })
                }else{
                  this.canICheckIn = false
                  resolve({allowed:false})
                  wx.hideLoading()
                }
              }
            }
          }
        })
      })
    },
    punchHelp() {
      if(this.scheduleState && this.punchTime.length)
        wx.showModal({
          title: '考勤说明',
          content: `值班日打卡时间段为:\n\n上午/上班打卡: ${this.punchTime[0]}\n下午/下班打卡: ${this.punchTime[1]}\n\n非值班日不能打卡`,
          showCancel: false
        })
    },
    getPunchTime(){
      return new Promise(resolve => {
        wx.request({
          url: this.rootUrl + '/ptime/all',
          success: res => {
            this.punchTime = res.data.map( v => {
              const clockIn = this.service.correctTime(v.clockIn,'full').slice(-5)
              const knockOff = this.service.correctTime(v.knockOff,'full').slice(-5)
              return clockIn + ' - ' + knockOff
            })
            resolve(res.data)
          }
        })
      })
    },
    punchTimeCheck(){
      return new Promise(resolve=>{
        this.getPunchTime().then( timeArr => {
          let time = timeArr[this.morning ? 0 : 1]
          time.clockIn = this.service.correctTime(time.clockIn,'DateObj')
          time.knockOff = this.service.correctTime(time.knockOff,'DateObj')

          const hourStart = time.clockIn.getHours()
          const hourEnd = time.knockOff.getHours()
          let minuteStart = time.clockIn.getMinutes()
          let minuteEnd = time.knockOff.getMinutes()
          const hour = new Date().getHours()
          const minute = new Date().getMinutes()
          if (
            (hour > hourStart && hour < hourEnd) ||
            (hour == hourStart && minute > minuteStart) ||
            (hour == hourEnd && minute < minuteEnd)
          ) {
            console.log(hourStart,minuteStart,hourEnd,minuteEnd)
            resolve(true)
          } else {
            if(this.warning==''){
              this.warning = `${this.morning?'上':'下'}班打卡时间段为\n${hourStart}:${('0'+minuteStart).slice(-2)} - ${hourEnd}:${('0'+minuteEnd).slice(-2)}\n请在规定时间段打卡`
            }
            resolve(false)
          }
        })
      })
    },
    checkInSetter(scheduleState,warning){
      this.scheduleState = scheduleState
      this.warning = warning
    },
    StateMachine(morning,first,second){
      const Arr2Str = [morning?1:0,first?1:0,second?1:0].join('')
      switch(Arr2Str){
        case '110': this.checkInSetter('值班中','上午只可进行一次打卡'); return false
        case '100': this.checkInSetter('未上班',''); return true
        case '011': this.checkInSetter('已下班','今日上下班打卡已完成\n不需要再打卡'); return false
        case '010': this.checkInSetter('值班中',''); return true
        case '001': this.checkInSetter('已下班','下午只可进行一次打卡'); return false
        case '000': this.checkInSetter('未上班',''); return true
      }
    },
    getUnionId(){
      this.service.getUnionId(this.rootAvatar,this.rootUrl).then( res => {
        if(res === 'unverified'){
          wx.setStorageSync('isVerify', false)
          wx.redirectTo({ url: '../verify/main' })
        }
        else this.replyNum()
      })
    },
    replyNum() {
      if(this.name === '') wx.showLoading({ title:'正在加载信息' })
      wx.request({
        url: this.rootUrl + '/conwx/lawcountun', //待回复
        data: { sessionID: wx.getStorageSync('sessionID') },
        success: res => {
          if(res.statusCode == '500'){
            this.getUnionId()
          }else{
            this.refreshInfo()
            this.refreshDuty()
            wx.request({
              url: this.rootUrl + '/conwx/lawcount', //已回复
              data:{ sessionID: wx.getStorageSync('sessionID') },
              success: res1 => {
                const navArray = [
                  { num: parseInt(res.data), title: '待回复' },
                  { num: parseInt(res1.data), title: '已回复' },
                  { num: parseInt(res.data) + parseInt(res1.data), title: '总咨询' }
                ]
                this.navArray = navArray
              }
            })
          }
        },
        fail: res => {
          if(res.errMsg=='request:fail url not in domain list'){
            wx.hideLoading()
            wx.showModal({
              title:'非法域名',
              content:'当前为测试服务器,请开启调试模式',
              showCancel:false
            })
          }
        }
      })
    },
    //取最新通知公告
    getNewNotice()  {
      wx.request({
        url: this.rootUrl + '/notice/getNewNotice',
        data: { sendType: "1" },
        success: res => {
            this.noticeTitle=res.data.messageTitle
        }
      })
    }
  },
  onShow() {
    this.getNewNotice()
    this.replyNum()
    this.getPunchTime()
  },
  onUnload(){
    this.hasLeaveMessage = false
    this.loaded = false
  }
}
</script>
<style lang="stylus" scoped>
.workplace
  position absolute
  min-height 100%
  width 100%
  Background()
  z-index 1
.head
  Flex(flex, , center)
  padding 50rpx
  position relative
  .photo
    Height_Width(120rpx)
    border-radius 50%
    margin-right 20rpx
    background-color rgba(255,255,255,.25)
  .info
    display flex
    flex-direction column
    height 120rpx
    BorderBox()
    color white
    .name_vip
      Flex(flex, , center)
      .name
        Font(32rpx)
      .vip
        Height_Width(46rpx,140rpx)
        margin-left 20rpx
    .status
      margin-top 15rpx
      Flex(flex,,center)
      height 27rpx
      Font(27rpx)
      img
        Height_Width(27rpx)
        &.loading
          animation loading 1s steps(12) infinite
        &.help
          margin-left 10rpx
  .schedule
    margin 0 0 0 auto
    width 130rpx
    border-radius 50%
    Font(35rpx, 130rpx, bold)
    text-align center
    color themeColor
    background white
  ._fade
    opacity .5 !important
.nav
  margin-bottom 20rpx
  Flex(flex, center)
  position relative
  Height_Width(180rpx, 94%)
  margin-left 3%
  border-radius 20rpx
  border 1rpx solid #EEE
  background white
  .nav-item
    Flex(flex, space-between, center, column)
    Font(30rpx, 50rpx)
    width 33%
    margin 40rpx 0
    &:nth-child(2)
      Border(0, 1rpx, 0, 1rpx)
      border-color #dedede
  .slide
    position absolute
    bottom 0
    Height_Width(3px, 27%)
    margin-left 0 auto 0 33.495%
    transition transform 0.3s
    background themeColor
  .moveToOne
    transform translateX(-123.44%)
  .moveToThree
    transform translateX(123.44%)
.border-right
  border-right 1rpx solid #EEE
.report
  Flex(inline-flex, center, center, column)
  width 50%
  padding 30rpx 0
  margin 20rpx 0
  background white
  BorderBox()
  Font(30rpx)
  img
    Height_Width(100rpx)
    margin-bottom 30rpx
.foot-title
  padding-left 30rpx
  background white
  Border(1rpx, 0, 1rpx, 0)
  Font(30rpx, 80rpx)
  font-weight bold
.title
  font-size 28rpx
.foot
  Flex(inline-flex, center, center, column)
  width 25%
  padding 30rpx 0
  background white
  Font(27rpx)
  img
    Height_Width(88rpx)
    margin-bottom 20rpx
.red-background
  position absolute
  top 0
  Height_Width(348rpx, 100%)
  background themeColor
  z-index -99
.leave
  position absolute
  bottom 20rpx
  left 185rpx
  width 140rpx
  padding 10rpx 0
  background-color rgba(255,255,255,.25)
  border-radius 6rpx
  color #fff
  font-size 26rpx
  text-align center
.notice
  width 100%
  height 90rpx
  padding 20rpx
  border-top 1rpx solid #eee
  border-bottom 1rpx solid #eee
  box-sizing border-box
  background-color #fff
  display inline-flex
.titicon
  width 25%
.titicon img
  width 160rpx
  height 50rpx
.list
  width 75%
.list p
  line-height 50rpx
  white-space nowrap
  overflow hidden
  text-overflow ellipsis
.reddot
  display inline-block
  width 16rpx
  height 16rpx
  border-radius 50%
  background-color red
  position absolute
  right -4rpx
  top -4rpx
</style>
