
<style>
.form {
  padding: 20px 30px;
}

.row {
  margin: 30px 0;
  border-bottom: 2px solid grey;
}

.rowItem {
  margin: 0;
  padding: 0;
  display: inline-block;

  vertical-align: middle;
  height: 1.6rem;
}

.rowLeft {
  width: 30%;
}

.rowRight {
  width: 70%;
}

.rowRightElement {
  width: 100%;
}

.center {
  text-align: center;
}

.controlBtn {
  width: 250px;
  margin: 0 30px;
}
</style>

<template>
  <view>
    <view v-if="!isFilled" class="form">
      <view class="row">
        <view class="rowItem rowLeft center">
          <text>姓名</text>
        </view>
        <view class="rowItem rowRight center">
          <input class="rowRightElement" :value="formData.userRealname" disabled="true" />
        </view>
      </view>

      <view class="row">
        <view class="rowItem rowLeft center">
          <text>填报时间</text>
        </view>
        <view class="rowItem rowRight center">
          <input class="rowRightElement" :value="formData.time" disabled="true" />
        </view>
      </view>

      <view class="row">
        <view class="rowItem rowLeft center">
          <text>地址</text>
        </view>
        <view class="rowItem rowRight center" @tap="chooseLocation">
          <input class="rowRightElement" placeholder="点击获取当前位置" v-model="formData.address" disabled="true"
            maxlength="500" />
        </view>
      </view>

      <view class="row">
        <view class="rowItem rowLeft center">
          <text>今日体温</text>
        </view>
        <view class="rowItem rowRight center">
          <radio-group class="rowRightElement" @change="(e) => formData.temperature = e.detail.value">
            <radio value="0" checked="true" />正常&nbsp;
            <radio value="1" />异常(≥37.3°)
          </radio-group>
        </view>
      </view>

      <view class="tips-area">
        <view class="tips" style="color: red;">
          * 本人承诺以上所填报的内容全部真实，并愿意承担相应责任。
        </view>
      </view>

      <view style="text-align: center;">
        <button class="controlBtn" size="mini" type="none" @tap="myreport">历史填报</button>
        <button class="controlBtn" size="mini" type="primary" @tap="report">提交</button>
      </view>

      <textarea v-if="this.debugMode" maxlength="-1" disabled="true" auto-height="true" style="width: 100%"
        :value="JSON.stringify(formData, null, 8)"></textarea>
    </view>
    <view v-else style="text-align: center;">
      <!--  -->
      <view style="margin: 40px 0;">{{ filledMsg }}</view>
      <button class="controlBtn" size="mini" type="none" @tap="myreport">历史填报</button>
    </view>
  </view>
</template>

<script>
import Taro from '@tarojs/taro'
import utils from '../../utils/utils'

export default {
  data() {
    return {
      ...Taro.getApp().globalData,
      userInfo: null,
      timeInterval: null,
      formData: {
        userId: '',
        userRealname: '',
        address: '',
        time: '',
        timestamp: '',
        temperature: 0,
      },
      // 是否填报过
      isFilled: true,
      filledMsg: "",
    }
  },

  onShow() {
    console.log('onShow')
    this.userInfo = Taro.getStorageSync("userInfo")
    console.log("this.userInfo", this.userInfo)

    this.formData.userId = this.userInfo.id
    this.formData.userRealname = this.userInfo.realname
    this.updateTime();
    this.timeInterval = setInterval(this.updateTime, 1000);

    // 获取用户当日是否填报过
    Taro.showLoading({ title: '加载中' })
    var that = this;
    Taro.request({
      url: `${this.baseUrl}/access/report/getLatestRecord`,
      method: "POST",
      header: {
        "Content-Type": "application/x-www-form-urlencoded" //用于post
      },
      data: {
        userId: this.userInfo.id
      },
      success: function (d) {
        Taro.hideLoading()
        let result = d.data
        console.log("result", result)
        if (result.success) {
          console.log("result.data", result.data);
          if (result.data == null || new Date(result.data.time) < new Date(new Date().toISOString().substring(0, 10))) {
            // 如果没有填报记录，或者填报记录不是今天，那么说明没有填报过
            that.isFilled = false
          } else {
            // 有今日记录，说明已经填报过
            that.isFilled = true
            that.filledMsg = "您已完成今日体温填报"
          }
        } else {
          Taro.showToast({
            title: "加载填报信息失败",
            icon: 'error',
            duration: 2000
          })
        }
      },
      fail: function () {
        Taro.hideLoading()
        Taro.showToast({
          title: "请求失败",
          icon: 'error',
          duration: 2000
        })
      },
      complete: function () {
        Taro.hideNavigationBarLoading();
      }
    })
  },

  onHide() {
    console.log('onHide')
    clearInterval(this.timeInterval)
  },

  methods: {
    updateTime() {
      this.formData.timestamp = Date.now();
      this.formData.time = utils.formatTime(new Date(this.formData.timestamp));
    },
    chooseLocation: async function () {
      Taro.showLoading({ title: '正在定位' })
      await new Promise((resolve) => {
        Taro.getSetting({
          success(res) {
            if (!res.authSetting['scope.userLocation']) {
              Taro.authorize({
                scope: 'scope.userLocationBackground',
                success() {
                  resolve();
                }
              })
            } else {
              resolve();
            }
          }
        })
      });
      var that = this;
      Taro.chooseLocation({
        success: function (res) {
          that.formData.address = res.address;
        },
        fail: function () {
          if (!that.formData.address) {
            Taro.showToast({
              title: "请获取当前位置",
              icon: 'error'
            })
          }
        },
      })
      Taro.hideLoading()
    },
    // 体温上报 提交按钮
    report() {
      console.log("点击提交", "this.formData", this.formData)
      if (!this.formData.address) {
        Taro.showToast({
          title: "请获取当前位置",
          icon: 'error'
        })
        return;
      }
      Taro.showLoading({ title: '加载中' })
      var that = this;
      Taro.request({
        url: `${this.baseUrl}/access/report/submit`,
        method: "POST",
        header: {
          "Content-Type": "application/x-www-form-urlencoded" //用于post
        },
        data: {
          ...this.formData,
        },
        success: function (d) {
          that.debugMode && console.log("begin success")
          Taro.hideLoading()
          let result = d.data;
          if (result.success) {
            // 填报完成
            that.isFilled = true
            that.filledMsg = "您已完成今日体温填报"
            console.log("result.data", result.data);
            Taro.showToast({
              title: "填报成功",
              icon: 'success',
              duration: 2000
            })
          } else {
            Taro.showToast({
              title: result.msg,
              icon: 'error',
              duration: 2000
            })
          }
          that.isShow = ''
          that.debugMode && console.log("end success")
        },
        fail: function () {
          that.debugMode && console.log("begin fail")
          Taro.hideLoading()
          Taro.showToast({
            title: "请求失败",
            icon: 'error',
            duration: 2000
          })
          that.debugMode && console.log("end fail")
        },
        complete: function () {
          that.debugMode && console.log("begin complete")
          if (typeof (callback) === "function")
            callback();
          Taro.hideNavigationBarLoading();
          that.debugMode && console.log("end complete")
        }
      })
    },
    // 历史填报
    myreport() {
      Taro.navigateTo({
        url: "/pages/residents/reportHistory"
      })
    }
  }
}
</script>
