<template>
  <view class="home">
    <view class="nav">
      <view :style="{ paddingTop }">
        <view class="title" :style="[{ height }, { lineHeight: height }]">
          <view class="back" @click="goBack()">
            <u-icon name="arrow-left" color="#ffffff" size="22"></u-icon>
          </view>
          <text>打卡</text>
        </view>
      </view>
    </view>
    <view class="main">
      <view class="main-header">
        <view class="user-info">
          <image class="user-img" src="@/static/images/user.jpg" mode="scaleToFill" />
          <view class="info flex1 flex-column flex_1">
            <u-text :lines="1" size="32rpx" :bold="true" :text="nickName"></u-text>
            <u-text :lines="1" size="24rpx" :text="postName"></u-text>
          </view>
        </view>
        <view class="more" @click="showCheckList">
          <u-icon name="order" size="60rpx"></u-icon>
          <u-text :lines="1" size="24rpx" text="打卡记录"></u-text>
        </view>
      </view>
      <view class="main-container">
        <template v-if="!showList">
          <view class="btn" @click="checkIn">打卡</view>
          <view class="location">
            <u-text @click="getLocation" :lines="1" :block="true" align="center" size="32rpx" :text="address">
            </u-text>
            <u-loading-icon mode="circle" size="24rpx" :show="show"></u-loading-icon>
          </view>
        </template>
        <u-list @scrolltolower="scrolltolower" v-else>
          <u-list-item v-for="(item, index) in checkList" :key="index">
            <u-cell :title="item.punchTime" :label="item.punchLocation">
            </u-cell>
          </u-list-item>
        </u-list>
      </view>
    </view>
    <u-toast ref="uToast"></u-toast>
    <!-- <uni-file-picker file-mediatype="all" v-model="imageValue" @select="select" @progress="progress" @success="success"
      @fail="fail" ref="upload" limit="1">
      <view class="upload-btn">
        <u-icon name="plus-circle-fill" color="blue" size="28"></u-icon>
      </view>
    </uni-file-picker> -->
  </view>
</template>

<script>
  import {
    mapGetters
  } from 'vuex'
  import to from 'await-to-js'
  import api from '@/api/system'
  export default {
    data() {
      return {
        height: '',
        paddingTop: '',
        address: '获取定位',
        form: {
          punchLat: 0,
          punchLng: 0,
          punchLocation: '',
          punchImg: ''
        },
        show: false,
        imageValue: [],
        showList: false,
        checkList: [],
        queryForm: {
          pageNum: 1,
          pageSize: 10
        }
      }
    },
    computed: {
      ...mapGetters(['nickName', 'postName']),
    },
    created() {
      this.getLocation()
      const navData = uni.getMenuButtonBoundingClientRect()
      this.height = navData.height + 'px'
      this.paddingTop = navData.top + 'px'
    },
    methods: {
      getLocation() {
        this.show = true
        const _this = this
        uni.getLocation({
          type: 'wgs84',
          success: function(res) {
            const latitude = res.latitude.toString();
            const longitude = res.longitude.toString();
            uni.request({
              header: {
                "Content-Type": "application/text"
              },
              url: process.uniEnv.VUE_APP_PROTOCOL + 'apis.map.qq.com/ws/geocoder/v1/?location=' + latitude + ',' + longitude +
                '&key=6REBZ-BRN6J-BMAFY-FIRI3-SMK43-G3FXU',
              success(re) {
                if (re.statusCode === 200) {
                  _this.address = re.data.result.address;
                  _this.form = {
                    punchLat: latitude,
                    punchLng: longitude,
                    punchLocation: re.data.result.address
                  }
                  _this.show = false
                } else {
                  _this.address = '点击重试'
                  this.$refs.uToast.show({
                    type: 'error',
                    message: '定位失败，请重试',
                  })
                }
              },
              fail: err => _this.show = false
            });
          },
          fail: err => _this.show = false
        });
      },
      async checkIn() {
        if (!this.form.punchLat || !this.form.punchLng) {
          this.address = '点击重试'
          return this.$refs.uToast.show({
            type: 'error',
            message: '定位失败，请重试',
          })
        }
        // console.log(this.$refs.upload);
        // this.$refs.upload.choose()
        const [err, res] = await uni.chooseImage({
          count: 1, //默认9
          sizeType: ['original'], //可以指定是原图还是压缩图，默认二者都有
          sourceType:['camera']
        })
        // console.log(res, 'rs');
        if (err) return
        this.select(res)
        res.tempFiles[0].name = (new Date()).getTime() + ''
        res.tempFiles[0].type = ''
        // console.log(res.tempFiles[0], typeof res.tempFiles[0])
      },
      // // 选择上传触发函数
      select(e) {
        let url = process.uniEnv.VUE_APP_UPLOAD_WEED
        uni.request({
          url, //仅为示例，并非真实接口地址。
          success: (res) => {
            this.uploadFiles(e, res.data)
          },
        })
      },
      // 上传函数
      async uploadFiles(e, res) {
        let action = process.uniEnv.VUE_APP_PROTOCOL + res.publicUrl + '/' + res.fid
        uni.uploadFile({
          url: action,
          filePath: e.tempFilePaths[0],
          name: 'file',
          formData: {
            file: e.tempFiles[0],
          },
          success: (res) => {
            this.form.punchImg = action
            api.checkIn(this.form).then(res => {
              this.$refs.uToast.show({
                type: 'success',
                message: '打卡成功',
              })
            })
          },
          fail: () => {
            console.log('err')
          },
        })
      },
      showCheckList() {
        if (!this.showList) this.loadCheckList()
        this.showList = !this.showList
      },
      async loadCheckList() {
        this.loadStatus = 'loading'
        const [err, res] = await to(api.getCheckList(this.queryForm))
        if (err) {
          this.loadStatus = 'nomore'
          return
        }
        if (res && res.code == 200) {
          // this.checkList = [...this.checkList, ...(res.data.list || [])]
          this.checkList = res.data.list
          this.total = res.data.total
          this.loadStatus = this.checkList.length == this.total ? 'nomore' : 'loadmore'
        } else {
          this.loadStatus = 'nomore'
        }

      },
      scrolltolower() {
        if (this.list.length < this.total && this.loadStatus != 'loading') {
          this.queryForm.pageNum++
          this.$u.throttle(this.loadCheckList(), 2000, false)
        }
        this.loadCheckList()
      },
      goBack() {
        uni.navigateBack({
          //关闭当前页面，返回上一页面或多级页面。
          delta: 1,
        })
      },
    }
  }
</script>
<style lang="scss" scoped>
  /deep/ .uni-file-picker {
    display: none;
  }

  .home {
    padding-top: 188rpx;
    height: 100%;

    .nav {
      position: absolute;
      left: 0;
      top: 0;
      width: 100%;
      height: 284rpx;
      background: #3e7ef8;

      .title {
        position: relative;
        text-align: center;
        font-size: 32rpx;
        font-weight: bold;
        color: #ffffff;

        .back {
          position: absolute;
          top: 0;
          bottom: 0;
          margin: auto;
          left: 70rpx;
          display: flex;
        }
      }
    }

    .main {
      display: flex;
      flex-direction: column;
      position: absolute;
      width: 100%;
      height: calc(100vh - 188rpx);
      background: #ffffff;
      box-shadow: 0 6rpx 19rpx 2rpx rgba(0, 45, 132, 0.15);
      border-radius: 31rpx 31rpx 0 0;
      padding: 0 32rpx;
      overflow: hidden;
      padding-bottom: 64rpx;

      .main-header {
        padding: 20rpx 40rpx;
        display: flex;
        justify-content: space-between;

        .user-info {
          display: flex;

          .user-img {
            width: 116rpx;
            height: 116rpx;
            border-radius: 50%;
            margin-right: 32rpx;
          }

          .info {
            height: 116rpx;
            margin-right: 32rpx;
          }
        }

        .more {
          display: flex;
          flex-direction: column;
          align-items: center;
        }
      }

      .main-container {
        flex: 1;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;

        .btn {
          width: 300rpx;
          height: 300rpx;
          border-radius: 50%;
          background: linear-gradient(70deg, #3e7ef8, #1d66dc);
          display: flex;
          justify-content: center;
          align-items: center;
          color: #fff;
          font-size: 48rpx;
          font-weight: bold;
          box-shadow: 0 6rpx 19rpx 2rpx rgba(29, 102, 220, 0.2);
          margin-bottom: 40rpx;
        }

        .location {
          display: flex;
          height: 32rpx;
          line-height: 32rpx;
        }
      }
    }
  }
</style>
