<!-- 设备列表 -->
<script name="DataQueryList" lang="ts" setup>
import type { DateModelType } from 'element-plus'
import { ElLoading, ElMessage, dayjs } from 'element-plus'
import type { IDataDetailInfo, IListQuery } from './data-query'
import DataDetailDialog from './dataDetailDialog.vue'
import type { IDictType } from '@/views/basic/common-interface'
import type { TableColumn } from '@/components/NormalTable/table_interface'
import { getDictByCode } from '@/api/system/dict'
import { exportFile } from '@/utils/exportUtils'
import { exportDeviceData, getDeviceDataListPage } from '@/api/data/query'

const props = defineProps({
  embedded: {
    type: Boolean,
    default: false,
  },
  devcode: {
    type: String,
    default: '',
  },
})

const refDataDialog = ref()

// 查询条件
const searchQuery = ref<IListQuery>({
  keywords: props.devcode === undefined ? '' : props.devcode,
  beginTime: '',
  endTime: '',
  offset: 1,
  limit: 20,
})
const dateRange = ref<[DateModelType, DateModelType]>(['', ''])// 筛选时间段数据
const total = ref(0) // 数据条数
const loadingTable = ref(false) // 表格loading

// 表头
const columns = ref<TableColumn[]>([
  { text: '设备编号', value: 'devcode', align: 'center', width: '200' },
  { text: '采集时间', value: 'uptime', align: 'center', width: '200' },
  { text: '数值', value: 'ddata', align: 'center' },
  { text: '信号强度', value: 'signalStr', align: 'center' },
  { text: '设备状态', value: 'status', align: 'center', width: '150' },
])
const dataList = ref<Array<IDataDetailInfo>>([]) // 表格数据

const statusDict = ref<Array<IDictType>>([])

// 逻辑
const joinSignalStr = (data: IDataDetailInfo) => {
  if (data.rsrp === undefined || data.rsrp === '') {
    return ''
  }
  else {
    return `pci：${data.pci}；rsrp：${data.rsrp}；snr：${data.snr}`
  }
}

// 跳转到新建的页面
const exportDeviceDataList = () => {
  if (dataList.value.length > 0) {
    const filename = `设备数据列表${new Date().valueOf()}.xlsx`

    const loading = ElLoading.service({
      lock: true,
      text: '下载中请稍后',
      background: 'rgba(255, 255, 255, 0.8)',
    })

    // 导出接口
    exportDeviceData(searchQuery).then((res) => {
      const blob = new Blob([res.data])
      exportFile(blob, filename)

      nextTick(() => {
        // 关闭loading
        loading.close()
      })
    }).catch(() => {
      loading.close()
    })
  }
  else {
    ElMessage.warning('无数据可导出数据')
  }
}

// 详情
const detail = (row: IDataDetailInfo) => {
  refDataDialog.value.initDialog(row)
}

// 数据查询
function fetchData(isNowPage = false) {
  loadingTable.value = true
  if (!isNowPage) {
    // 是否显示当前页，否则跳转第一页
    searchQuery.value.offset = 1
  }
  getDeviceDataListPage(searchQuery.value).then((response) => {
    if (response.code === 200) {
      dataList.value = response.data.rows.map((item: IDataDetailInfo) => {
        return {
          ...item,
          signalStr: joinSignalStr(item),
        }
      })
      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 = {
    keywords: props.devcode,
    beginTime: '',
    endTime: '',
    offset: 1,
    limit: 20,
  }
  dateRange.value = ['', '']
  fetchData(true)
}

// 获取在用状态字典值
const getStatusDict = async () => {
  getDictByCode('onlineStatus').then((res: any) => {
    if (res.code === 200) {
      statusDict.value = res.data
      sessionStorage.setItem('onlineStatus', JSON.stringify(statusDict.value))
    }
  })
}

const getDict = async () => {
  await getStatusDict()
}

const initQuerySearch = () => {
  if (props.embedded === false) {
    searchQuery.value.beginTime = dayjs(new Date().valueOf() - 3600 * 24 * 6 * 1000).format('YYYY-MM-DD')
    searchQuery.value.endTime = dayjs(new Date().valueOf() + 3600 * 24 * 1000).format('YYYY-MM-DD')
    dateRange.value = [searchQuery.value.beginTime, searchQuery.value.endTime]
  }
}

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

// 监听父组件传过来的值
watch(props, (val) => {
  // 如果是嵌入的页面 当devcode改变时则将查询条件进行修改
  if (val.embedded === true) {
    searchQuery.value.keywords = props.devcode
  }
})

onMounted(async () => {
  await getDict()
  initQuerySearch()
  searchList()
})
</script>

<template>
  <app-container>
    <!-- 筛选条件 -->
    <search-area :need-clear="true" @search="searchList" @clear="reset">
      <search-item>
        <el-input v-model="searchQuery.keywords" :disabled="props.embedded === true" placeholder="设备编号" clearable />
      </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>
        <el-button type="primary" @click="exportDeviceDataList">
          导出列表
        </el-button>
      </template>

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

        <template #columns>
          <el-table-column fixed="right" label="操作" align="center" width="80">
            <template #default="{ row }">
              <el-button size="small" type="primary" link @click="detail(row)">
                查看
              </el-button>
            </template>
          </el-table-column>
        </template>
      </normal-table>
    </table-container>

    <data-detail-dialog ref="refDataDialog" />
  </app-container>
</template>
