<template>
  <div style="height: calc(100vh - 110px)">
    <a-layout :theme="'light'" style="height: calc(100vh - 110px)">
      <a-layout-sider :theme="'light'" :width="300" style="padding: 20px">
        <div style="text-align: center; font-size: 16px">选择站点</div>
        <a-divider />
        <a-tree
          v-model="checkedKeys"
          checkable
          :selected-keys="selectedKeys"
          :auto-expand-parent="autoExpandParent"
          :tree-data="treeData"
          @check="onSelect"
          showLine
        >
          <a-icon slot="switcherIcon" type="down" />
        </a-tree>
      </a-layout-sider>
      <a-layout style="padding: 20px">
        <a-layout-header style="background: #fff; padding: 15px 0 5px 15px">
          <a-radio-group
            default-value="1-hours"
            button-style="solid"
            style="display: block; line-height: 32px"
            @change="handleTimeRadioClick"
          >
            <a-radio-button
              v-for="item in timeRadios"
              :key="item.value"
              :value="item.value"
            >
              {{ item.name }}
            </a-radio-button>
          </a-radio-group>
          <a-radio-group
            default-value="chart"
            button-style="solid"
            @change="handleRadioClick"
          >
            <a-radio-button
              v-for="item in radios"
              :key="item.value"
              :value="item.value"
            >
              {{ item.name }}
            </a-radio-button>
          </a-radio-group>
          <span style="margin-left: 30px"
            ><a-button @click="getData"> 刷新数据</span
          >
        </a-layout-header>
        <a-layout-content style="padding: 20px 0 20px 0">
          <a-spin :spinning="loading">
            <a-table
              v-if="currentType === 'table'"
              :columns="columns"
              :data-source="waterData"
              bordered
              :pagination="pagination"
              size="middle"
              @change="handleTableChange"
            >
              <span slot="device" slot-scope="record">
                {{ deviceNames[record.device_id] }}
              </span>
            </a-table>
            <div v-if="currentType === 'chart'">
              <a-row v-for="chart in chartSettings" :key="chart.series" style="margin-bottom:30px;">
                <base-index-chart
                  :height="'300px'"
                  :width="'100%'"
                  :rawData="waterData"
                  :setting="chart"
                />
              </a-row>
            </div>
            <!--  -->
          </a-spin>
        </a-layout-content>
      </a-layout>
    </a-layout>
  </div>
</template>

<script>
// import SZJCChart from "./SZJCChart";
import { getData, URL_MAP } from "@/utils/http";
import Moment from "@/components/utils/moment.zh_cn";
import { generateWaterData, processWater } from "@/utils/water";
import BaseIndexChart from "../charts/BaseIndexChart.vue";
export default {
  components: {
    BaseIndexChart
  },
  data() {
    return {
      checkedKeys: [],
      expandedKeys: [],
      autoExpandParent: true,
      selectedKeys: [],
      treeData: [],
      waterData: [],
      pagination: {
        total: 0,
        pageSize: 10,
        current: 0,
      },
      loading: false,
      update: false,
      startTime: Moment().subtract(1, "hours"),
      endTime: Moment(),
      deviceNames: {},
      timeRadios: [
        {
          value: "5-minutes",
          name: "最近5分钟",
        },
        {
          value: "15-minutes",
          name: "最近15分钟",
        },
        {
          value: "30-minutes",
          name: "最近30分钟",
        },
        {
          value: "1-hours",
          name: "最近1小时",
        },
        {
          value: "3-hours",
          name: "最近3小时",
        },
        {
          value: "6-hours",
          name: "最近6小时",
        },
        {
          value: "1-days",
          name: "最近24小时",
        },
      ],
      radios: [
        {
          value: "table",
          name: "表格",
        },
        {
          value: "chart",
          name: "图形",
        },
      ],
      currentType: "chart",
      chartSettings: [],
    };
  },
  computed: {
    sensorList() {
      return this.$store.getters.sensorList;
    },
    deviceList() {
      return this.$store.getters.deviceList;
    },
    ruleList() {
      return this.$store.getters.ruleList;
    },
  },
  methods: {
    async initSeting() {
      // console.log(this.ruleList)
      const columns = [
        {
          title: "站点名",
          key: "device_name",
          scopedSlots: { customRender: "device" },
        },
        {
          title: "时间",
          dataIndex: "time_str",
        },
      ];
      const ruleSlot = {};
      this.ruleList.forEach((rule) => {
        ruleSlot[rule.sensor.param_key] = {
          mmax: rule.allow_max,
          mmin: rule.allow_min,
        };
      });
      const chartSettings = [];
      this.sensorList.forEach((sensor) => {
        columns.push({
          title: sensor.param_name,
          children: [
            {
              title: sensor.uint || "-",
              dataIndex: sensor.param_key,
              customCell: (record, index) => {
                if (
                  record[sensor.param_key] &&
                  record[sensor.param_key] >= ruleSlot[sensor.param_key].mmin &&
                  record[sensor.param_key] <= ruleSlot[sensor.param_key].mmax
                )
                  return {};
                else {
                  return {
                    style: { color: "#ff0000" },
                  };
                }
              },
              // scopedSlots: { customRender: sensor.param_key },
            },
          ],
        });
        chartSettings.push({
          title: sensor.param_name,
          xAxis: "time",
          series: sensor.param_key,
          seriesName: sensor.param_name,
          seriesType: "line",
          // yRange: [
          //   ruleSlot[sensor.param_key].mmin,
          //   ruleSlot[sensor.param_key].mmax,
          // ],
        });
      });
      this.chartSettings = chartSettings;
      // this.ruleSlot = ruleSlot;
      this.columns = columns;

      const deviceTree = [];
      const deviceName = {};
      this.checkedKeys = [];
      this.deviceList.forEach((device) => {
        deviceTree.push({
          title: device.device_name,
          key: device._id,
        });
        deviceName[device.device_id] = device.device_name;
        this.checkedKeys.push(device._id);
      });
      this.deviceNames = deviceName;
      this.treeData = [
        {
          title: "设备",
          key: "all",
          children: deviceTree,
        },
      ];
    },

    async getData() {
      this.loading = true;
      try {
        let count = 10

        if (this.currentType === "chart") {
          count = 300;
        }
        // let data = await getData(URL_MAP.WATER_LIST, params);
        let data = generateWaterData(this.sensorList.map((s) => s.param_key), count)
        this.waterData = data
        this.pagination.total = 300;
      } catch (e) {
        console.log(e);
        this.waterData = [];
      } finally {
        this.loading = false;
      }
    },
    handleTableChange(page, filters, sorter) {
      const pager = { ...this.pagination };
      pager.current = page.current;
      this.pagination = pager;
      this.getData();
    },
    dateRangeChange(dates, dateStrings) {
      this.datetimeRange = dates;
      console.log(this.datetimeRange);
      this.getData();
    },
    handleRadioClick(v) {
      this.currentType = v.target.value;
    },
    handleTimeRadioClick(v) {
      let now = Moment();
      let pre = Moment();
      let d = v.target.value.split("-");
      pre = pre.subtract(parseInt(d[0]), d[1]);
      this.startTime = pre;
      this.endTime = now;
      this.getData();
    },
    onSelect(keys) {
      // console.log(keys)
      this.selectedKeys = keys.filter((v) => v !== "all");
      // console.log(this.selectedKeys)
    },
  },

  async mounted() {
    await this.initSeting();
    this.getData();
  },
};
</script>

<style>
.el-header,
.el-footer {
  background-color: #b3c0d1;
  color: #333;
  text-align: center;
  line-height: 60px;
}
.error-data {
  color: rgb(255, 11, 2);
}
</style>