<template>
  <div class="panel panel-default auto repair-info-content">
    <div class="panel-body">
      <div class="auto repair-info-content compatible ">
        <div style="display: flex; margin-bottom: 20px">
          <div>上班打卡时间：</div>
          <div>{{record.f_onsite_time?.substring(11) || '未打卡'}}</div>
        </div>
        <div style="margin-bottom: 20px">
          <button class="btn btn-primary" @click="clockIn('上班')">上班打卡</button>
        </div>
        <div style="display: flex; margin-bottom: 20px">
          <div>下班打卡时间：</div>
          <div>{{record.f_offsite_time?.substring(11) || '未打卡'}}</div>
        </div>
        <div style="margin-bottom: 20px">
          <button class="btn btn-primary" @click="clockIn('下班')">下班打卡</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import Vue from 'vue'
  import {toStandardDateString, toStandardTimeString} from '../Util'
export default {
  title:'add-gas',
  data(){
    return{
      record: {
        id: undefined,
        f_user_id: Vue.user.id,
        f_user_name: Vue.user.name,
        f_onsite_time: '',
        f_offsite_time: ''
      }
    }
  },
  ready () {
    this.getTodayClockInRecord()
  },
  methods: {
    async getTodayClockInRecord(){
      const today = toStandardDateString()
      let res = await this.$resetpost('rs/sql/singleTable', {
        data: {
          tablename: 't_work_record',
          condition: `f_user_id = ${Vue.user.id} and f_onsite_time >= '${today} 00:00:00' and f_onsite_time <= '${today} 23:59:59'`
        }
      })
      console.log('res=', JSON.stringify(res))
      if (res.data.length > 0){
        this.record = res.data[0]
      }
    },
    clockIn(type) {
      const now = toStandardTimeString()
      const record = {
        id: this.record.id,
        f_user_id: this.record.f_user_id,
        f_user_name: this.record.f_user_name,
        f_onsite_time: this.record.f_onsite_time,
        f_offsite_time: this.record.f_offsite_time
      }
      if (type == '上班'){
        if (record.f_onsite_time) {
          this.$showMessage("今天已经上班打过卡了！")
          return
        }
        record.f_onsite_time = now
      }else if (type == '下班'){
        if (record.f_offsite_time) {
          this.$showMessage("今天已经下班打过卡了！")
          return
        }
        if (!record.f_onsite_time) {
          this.$showMessage("请先进行上班打卡！")
          return
        }
        record.f_offsite_time = now
      }
      this.$resetpost('rs/logic/saveWorkRecord', record).then((res) => {
        if (res.data.id){
          record.id = res.data.id
        }
        this.record = record
        this.$showMessage(`${type}打卡成功！`)
      })
    }
  }
}
</script>

