import request from '@/utils/request'
import config from '@/myConfig/config'

const headers = {
  Authorization: 'Token ' + config.token, // 使用this.token来引用token值
  isToken: false,
}

export function getChartsData() {
  // SELECT MEAN("temperature_1")
  const query = ` 
        SELECT MEAN(*) 
        FROM "sensor_test" 
        WHERE time >= now() - 120s
        GROUP BY time(1s) FILL(none)
    `
  return request({
    baseURL: '/api',
    url: '/query?org=myorg&db=mybucket&q=' + query, // 如果是 InfluxDB v2.x, 这应该是 '/api/v2/query'
    headers,
    method: 'post' // 使用 POST 方法
  })
}

export function getNewChartsData(params, bucketName, time, step) {
  const query = ` 
      SELECT ${params} 
      FROM "sensor_test" 
      WHERE time >= now() - ${time}
      GROUP BY time(${step}) FILL(none)
    `

  return request({
    baseURL: '/api',
    url: `/query?org=my-org&db=${bucketName}&q=${query}`, // 如果是 InfluxDB v2.x, 这应该是 '/api/v2/query'
    headers,
    method: 'post' // 使用 POST 方法
  })
}

export function getChartsData2() {
  const query = ` 
        SELECT MEAN(*) 
        FROM "sensor_test" 
        WHERE time >= now() - 5m
        GROUP BY time(1s) FILL(none)
    `
  return request({
    baseURL: '/api',
    url: '/query?org=myorg&db=mybucket&q=' + query,
    headers,
    method: 'post'
  })
}

//根据设备阀门和时间区间获取数据
export function getChartsDataByTime(params, bucketName, timeArr, time) {
  // SELECT MEAN("temperature_1")
  // AND "_field" IN ("temperature_1")
  const query = `SELECT ${params} FROM "sensor_test" WHERE time >= '${timeArr[0]}' AND time <= '${timeArr[1]}' GROUP BY time(${time}) FILL(none)`
  return request({
    baseURL: '/api',
    url: '/query?org=my-org&db=' + bucketName + '&q=' + query, // 如果是 InfluxDB v2.x, 这应该是 '/api/v2/query'
    headers,
    method: 'post' // 使用 POST 方法
  })
}
//获取设备信息温度数据
export function getEqTempData() {
  // const query = "union(tables: [from(bucket: \"mybucket\") |> range(start: -2s) |> filter(fn: (r) => r[\"_measurement\"] == \"sensor_test\" and r[\"_field\"] =~ /temperature/) |> set(key: \"_bucket\", value: \"mybucket\") |> max()  |> group(columns: [\"_bucket\"]), from(bucket: \"mybucket02\") |> range(start: -2s) |> filter(fn: (r) => r[\"_measurement\"] == \"sensor_test\" and r[\"_field\"] =~ /temperature/) |> set(key: \"_bucket\", value: \"mybucket02\") |> max()  |> group(columns: [\"_bucket\"]), from(bucket: \"mybucket03\") |> range(start: -2s) |> filter(fn: (r) => r[\"_measurement\"] == \"sensor_test\" and r[\"_field\"] =~ /temperature/) |> set(key: \"_bucket\", value: \"mybucket03\") |> max()  |> group(columns: [\"_bucket\"]), from(bucket: \"mybucket04\") |> range(start: -2s) |> filter(fn: (r) => r[\"_measurement\"] == \"sensor_test\" and r[\"_field\"] =~ /temperature/) |> set(key: \"_bucket\", value: \"mybucket04\") |> max()  |> group(columns: [\"_bucket\"]), from(bucket: \"mybucket05\") |> range(start: -2s) |> filter(fn: (r) => r[\"_measurement\"] == \"sensor_test\" and r[\"_field\"] =~ /temperature/) |> set(key: \"_bucket\", value: \"mybucket05\") |> max()  |> group(columns: [\"_bucket\"]), from(bucket: \"mybucket06\") |> range(start: -2s) |> filter(fn: (r) => r[\"_measurement\"] == \"sensor_test\" and r[\"_field\"] =~ /temperature/) |> set(key: \"_bucket\", value: \"mybucket06\") |> max()  |> group(columns: [\"_bucket\"]), from(bucket: \"mybucket07\") |> range(start: -2s) |> filter(fn: (r) => r[\"_measurement\"] == \"sensor_test\" and r[\"_field\"] =~ /temperature/) |> set(key: \"_bucket\", value: \"mybucket07\") |> max()  |> group(columns: [\"_bucket\"]), from(bucket: \"mybucket08\") |> range(start: -2s) |> filter(fn: (r) => r[\"_measurement\"] == \"sensor_test\" and r[\"_field\"] =~ /temperature/) |> set(key: \"_bucket\", value: \"mybucket08\") |> max()  |> group(columns: [\"_bucket\"])])"
  const query ="union(tables: [from(bucket: \"mybucket\") |> range(start: -10s) |> filter(fn: (r) => r[\"_measurement\"] == \"sensor_test\" and r[\"_field\"] =~ /temperature/) |> last() |> set(key: \"_bucket\", value: \"mybucket\"), from(bucket: \"mybucket02\") |> range(start: -24h) |> filter(fn: (r) => r[\"_measurement\"] == \"sensor_test\" and r[\"_field\"] =~ /temperature/) |> last() |> set(key: \"_bucket\", value: \"mybucket02\"), from(bucket: \"mybucket03\") |> range(start: -24h) |> filter(fn: (r) => r[\"_measurement\"] == \"sensor_test\" and r[\"_field\"] =~ /temperature/) |> last() |> set(key: \"_bucket\", value: \"mybucket03\"), from(bucket: \"mybucket04\") |> range(start: -24h) |> filter(fn: (r) => r[\"_measurement\"] == \"sensor_test\" and r[\"_field\"] =~ /temperature/) |> last() |> set(key: \"_bucket\", value: \"mybucket04\"), from(bucket: \"mybucket05\") |> range(start: -24h) |> filter(fn: (r) => r[\"_measurement\"] == \"sensor_test\" and r[\"_field\"] =~ /temperature/) |> last() |> set(key: \"_bucket\", value: \"mybucket05\"), from(bucket: \"mybucket06\") |> range(start: -24h) |> filter(fn: (r) => r[\"_measurement\"] == \"sensor_test\" and r[\"_field\"] =~ /temperature/) |> last() |> set(key: \"_bucket\", value: \"mybucket06\"), from(bucket: \"mybucket07\") |> range(start: -24h) |> filter(fn: (r) => r[\"_measurement\"] == \"sensor_test\" and r[\"_field\"] =~ /temperature/) |> last() |> set(key: \"_bucket\", value: \"mybucket07\"), from(bucket: \"mybucket08\") |> range(start: -24h) |> filter(fn: (r) => r[\"_measurement\"] == \"sensor_test\" and r[\"_field\"] =~ /temperature/) |> last() |> set(key: \"_bucket\", value: \"mybucket08\")]) |> filter(fn: (r) => r[\"_value\"] >= 0 and r[\"_value\"] < 100) |> map(fn: (r) => ({r with temp_range: if r[\"_value\"] < 45 then \"1\" else if r[\"_value\"] < 60 then \"2\" else \"3\"})) |> group(columns: [\"_bucket\", \"temp_range\"]) |> count()"

  return request({
    baseURL: '/api',
    url: '/api/v2/query?org=myorg',
    headers,
    data: {
      "query": query
    },
    method: 'post' // 使用 POST 方法
  })
}

export function getHourFlowData() {
  // 破解 query语句
  let data = `union(tables: [`;
  for (let index = 1; index <= 8; index++) {
    let i = index.toString().padStart(2, '0');
    if (index == 1) {
      i = ''
    }
    data += `from(bucket: "mybucket${i}") 
    |> range(start: -1h) 
    |> filter(fn: (r) => r["_measurement"] == "sensor_test") 
    |> filter(fn: (r) => r["_field"] == "flow") 
    |> aggregateWindow(every: 1m, fn: mean, createEmpty: false)
    |> map(fn: (r) => ({ bucket: "mybucket${i}", time: r._time, flow: r._value })),`
  }
  data += `])`
  return request({
    baseURL: '/api',
    url: '/api/v2/query?org=myorg',
    headers,
    data: {
      "query": data
    },
    method: 'post' // 使用 POST 方法
  })
}

//获取预警数据
export function getAlarmData() {
  const data = "union(tables: [from(bucket: \"mybucket\") |> range(start: -2s) |> filter(fn: (r) => r[\"_measurement\"] == \"sensor_test\" and r[\"_field\"] =~ /temperature/) |> set(key: \"_bucket\", value: \"mybucket\") |> max()  |> filter(fn: (r) => r[\"_value\"] > 60)    |> group(columns: [\"_bucket\"]), from(bucket: \"mybucket02\") |> range(start: -2s) |> filter(fn: (r) => r[\"_measurement\"] == \"sensor_test\" and r[\"_field\"] =~ /temperature/) |> set(key: \"_bucket\", value: \"mybucket02\") |> max()  |> filter(fn: (r) => r[\"_value\"] > 60)    |> group(columns: [\"_bucket\"]), from(bucket: \"mybucket03\") |> range(start: -2s) |> filter(fn: (r) => r[\"_measurement\"] == \"sensor_test\" and r[\"_field\"] =~ /temperature/) |> set(key: \"_bucket\", value: \"mybucket03\") |> max()  |> filter(fn: (r) => r[\"_value\"] > 60)    |> group(columns: [\"_bucket\"]), from(bucket: \"mybucket04\") |> range(start: -2s) |> filter(fn: (r) => r[\"_measurement\"] == \"sensor_test\" and r[\"_field\"] =~ /temperature/) |> set(key: \"_bucket\", value: \"mybucket04\") |> max()  |> filter(fn: (r) => r[\"_value\"] > 60)    |> group(columns: [\"_bucket\"]), from(bucket: \"mybucket05\") |> range(start: -2s) |> filter(fn: (r) => r[\"_measurement\"] == \"sensor_test\" and r[\"_field\"] =~ /temperature/) |> set(key: \"_bucket\", value: \"mybucket05\") |> max()  |> filter(fn: (r) => r[\"_value\"] > 60)    |> group(columns: [\"_bucket\"]), from(bucket: \"mybucket06\") |> range(start: -2s) |> filter(fn: (r) => r[\"_measurement\"] == \"sensor_test\" and r[\"_field\"] =~ /temperature/) |> set(key: \"_bucket\", value: \"mybucket06\") |> max()  |> filter(fn: (r) => r[\"_value\"] > 60)    |> group(columns: [\"_bucket\"]), from(bucket: \"mybucket07\") |> range(start: -2s) |> filter(fn: (r) => r[\"_measurement\"] == \"sensor_test\" and r[\"_field\"] =~ /temperature/) |> set(key: \"_bucket\", value: \"mybucket07\") |> max()  |> filter(fn: (r) => r[\"_value\"] > 60)    |> group(columns: [\"_bucket\"]), from(bucket: \"mybucket08\") |> range(start: -2s) |> filter(fn: (r) => r[\"_measurement\"] == \"sensor_test\" and r[\"_field\"] =~ /temperature/) |> set(key: \"_bucket\", value: \"mybucket08\") |> max()  |> filter(fn: (r) => r[\"_value\"] > 60)    |> group(columns: [\"_bucket\"])])";
  return request({
    baseURL: '/api',
    url: '/api/v2/query?org=myorg',
    headers,
    data: {
      "query": data
    },
    method: 'post' // 使用 POST 方法
  })
}

//获取流量数据
export function getWeekFlowData() {
  const data = `
import "date"
// 定义计算每日流量总和的函数
getDailyFlowSum = (bucketName) => {
  data = from(bucket: bucketName)
    |> range(start: -7d)  
    |> filter(fn: (r) => r["_measurement"] == "sensor_test")
    |> filter(fn: (r) => r["_field"] == "flow")
    |> aggregateWindow(every: 1d, fn: sum, createEmpty: false)
    |> map(fn: (r) => ({
        r with 
        _time: date.truncate(t: r._time, unit: 1d)  // 保证每天只有一组数据
    }))
    |> unique(column: "_time")  // 确保每天只有一条数据
  return data
}

// 计算前四个桶的每日总和，命名为 group1
group1 = union(
  tables: [
    getDailyFlowSum(bucketName: "mybucket"),
    getDailyFlowSum(bucketName: "mybucket02"),
    getDailyFlowSum(bucketName: "mybucket03"),
    getDailyFlowSum(bucketName: "mybucket04")
  ]
)
  |> map(fn: (r) => ({ r with group: "K" }))  // 给 group1 添加分组标识
  |> group(columns: ["_time", "group"])  // 按天分组，并包含 group 字段
  |> sum()  // 每组数据求和

// 计算后四个桶的每日总和，命名为 group2
group2 = union(
  tables: [
    getDailyFlowSum(bucketName: "mybucket05"),
    getDailyFlowSum(bucketName: "mybucket06"),
    getDailyFlowSum(bucketName: "mybucket07"),
    getDailyFlowSum(bucketName: "mybucket08")
  ]
)
  |> map(fn: (r) => ({ r with group: "L" }))  // 给 group2 添加分组标识
  |> group(columns: ["_time", "group"])  // 按天分组，并包含 group 字段
  |> sum()  // 每组数据求和

// 合并两组结果，确保每条记录带有 group 标识
union(
  tables: [group1, group2]
)
`
  return request({
    baseURL: '/api',
    url: '/api/v2/query?org=myorg',
    headers,
    data: {
      "query": data
    },
    method: 'post' // 使用 POST 方法
  })
}


//获取能耗数据
export function getEnergyData() {
  return request({
    // baseURL: '/api',
    url: 'http://192.168.110.221:8083/api/energy/getEnergyWeekData',
    method: 'get' 
  })
}
