<!-- 环境记录单列表页 -->
<script name="EnvironmentRecordList" lang="ts" setup>
import dayjs from 'dayjs'
import type { DateModelType } from 'element-plus'
import type { IListQuery, ILocation, IRecordInfo } from './record-interface'
import type { TableColumn } from '@/components/NormalTable/table_interface'
import { getEnvDataRecordList, getLocationList } from '@/api/resource/environment'

const { proxy } = getCurrentInstance() as any
const router = useRouter()

// 查询条件
const searchQuery = ref<IListQuery>({
  recordNo: '', // 环境记录单编号
  locationId: '', // 地点
  createStartTime: '', // 创建开始时间
  createEndTime: '', // 创建结束时间
  offset: 1,
  limit: 20,
})
const dateRange = ref<[DateModelType, DateModelType]>(['', ''])// 筛选时间段数据
const total = ref(0) // 数据条数
const loadingTable = ref(false) // 表格loading

// 表头
const columns = ref<TableColumn[]>([
  { text: '环境记录单编号', value: 'recordNo', align: 'center' },
  { text: '地点', value: 'locationName', align: 'center' },
  { text: '温度（℃）', value: 'temperature', align: 'center', width: '150' },
  { text: '湿度（%）', value: 'humidity', align: 'center', width: '150' },
  { text: '氧气浓度（ppm）', value: 'oxygenDensity', align: 'center', width: '150' },
  { text: '烟雾值（mg/m³）', value: 'smokeValue', align: 'center', width: '150' },
  { text: '创建时间', value: 'createTime', align: 'center', width: '180' },
])
const envDataList = ref<Array<IRecordInfo>>([]) // 表格数据

const locationList = ref<Array<ILocation>>([])

// 逻辑
const envRecordSetting = () => {
  router.push({
    path: '/environment/setting',
  })
}

// 数据查询
function fetchData(isNowPage = false) {
  loadingTable.value = true
  if (!isNowPage) {
    // 是否显示当前页，否则跳转第一页
    searchQuery.value.offset = 1
  }
  getEnvDataRecordList(searchQuery.value).then((response) => {
    if (response.code === 200) {
      envDataList.value = response.data.rows
      total.value = parseInt(response.data.total)
    }
    loadingTable.value = false
  }).catch(() => {
    loadingTable.value = false
  })
}

const searchList = () => {
  fetchData(true)
}

// 页数发生变化后的操作，可能是页码变化，可能是每页容量变化，此函数必写
const changePage = (val: { size?: number; page?: number }) => {
  if (val && val.size) {
    searchQuery.value.limit = val.size
  }
  if (val && val.page) {
    searchQuery.value.offset = val.page
  }
  fetchData(true)
}

// 重置
const reset = () => {
  searchQuery.value = {
    recordNo: '', // 环境记录单编号
    locationId: '', // 地点
    createStartTime: '', // 创建开始时间
    createEndTime: '', // 创建结束时间
    offset: 1,
    limit: 20,
  }
  dateRange.value = ['', '']
  fetchData(true)
}

// 获取地点列表
const getLocationListForSelector = () => {
  getLocationList({ limit: 1000, offset: 1 }).then((res: any) => {
    if (res.code === 200) {
      locationList.value = res.data.rows
      sessionStorage.setItem('envlocationList', JSON.stringify(locationList.value))
    }
  })
}

watch(dateRange, (val) => {
  if (val) {
    searchQuery.value.createStartTime = dayjs(val[0]).format('YYYY-MM-DD HH:mm:ss') === 'Invalid Date' ? '' : dayjs(val[0]).format('YYYY-MM-DD HH:mm:ss')
    searchQuery.value.createEndTime = dayjs(val[1]).format('YYYY-MM-DD HH:mm:ss') === 'Invalid Date' ? '' : dayjs(val[1]).format('YYYY-MM-DD HH:mm:ss')
  }
  else {
    searchQuery.value.createStartTime = ''
    searchQuery.value.createEndTime = ''
  }
})

onMounted(async () => {
  getLocationListForSelector()
  searchList()
})
</script>

<template>
  <app-container>
    <!-- 筛选条件 -->
    <search-area :need-clear="true" @search="searchList" @clear="reset">
      <search-item>
        <el-input v-model="searchQuery.recordNo" placeholder="环境记录单编号" clearable />
      </search-item>
      <search-item>
        <el-select v-model="searchQuery.locationId" placeholder="地点" clearable>
          <el-option v-for="item in locationList" :key="item.id" :value="item.id" :label="item.locationName" />
        </el-select>
      </search-item>
      <search-item>
        <el-date-picker v-model="dateRange" type="daterange" start-placeholder="创建时间（开始）" end-placeholder="创建时间（结束）" />
      </search-item>
    </search-area>

    <!-- 表格数据展示 -->
    <table-container title="环境记录单列表">
      <!-- 表头区域 -->
      <template #btns-right>
        <icon-button v-if="proxy.hasPerm(`/resource/seal/list/add`)" icon="icon-setting" title="设置" @click="envRecordSetting" />
      </template>

      <!-- 表格区域 -->
      <normal-table
        :data="envDataList" :total="total" :columns="columns"
        :query="{ limit: searchQuery.limit, offset: searchQuery.offset }"
        :list-loading="loadingTable"
        @change="changePage"
      >
        <template #preColumns>
          <el-table-column label="序号" width="55" align="center">
            <template #default="scope">
              {{ (searchQuery.offset - 1) * searchQuery.limit + scope.$index + 1 }}
            </template>
          </el-table-column>
        </template>
        <template #columns />
      </normal-table>
    </table-container>
  </app-container>
</template>

