<template>
  <div class="page">
    <el-card shadow="never">
      <el-form inline>
        <el-form-item label="选择产品：" prop="productKey">
          <el-select v-model="params.productKey" filterable placeholder="请选择产品" @change="productChange">
            <el-option v-for="item in productList" :key="item.key" :label="item.name" :value="item.key">
              <span style="float: left">{{ item.name }}</span>
              <span style="float: right; font-size: 13px">{{ item.key }}</span>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="选择设备：" prop="deviceKey">
          <el-select v-model="params.deviceKey" filterable placeholder="请选择设备">
            <el-option v-for="item in deviceList" :key="item.key" :label="item.name" :value="item.key">
              <span style="float: left">{{ item.name }}</span>
              <span style="float: right; font-size: 13px;margin-left: 12px;">{{ item.key }}</span>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="选择属性：" prop="properties">
          <el-select v-model="params.properties" filterable placeholder="请选择属性" @change="propertyChange">
            <el-option v-for="item in propertyList" :key="item.key" :label="item.name" :value="item.key">
              <span style="float: left">{{ item.name }}</span>
              <span style="float: right; font-size: 13px">{{ item.key }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选择时间：" prop="dateRange">
          <el-date-picker v-model="params.dateRange" style="width: 360px" value-format="YYYY-MM-DD HH:mm:ss" format="YYYY-MM-DD HH:mm:ss" type="datetimerange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" :clearable="false">
          </el-date-picker>
          <el-button-group class="ml10">
            <el-button @click="changeDate(1)" :type="activeIndex == 1 ? 'primary' : ''">最近一小时</el-button>
            <el-button @click="changeDate(2)" :type="activeIndex == 2 ? 'primary' : ''">最近24小时</el-button>
            <el-button @click="changeDate(3)" :type="activeIndex == 3 ? 'primary' : ''">最近一周</el-button>
          </el-button-group>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getData">
            <el-icon>
              <ele-Search />
            </el-icon>
            查询
          </el-button>
          <el-button type="primary" @click="handlePrintChart">
            <el-icon>
              <ele-Printer />
            </el-icon>
            打印图表
          </el-button>
        </el-form-item>
      </el-form>
      <div class="title">
        <el-icon style="margin-right: 5px;">
          <ele-Histogram />
        </el-icon>
        指标趋势统计图
      </div>
      <Chart class="flex1" height="12vw" ref="chart" :autoLoading="false" style="margin-top: 20px;" v-loading="loading"></Chart>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue';
import { ElMessage } from 'element-plus';
import api from '/@/api/device';
import dayjs from 'dayjs';
import Chart from '/@/components/chart/index.vue'
import { getLineOption } from '/@/components/chart/options'
import { printChart } from '/@/utils/print';

const productList = ref<any[]>([])
const deviceList = ref<any[]>([])
const propertyList = ref<any[]>([])
const chart = ref()
const loading = ref(false)
const propertyName = ref('')
const activeIndex = ref(1);
const params = reactive({
  productKey: '',
  deviceKey: '',
  properties: '',
  dateRange: [dayjs().subtract(1, 'hour').format('YYYY-MM-DD HH:mm:ss'), dayjs().format('YYYY-MM-DD HH:mm:ss')],
})

api.product.getLists({ status: 1 }).then((res: any) => {
  productList.value = res.product || [];
});

// 仪表盘折线按钮
const changeDate = (key: number) => {
  if (!params.productKey) return ElMessage('请选选择产品')
  if (!params.deviceKey) return ElMessage('请选选择设备')
  if (!params.properties) return ElMessage('请选选择属性')
  // 1 近1小时 2近24小时 3近一周
  activeIndex.value = key;
  if (key === 1) {
    // 近1小时
    params.dateRange = [dayjs().subtract(1, 'hour').format('YYYY-MM-DD HH:mm:ss'), dayjs().format('YYYY-MM-DD HH:mm:ss')]
  } else if (key === 2) {
    // 近24小时
    params.dateRange = [
      dayjs().subtract(24, 'hour').format('YYYY-MM-DD HH:mm:ss'),
      dayjs().format('YYYY-MM-DD HH:mm:ss'),
    ]
  } else if (key === 3) {
    // 近一周
    params.dateRange = [
      dayjs().subtract(7, 'day').format('YYYY-MM-DD HH:mm:ss'),
      dayjs().format('YYYY-MM-DD HH:mm:ss'),
    ]
  }
  getData();
}

function getData() {
  if (!params.productKey) return ElMessage('请选选择产品')
  if (!params.deviceKey) return ElMessage('请选选择设备')
  if (!params.properties) return ElMessage('请选选择属性')

  loading.value = true
  api.analysis.deviceIndicatorTrend(params).then((data: any[]) => {
    const res = data || []
    chart.value.draw(
      getLineOption({
        datas: [res.map(item => item.dataValue)],
        xAxis: res.map(item => item.dataTime),
        legend: [propertyName.value],
        dataZoom: [{ // 这部分是dataZoom的配置
          type: 'slider', // 这里可以选择你需要的dataZoom类型
          start: 0, // 数据窗口范围的起始百分比
          end: 100,// 数据窗口范围的结束百分比
          xAxisIndex: [0, 2],
        }]
      })
    )
  }).finally(() => loading.value = false)
}

function productChange(productKey: string) {
  params.deviceKey = ''
  params.properties = ''
  deviceList.value = []
  propertyList.value = []
  api.device.allList({ productKey }).then((res: any) => {
    deviceList.value = res.device;
  });
  api.product.getpropertyList({ productKey }).then((res: any) => {
    propertyList.value = res;
  });
}

function propertyChange(property: string) {
  propertyName.value = propertyList.value.find(item => item.key === property)?.name
}

// 打印图表
const handlePrintChart = async () => {
  if (!chart.value) {
    ElMessage.warning('图表未加载');
    return;
  }
  await printChart(chart.value.$el);
};
</script>
<style scoped>
.title {
  font-size: 14px;
  font-weight: bold;
  border-bottom: 1px solid #eee;
  display: flex;
  align-items: center;
  padding-bottom: 6px;
}
</style>