<!-- 环境记录单列表 -->
<script lang="ts" setup name="EnvironmentalList">
import { getCurrentInstance, ref } from 'vue'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import type { IEnvironmental, IListQuery, IRoomNumber } from './environmentalList_interface'
import { getTypeSelect } from '@/api/system/price'
import { exportEnvironmentRecord, getEnvironmentRecordDelete, getEnvironmentRecordList } from '@/api/business/lab/environmentRecord'
import type { TableColumn } from '@/components/NormalTable/table_interface'
import { printJSON } from '@/utils/printUtils'
import { exportFile } from '@/utils/exportUtils'
const { proxy } = getCurrentInstance() as any
const $router = useRouter()

// 查询参数
const listQuery = ref<IListQuery>({
  environmentCode: '', // 记录单编号
  roomNumber: '', // 房间号
  startTime: '', // 记录开始时间
  endTime: '', // 记录结束时间
  offset: 1, // 当前页
  limit: 20, // 多少条
})
const checkoutList = ref<string[]>([]) // 多选选中参数
const list = ref<IEnvironmental[]>([]) // 表格参数
const total = ref(0)
const loadingTable = ref(false) // 表格loading
const trainTime = ref('') // 记录时间数组
const roomNumberList = ref<IRoomNumber[]>([]) // 房间号
// 表头
const columns = ref<TableColumn[]>([
  { text: '记录单号', value: 'environmentCode', align: 'center', width: '160' },
  { text: '房间号', value: 'roomNumber', align: 'center' },
  { text: '记录人', value: 'recorder', align: 'center' },
  { text: '记录时间', value: 'recordTime', width: '180', align: 'center' },
  { text: '温度(℃)', value: 'temperature', align: 'center' },
  { text: '湿度(%)', value: 'humidity', align: 'center' },
  { text: '输出电压(V)', value: 'outputVoltage', align: 'center' },
  { text: '零地电压(V)', value: 'zeroGroundVoltage', align: 'center' },
])
// 时间变更
watch(trainTime, (val) => {
  if (val) {
    listQuery.value.startTime = `${val[0]}`
    listQuery.value.endTime = `${val[1]}`
  }
  else {
    listQuery.value.startTime = ''
    listQuery.value.endTime = ''
  }
})
// 查询列表
const fetchData = (isNowPage: boolean) => {
  // listQuery.value.startTime = trainTime.value[0] || ''
  // listQuery.value.endTime = trainTime.value[1] || ''
  loadingTable.value = true
  if (!isNowPage) {
    // 是否显示当前页，否则跳转第一页
    listQuery.value.offset = 1
  }
  getEnvironmentRecordList(listQuery.value).then((res) => {
    list.value = res.data.rows
    total.value = res.data.total
  })
  loadingTable.value = false
}
fetchData(true)

// 搜索
const searchList = () => {
  fetchData(true)
}

// 重置
const clearList = () => {
  listQuery.value = {
    environmentCode: '', // 记录单编号
    roomNumber: '', // 房间号
    startTime: '', // 记录开始时间
    endTime: '', // 记录结束时间
    offset: 1, // 当前页
    limit: 20, // 多少条
  }
  trainTime.value = ''
  fetchData(true)
}

// 导出
const exportAll = () => {
  const loading = ElLoading.service({
    lock: true,
    text: '下载中请稍后',
    background: 'rgba(255, 255, 255, 0.8)',
  })
  if (list.value.length > 0) {
    const params = {
      environmentCode: '', // 记录单编号
      roomNumber: '', // 房间号
      startTime: '', // 记录开始时间
      endTime: '', // 记录结束时间
      offset: 1, // 当前页
      limit: 20, // 多少条
      ids: checkoutList.value,
    }
    exportEnvironmentRecord(params).then((res) => {
      const blob = new Blob([res.data])
      exportFile(blob, '环境记录单列表.xlsx')
    })
  }
  else {
    ElMessage.warning('无数据可导出数据')
  }
  loading.close()
}

// 点击编辑/详情
const handleEdit = (row: IEnvironmental, pageType: 'edit' | 'detail') => {
  $router.push(`/lab/environmentalList/${pageType}/${row.id}`)
}

// 点击删除
const handleDelete = (row: IEnvironmental) => {
  ElMessageBox.confirm(
    `确认删除单号${row.environmentCode}吗？`,
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(() => {
      getEnvironmentRecordDelete({ id: row.id }).then((res) => {
        if (res.code === 200) {
          ElMessage.success('已删除')
          fetchData(true)
        }
      })
    })
}

// 多选框选中
const handleSelectionChange = (e: any) => {
  checkoutList.value = e.map((item: { id: string }) => item.id)
}

// 点击新增
const add = () => {
  $router.push('/lab/environmentalList/add')
}

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

// 获取房间号
getTypeSelect('roomNumber').then((res) => {
  roomNumberList.value = res.data
})

// 打印列表
function printList() {
  // 打印列
  const properties = columns.value.map((item) => {
    return {
      field: item.value,
      displayName: item.text,
    }
  })
  if (checkoutList.value.length <= 0 && list.value.length > 0) {
    printJSON(list.value, properties, '环境记录单列表')
  }
  else if (checkoutList.value.length > 0) {
    const printList = list.value.filter((item: IEnvironmental) => checkoutList.value.includes(item.id))
    printJSON(printList, properties, '环境记录单列表')
  }
  else {
    ElMessage.warning('无可打印内容')
  }
}
</script>

<template>
  <app-container>
    <search-area :need-clear="true" @search="searchList" @clear="clearList">
      <search-item>
        <el-input
          v-model.trim="listQuery.environmentCode"
          placeholder="记录编号"
          clearable
        />
      </search-item>
      <search-item>
        <el-select
          v-model="listQuery.roomNumber"
          clearable
          filterable
          placeholder="请选择房间号"
          size="default"
        >
          <el-option
            v-for="item in roomNumberList"
            :key="item.value"
            :label="item.name"
            :value="item.value"
          />
        </el-select>
      </search-item>
      <search-item>
        <el-date-picker
          v-model="trainTime"
          type="datetimerange"
          range-separator="到"
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
          start-placeholder="记录时间开始时间"
          end-placeholder="记录时间结束时间"
        />
      </search-item>
    </search-area>
    <table-container>
      <template #btns-right>
        <icon-button
          v-if="proxy.hasPerm('/lab/environmentalList/add')"
          icon="icon-add"
          title="新建"
          type="primary"
          @click="add"
        />
        <icon-button
          v-if="proxy.hasPerm('/lab/environmentalList/export')"
          icon="icon-export"
          title="导出"
          type="primary"
          @click="exportAll"
        />
        <icon-button
          v-if="proxy.hasPerm('/lab/environmentalList/print')"
          icon="icon-print"
          title="打印"
          type="primary"
          @click="printList"
        />
      </template>
      <normal-table
        :data="list"
        :total="total"
        :columns="columns"
        :query="listQuery"
        :list-loading="loadingTable"
        is-showmulti-select
        @change="changePage"
        @multiSelect="handleSelectionChange"
      >
        <template #preColumns>
          <el-table-column label="序号" width="55" align="center">
            <template #default="scope">
              {{ (listQuery.offset - 1) * listQuery.limit + scope.$index + 1 }}
            </template>
          </el-table-column>
        </template>
        <template #columns>
          <el-table-column label="操作" align="center" width="130" fixed="right">
            <template #default="{ row }">
              <el-button
                v-if="proxy.hasPerm('/measure/train/plan/edit')"
                size="small"
                type="primary"
                link
                @click="handleEdit(row, 'edit')"
              >
                编辑
              </el-button>
              <el-button
                size="small"
                link
                type="primary"
                @click="handleEdit(row, 'detail')"
              >
                详情
              </el-button>
              <el-button
                v-if="proxy.hasPerm('/measure/train/plan/delete')"
                size="small"
                link
                type="danger"
                @click="handleDelete(row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </template>
      </normal-table>
    </table-container>
  </app-container>
</template>
