<template>
  <div class="app-container">
    <!-- 统计模块 -->
    <div
      class="statistics-module"
      style="
        background-color: #f9fafd;
        padding: 20px;
        border-radius: 8px;
        margin-bottom: 20px;
        width: 600px;
      "
    >
      <el-row :gutter="20">
        <!-- 第一部分：人员统计 -->
        <el-col :span="6">
          <div
            class="stat-item"
            style="
              display: flex;
              flex-direction: column;
              align-items: center;
              justify-content: center;
              padding: 10px;
            "
          >
            <div
              class="stat-icon"
              style="font-size: 30px; color: #409eff; margin-bottom: 10px"
            >
              <svg-icon icon-class="build" />
            </div>
            <div class="stat-text" style="font-size: 16px; color: #000">
              报警统计
            </div>
          </div>
        </el-col>
        <!-- 第二部分：今日员工人数 -->
        <el-col :span="6">
          <div
            class="stat-item"
            style="
              display: flex;
              flex-direction: column;
              align-items: center;
              justify-content: center;
              padding: 10px;
              border-left: 1px solid #ebeef5;
              border-right: 1px solid #ebeef5;
            "
          >
            <div
              class="stat-label"
              style="font-size: 14px; color: #000; margin-bottom: 12px"
            >
              今日SOS报警数
            </div>
            <div
              class="stat-value"
              style="font-size: 18px; font-weight: 400; color: #2196f3"
            >
              {{ sumObj.today_count }}次
            </div>
          </div>
        </el-col>
        <!-- 第三部分：今日访客人数 -->
        <el-col :span="6">
          <div
            class="stat-item"
            style="
              display: flex;
              flex-direction: column;
              align-items: center;
              justify-content: center;
              padding: 10px;
            "
          >
            <div
              class="stat-label"
              style="font-size: 14px; color: #000; margin-bottom: 12px"
            >
              当月SOS报警数
            </div>
            <div
              class="stat-value"
              style="font-size: 18px; font-weight: 400; color: #2196f3"
            >
              {{ sumObj.month_count }}次
            </div>
          </div>
        </el-col>
        <!-- 今年SOS报警数 -->
        <el-col :span="6">
          <div
            class="stat-item"
            style="
              display: flex;
              flex-direction: column;
              align-items: center;
              justify-content: center;
              padding: 10px;
            "
          >
            <div
              class="stat-label"
              style="font-size: 14px; color: #000; margin-bottom: 12px"
            >
              今年SOS报警数
            </div>
            <div
              class="stat-value"
              style="font-size: 18px; font-weight: 400; color: #ff0000"
            >
              {{ sumObj.year_count }}次
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
      :rules="dateRangeRules"
    >
      <label>SOS报警变化趋势图</label>
      <el-form-item
        label=""
        style="margin-top: -5px; margin-left: 20px"
        prop="dateRange"
      >
        <el-date-picker
          v-model="queryParams.dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @change="handleDateChange"
        ></el-date-picker>
      </el-form-item>

      <el-form-item style="margin-top: -5px; margin-left: 20px">
        <el-button
          type="primary"
          icon="el-icon-search1"
          size="mini"
          @click="handleQuery"
          >查询</el-button
        >
        <el-button icon="el-icon-refresh1" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    <!-- 趋势图 -->
    <div
      class="qushitu"
      style="width: 100%; height: 400px; margin-bottom: 20px"
    ></div>
  </div>
</template>

<script>
import {
  getYearMonthDayAlarmCount,
  getAlarmCountTrend,
} from "@/api/jinrun/baojingtongji";
import * as echarts from "echarts"; // 导入ECharts

export default {
  name: "Info",
  data() {
    // 日期范围校验规则
    const validateDateRange = (rule, value, callback) => {
      if (!value || value.length !== 2) {
        callback();
        return;
      }

      const startDate = new Date(value[0]);
      const endDate = new Date(value[1]);
      const daysDiff = (endDate - startDate) / (1000 * 60 * 60 * 24) + 1; // 包含起止日

      if (daysDiff > 31) {
        callback(new Error("日期范围不能超过一个月"));
      } else {
        callback();
      }
    };

    return {
      sumObj: {},
      // 人员类型下拉列表数据
      personTypeOptions: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 人员信息表格数据
      infoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        dateRange: [],
        pageNum: 1,
        pageSize: 10,
      },
      // 日期范围校验规则
      dateRangeRules: {
        dateRange: [
          {
            validator: validateDateRange,
            trigger: "change",
          },
        ],
      },
      // 表单参数
      form: {
        personType: "",
      },
    };
  },
  created() {
    this.getList();
  },
  mounted() {
    this.initChart();
    this.getYearMonthDayAlarmCount();
    this.getAlarmCountTrend();
  },
  methods: {
    // 日期变化处理
    handleDateChange(value) {
      if (value && value.length === 2) {
        this.$refs.queryForm.validateField("dateRange");
      }
    },

    getAlarmCountTrend() {
      // 处理日期范围参数
      this.queryParams.startDate = this.queryParams.dateRange[0] || "";
      this.queryParams.endDate = this.queryParams.dateRange[1] || "";
      getAlarmCountTrend(this.queryParams).then((response) => {
        // this.sumObj = response.data;
        console.log(response, " 人员数量趋势图数据");
        this.updateChart(response.data.xData, response.data.yData);
      });
    },
    getYearMonthDayAlarmCount() {
      getYearMonthDayAlarmCount().then((response) => {
        this.sumObj = response.data;
        console.log(response, " 报警数");
      });
    },

    /** 初始化图表 */

    initChart() {
      // 获取DOM元素并初始化图表
      const chartDom = document.querySelector(".qushitu");
      if (chartDom) {
        this.chartInstance = echarts.init(chartDom);

        // 设置初始配置
        const option = {
          title: {
            // text: "人员数量趋势图",
            left: "center",
          },
          tooltip: {
            trigger: "axis",
            formatter: function (params) {
              return (
                params[0].name + "<br/>" + "报警数量: " + params[0].value + "次"
              );
            },
          },
          grid: {
            left: "3%",
            right: "4%",
            bottom: "3%",
            containLabel: true,
          },
          xAxis: {
            type: "category",
            boundaryGap: false,
            data: [], // 将由updateChart方法填充
            axisLabel: {
              // 修改formatter配置，正确显示年月日
              formatter: function (value) {
                // value是完整的日期字符串，如"2023-10-25"
                return value.split("-").join("-"); // 显示月-日，如"10-25"
                // 如果需要显示完整年月日，可以使用：return value;
              },
              rotate: 45, // 添加旋转以避免日期重叠
              interval: 0, // 显示所有标签
            },
          },
          yAxis: {
            type: "value",
            // name: "人员数量",
            splitLine: {
              show: true, // 显示每个刻度对应的横线
              lineStyle: {
                type: "solid",
                color: "#f0f0f0",
              },
            },
            minInterval: 1, // y轴最小间隔为1，避免显示小数
            axisLabel: {
              formatter: "{value}",
            },
          },
          series: [
            {
              name: "报警次数",
              type: "line",
              smooth: false,
              symbol: "circle", // 数据点样式
              symbolSize: 8, // 数据点大小
              lineStyle: {
                width: 3, // 线宽
                color: "#1890ff", // 蓝色线条
              },
              itemStyle: {
                color: "#1890ff", // 数据点颜色
              },
              areaStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  {
                    offset: 0,
                    color: "rgba(24, 144, 255, 0.3)",
                  },
                  {
                    offset: 1,
                    color: "rgba(24, 144, 255, 0.05)",
                  },
                ]),
              },
              data: [], // 将由updateChart方法填充
            },
          ],
        };

        this.chartInstance.setOption(option);

        // 初始化后立即调用updateChart加载测试数据（添加这行）
        this.updateChart();

        // 监听窗口大小变化，自适应图表大小
        window.addEventListener("resize", this.handleResize);
      }
    },

    /** 更新图表数据 */
    updateChart(dates, values) {
      if (this.chartInstance) {
        // 更新图表数据
        this.chartInstance.setOption({
          xAxis: {
            data: dates,
          },
          series: [
            {
              data: values,
            },
          ],
        });
      }
    },

    /** 处理窗口大小变化 */
    handleResize() {
      if (this.chartInstance) {
        this.chartInstance.resize();
      }
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    /** 搜索按钮操作 */
    handleQuery() {
      if (this.queryParams.dateRange.length > 0) {
        const startDate = new Date(this.queryParams.dateRange[0]);
        const endDate = new Date(this.queryParams.dateRange[1]);
        const daysDiff = (endDate - startDate) / (1000 * 60 * 60 * 24) + 1; // 包含起止日

        if (daysDiff > 31) {
          this.$message.warning("日期范围不能超过一个月");
          return;
        }
      }

      this.getAlarmCountTrend();
    },
    /** 重置按钮操作 */
    resetQuery() {
      // this.resetForm("queryForm");
      this.queryParams.dateRange = [];
      this.queryParams.startDate = "";
      this.queryParams.endDate = "";
      this.handleQuery();
    },
  },
  /** 组件销毁时清理 */
  beforeDestroy() {
    if (this.chartInstance) {
      this.chartInstance.dispose();
    }
    window.removeEventListener("resize", this.handleResize);
  },
};
</script>

<style scoped lang="scss">
.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 50px;
  height: 50px;
  background-color: #f5f7fa;
  color: #909399;
  font-size: 20px;
}
</style>