<template>
  <view class="container">
    <uni-section title="用户打卡列表" type="line" class="mb-10">
      <template v-slot:right>
        <button class="ml-6" size="mini" type="primary" @click="handleQuery">搜索</button>
        <button class="ml-6" size="mini" @click="resetQuery">重置</button>
      </template>
    </uni-section>

    <view class="filters">
      <uni-datetime-picker type="daterange" v-model="dateRange" :clear-icon="true" start="1990-01-01" end="2099-12-31" />
    </view>

    <uni-card v-for="item in list" :key="item.id || item.recordId" :title="item.inspectionPoint" @click="onCardClick($event, item)">
      <uni-row class="row" :width="730">
        <uni-col :span="16">
          <view>
            <text class="uni-body">打卡时间：{{ formatDate(item.inspectionTime) }}</text>
          </view>
          <view>
            <text class="uni-body">巡检人：{{ item.inspectorUser || item.inspectorId || '-' }}</text>
          </view>
          <view v-if="item.remark">
            <text class="uni-body">备注：{{ item.remark }}</text>
          </view>
        </uni-col>
        <uni-col :span="8">
          <view class="thumbs">
            <image v-for="(img,idx) in firstThreeImages(item.inspectionImg || item.clockInImg || item.signImg)" :key="idx" :src="imageUrl(img)" mode="aspectFill" class="thumb" />
          </view>
        </uni-col>
      </uni-row>
    </uni-card>
    <uni-load-more :status="loadStatus" />
  </view>
</template>

<script>
import { listRecord } from '@/api/inspection/record.js';
import config from '@/config';

export default {
  data() {
    return {
      loadStatus: 'more',
      loading: false,
      total: 0,
      list: [],
      dateRange: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        inspectionPoint: '',
        inspectorUser: this.$store?.state?.user?.nickName || '',
        params: {}
      }
    }
  },
  created() {
    this.getList()
  },
  onReachBottom() {
    if (this.loadStatus !== 'more' || this.loading) return
    this.loadStatus = 'loading'
    this.queryParams.pageNum += 1
    this.fetchList({ append: true })
  },
  onShow() {
    this.getList()
  },
  methods: {
    buildParams() {
      if (this.dateRange && this.dateRange.length === 2) {
        this.queryParams.params = {
          beginTime: this.dateRange[0],
          endTime: this.dateRange[1]
        }
      } else {
        this.queryParams.params = {}
      }
    },
    imageUrl(path) {
      if (!path) return ''
      if (/^https?:\/\//.test(path)) return path
      return config.baseUrl + (path.startsWith('/') ? path : ('/' + path))
    },
    firstThreeImages(imgs) {
      if (!imgs) return []
      if (Array.isArray(imgs)) return imgs.slice(0,3)
      if (typeof imgs === 'string') return imgs.split(',').filter(Boolean).slice(0,3)
      return []
    },
    formatDate(val) {
      if (!val) return ''
      try {
        const d = new Date(val)
        const y = d.getFullYear()
        const m = String(d.getMonth()+1).padStart(2,'0')
        const dd = String(d.getDate()).padStart(2,'0')
        const hh = String(d.getHours()).padStart(2,'0')
        const mm = String(d.getMinutes()).padStart(2,'0')
        const ss = String(d.getSeconds()).padStart(2,'0')
        return `${y}-${m}-${dd} ${hh}:${mm}:${ss}`
      } catch(e) { return val }
    },
    async fetchList({ append = false } = {}) {
      try {
        this.loading = true
        this.buildParams()
        const res = await listRecord(this.queryParams)
        const rows = res?.rows || []
        this.total = typeof res?.total === 'number' ? res.total : (append ? this.list.length + rows.length : rows.length)
        if (append) {
          this.list = this.list.concat(rows)
        } else {
          this.list = rows
        }
        if (typeof res?.total === 'number') {
          this.loadStatus = this.list.length < this.total ? 'more' : 'noMore'
        } else {
          const hasMore = rows.length === this.queryParams.pageSize
          this.loadStatus = hasMore ? 'more' : 'noMore'
        }
      } catch (e) {
        this.loadStatus = 'noMore'
      } finally {
        this.loading = false
      }
    },
    async getList() {
      this.queryParams.pageNum = 1
      this.loadStatus = 'loading'
      await this.fetchList({ append: false })
    },
    onCardClick(type, item) {
      if (!item) return
      this.goDetail(item)
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        inspectionPoint: '',
        inspectorUser: this.$store?.state?.user?.nickName || '',
        params: {}
      }
      this.dateRange = []
      this.getList()
    },
    goDetail(item) {
      const id = item?.id || item?.recordId
      if (!id) return
      this.$tab.navigateTo(`/pages/work/inspection/checkInDetail/index?id=${id}`)
    }
  }
}
</script>

<style lang="scss">
.container { padding: 10px; }
.filters { display: flex; gap: 8px; align-items: center; margin-bottom: 10px; }
.thumbs { display: flex; gap: 6px; justify-content: flex-end; }
.thumb { width: 60px; height: 60px; border-radius: 6px; background: #f5f5f5; }
.mb-10 { margin-bottom: 10px; }
.ml-6 { margin-left: 6px; }
.row { }
</style>