<template>
  <view class="container">
    <uni-section title="异常隐患申报记录" type="line" class="mb-10">
      <template v-slot:right>
        <button size="mini" type="primary" @click.stop="addNew">新增</button>
      </template>
    </uni-section>

    <view class="filters">
      <uni-data-select v-model="queryParams.declarationType" :localdata="selectList" placeholder="申报类型" />
      <uni-datetime-picker type="daterange" v-model="dateRange" :clear-icon="true" start="1990-01-01" end="2099-12-31" />
      <button class="ml-6" size="mini" type="primary" @click="handleQuery">搜索</button>
      <button class="ml-6" size="mini" @click="resetQuery">重置</button>
    </view>

    <uni-card v-for="item in dataList" :key="item.id" :title="item.declarationLabel || '异常隐患申报'" @click="onCardClick($event, item)">
      <uni-row class="row" :width="730">
        <uni-col :span="16">
          <view>
            <text class="uni-body">申报人：{{ item.applyUser || '-' }}</text>
          </view>
          <view>
            <text class="uni-body">申报时间：{{ formatDate(item.occurTime) }}</text>
          </view>
          <view>
            <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.declarationImg)" :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 { listSafetyDeclaration } from '@/api/sidebar/sidebar.js';
import { listData } from '@/api/system/dict/data.js';
import config from '@/config';

export default {
  name: "FilingLog",
  data() {
    return {
      loadStatus: 'more',
      loading: false,
      total: 0,
      dataList: [],
      selectList: [],
      dateRange: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        declarationType: null,
        params: {}
      }
    }
  },
  created() {
    this.initDict()
    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: {
    async initDict() {
      try {
        const typeData = await listData({ dictType: 'hs_declaration_type' })
        this.selectList = typeData.rows.map(i => ({ value: i.dictValue, text: i.dictLabel }))
      } catch (e) {
        console.error('获取字典数据失败:', e)
        this.selectList = []
      }
    },
    imageUrl(path) {
      if (!path) return ''
      return config.baseUrl + path
    },
    firstThreeImages(declarationImg) {
      if (!declarationImg) return []
      if (typeof declarationImg === 'string') {
        return declarationImg.split(',').slice(0, 3)
      }
      return declarationImg.slice(0, 3)
    },
    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
      }
    },
    buildParams() {
      if (this.dateRange && this.dateRange.length === 2) {
        this.queryParams.params = {
          beginTime: this.dateRange[0],
          endTime: this.dateRange[1]
        }
      } else {
        this.queryParams.params = {}
      }
    },
    async fetchList({ append = false } = {}) {
      try {
        this.loading = true
        this.buildParams()
        const res = await listSafetyDeclaration(this.queryParams)
        const rows = res?.rows || []
        // 若接口提供 total 字段则使用，否则根据 pageSize 判断是否还有更多
        this.total = typeof res?.total === 'number' ? res.total : (append ? this.dataList.length + rows.length : rows.length)
        if (append) {
          this.dataList = this.dataList.concat(rows)
        } else {
          this.dataList = rows
        }
        // 根据是否还有更多数据设置加载状态
        if (typeof res?.total === 'number') {
          this.loadStatus = this.dataList.length < this.total ? 'more' : 'noMore'
        } else {
          // 当本次返回数量等于 pageSize，默认还有下一页
          const hasMore = rows.length === this.queryParams.pageSize
          this.loadStatus = hasMore ? 'more' : 'noMore'
        }
      } catch (e) {
        console.error('获取列表失败:', 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) {
      // 仅在内容区域点击时跳转（title/extra也可按需）
      if (!item) return
      this.goDetail(item)
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        declarationType: null,
        params: {}
      }
      this.dateRange = []
      this.getList()
    },
    addNew() {
      this.$tab.navigateTo('/pages/work/sidebar/safetyDeclaratio/index')
    },
    goDetail(item) {
      const id = item?.id
      if (!id) return
      this.$tab.navigateTo(`/pages/work/sidebar/filingDetail/index?id=${id}`)
    }
  }
}
</script>

<style lang="scss">
.container { 
  padding: 10px;
  background-color: #f8f9fa;
  min-height: 100vh;
}

.filters { 
  display: flex; 
  flex-direction: column;
  gap: 10px; 
  margin-bottom: 15px;
  padding: 15px;
  background: #fff;
  border-radius: 8px;
}

.thumbs {
  display: flex;
  gap: 6px;
  flex-wrap: wrap;
  justify-content: flex-end;
  
  .thumb {
    width: 50px;
    height: 50px;
    border-radius: 8px;
    background: #f5f5f5;
  }
}

.row {
  display: flex;
  align-items: flex-start;
}

.uni-body {
  font-size: 14px;
  color: #666;
  margin-bottom: 5px;
}

// 工具类
.mb-10 { 
  margin-bottom: 10px; 
}

.ml-6 { 
  margin-left: 6px; 
}
</style>