<!-- 设备详情 -->
<script name="DeviceInfoDetail" lang="ts" setup>
import { ElMessage, ElMessageBox, dayjs } from 'element-plus'
import type { DateModelType } from 'element-plus'
import type { IDataDetailInfo, IListQuery } from '../../data/query/data-query'
import DataDetailDialog from '../../data/query/dataDetailDialog.vue'
import type { IDeviceInfo } from './device-info'
import type { TableColumn } from '@/components/NormalTable/table_interface'
import { getDeviceDataList } from '@/api/data/query'
import LineChart from '@/components/Echart/LineChart.vue'
import type { lineDataI } from '@/components/Echart/echart-interface'

// 从路由中传过来的参数
const type = ref<string>('')
const id = ref<string>('')

const route = useRoute()
const router = useRouter()
const title = ref('')

const basicFormRef = ref()

const deviceInfo = ref<IDeviceInfo>({
  id: '',
  devcode: '',
  deviceName: '',
  deviceType: '',
  deviceTypeName: '',
  status: '',
  statusName: '',
  cell: '',
  imei: '',
  iccid: '',
  model: '',
  modelName: '',
  encipherType: '',
  encipherTypeName: '',
  createTime: '',
  createUserId: '',
  createUserName: '',
  dataValue: '',
})

const dataQuery = ref<IListQuery>({
  keywords: '',
  beginTime: '',
  endTime: '', //
})
const dateRange = ref<[DateModelType, DateModelType]>(['', ''])// 筛选时间段数据
const dataColumns = ref<TableColumn[]>([
  { text: '采集时间', value: 'uptime', align: 'center', width: '200' },
  { text: '数值', value: 'ddata', align: 'center' },
])
const dataList = ref<Array<IDataDetailInfo>>([]) // 表格数据

const chartTimeArray = ref<Array<string>>([])
const yAxisData = ref<Array<number>>([])
const chartDataArray = ref<Array<lineDataI>>([])

const dataChartRef = ref()
const refDataDialog = ref()
const buttonIndex = ref<number>(2)

// 逻辑
const detailNoiseData = (row: IDataDetailInfo) => {
  refDataDialog.value.initDialog(row)
}

const searchList = () => {
  getDeviceDataList(dataQuery.value).then((res) => {
    if (res.code === 200) {
      dataList.value = res.data.slice() // 需要倒序排列 使用值复制

      chartTimeArray.value = []
      yAxisData.value = []

      res.data.reverse().forEach((data: IDataDetailInfo) => {
        chartTimeArray.value.push(data.uptime)
        yAxisData.value.push(parseFloat(data.ddata))
      })

      chartDataArray.value[0] = {
        name: '噪声值',
        data: yAxisData.value,
      }
    }
  })
}

const fastDateRangeChanged = (index: number) => {
  switch (index) {
    case 1:
      dataQuery.value.beginTime = dayjs().add(-3, 'month').format('YYYY-MM-DD')
      break

    case 2:
      dataQuery.value.beginTime = dayjs().add(-1, 'month').format('YYYY-MM-DD')
      break

    case 3:
      dataQuery.value.beginTime = dayjs().add(-1, 'week').format('YYYY-MM-DD')
      break
  }

  buttonIndex.value = index
  dataQuery.value.endTime = dayjs().add(1, 'day').format('YYYY-MM-DD')
  dateRange.value = [dataQuery.value.beginTime!, dataQuery.value.endTime]
}

const resetForm = () => {
  sessionStorage.removeItem('deviceInfo')
  router.go(-1)
}

const initDialog = (params: any) => {
  // 从路由中获取参数
  type.value = params.type
  id.value = params.id !== undefined ? params.id : ''

  deviceInfo.value = JSON.parse(sessionStorage.getItem('deviceInfo')!)

  switch (params.type) {
    case 'detail':
      title.value = '设备详情'
      id.value = params.id

      // 查询数据详情
      dataQuery.value.keywords = deviceInfo.value.devcode
      dataQuery.value.beginTime = dayjs().add(-1, 'month').format('YYYY-MM-DD')
      dataQuery.value.endTime = dayjs().add(1, 'day').format('YYYY-MM-DD')
      dateRange.value = [dataQuery.value.beginTime, dataQuery.value.endTime]
      searchList()

      break
    default:
      title.value = ''
      break
  }
}

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

    buttonIndex.value = 0
  }

  searchList()
})

onMounted(async () => {
  initDialog(route.query)
})
</script>

<template>
  <app-container>
    <detail-page :title="`${title}`">
      <template #btns>
        <el-button type="info" @click="resetForm()">
          关闭
        </el-button>
      </template>

      <el-form ref="basicFormRef" :model="deviceInfo" label-position="right" label-width="110px" stripe>
        <el-row :gutter="24">
          <!-- 第一行 第一列 -->
          <el-col :span="6">
            <el-form-item label="设备编号：">
              {{ deviceInfo.devcode }}
            </el-form-item>
          </el-col>

          <!-- 第一行 第二列 -->
          <el-col :span="6">
            <el-form-item label="设备型号：">
              {{ deviceInfo.modelName }}
            </el-form-item>
          </el-col>

          <!-- 第一行 第三列 -->
          <el-col :span="6">
            <el-form-item label="设备类型：">
              {{ deviceInfo.deviceTypeName }}
            </el-form-item>
          </el-col>

          <!-- 第一行 第四列 -->
          <el-col :span="6">
            <el-form-item label="安装时间">
              {{ deviceInfo.installDate }}
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </detail-page>

    <detail-block title="">
      <el-row :gutter="24">
        <el-col :span="6">
          设备数据情况
        </el-col>
        <el-col :span="18" align="right">
          <el-button ref="threeMonRef" round :type="buttonIndex === 1 ? 'primary' : ''" @click="fastDateRangeChanged(1)">
            近3月
          </el-button>
          <el-button ref="oneMonRef" round :type="buttonIndex === 2 ? 'primary' : ''" @click="fastDateRangeChanged(2)">
            近1月
          </el-button>
          <el-button ref="oneWeekRef" round :type="buttonIndex === 3 ? 'primary' : ''" @click="fastDateRangeChanged(3)">
            近1周
          </el-button>
          <search-item style="padding: 0 10px;">
            <el-date-picker v-model="dateRange" type="daterange" start-placeholder="采集时间（开始）" end-placeholder="采集时间（结束）" />
          </search-item>
        </el-col>
      </el-row>

      <el-row :gutter="24">
        <el-col :span="16">
          <line-chart ref="dataChartRef" :x-axis-data="chartTimeArray" :data="chartDataArray" height="500px" :gradient="false" />
        </el-col>

        <el-col :span="8">
          <normal-table
            :data="dataList" :columns="dataColumns"
            :pagination="false"
            :height="560"
          >
            <template #preColumns>
              <el-table-column label="序号" width="55" align="center">
                <template #default="scope">
                  {{ 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="detailNoiseData(row)">
                    查看
                  </el-button>
                </template>
              </el-table-column>
            </template>
          </normal-table>
        </el-col>
      </el-row>
    </detail-block>

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