<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="user" />
            </div>
            <div class="stat-text" style="font-size: 16px; color: #000">
              报警统计
            </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;
              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: #ff0000"
            >
              3次
            </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"
            >
              3次
            </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"
            >
              3次
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <label>SOS报警变化趋势图</label>
      <el-form-item label="" style="margin-top: -5px; margin-left: 20px">
        <el-date-picker
          v-model="queryParams.dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>

      <el-form-item style="margin-top: -5px; margin-left: 20px">
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" 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 { listInfo } from "@/api/jinrun/renyuan";
import { getDict } from "@/api/jinrun/common";
import * as echarts from "echarts"; // 导入ECharts

export default {
  name: "Info",
  data() {
    return {
      // 人员类型下拉列表数据
      personTypeOptions: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 人员信息表格数据
      infoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        dateRange: null,
        realName: null,
        pageNum: 1,
        pageSize: 10,
      },
      // 表单参数
      form: {
        personType: "",
      },
    };
  },
  created() {
    this.getList();
  },
  mounted() {
    this.initChart();
  },
  methods: {
    /** 初始化图表 */
    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("-").slice(1).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() {
      if (this.chartInstance) {
        // 模拟数据（实际项目中应根据后端返回数据处理）
        const dateRange = this.queryParams.dateRange;
        let dates = [];
        let values = [];

        if (dateRange && dateRange.length === 2) {
          // 有日期范围时生成模拟数据
          const start = new Date(dateRange[0]);
          const end = new Date(dateRange[1]);
          const days = Math.ceil((end - start) / (1000 * 60 * 60 * 24));

          for (let i = 0; i <= days; i++) {
            const currentDate = new Date(start);
            currentDate.setDate(start.getDate() + i);
            const dateStr =
              currentDate.getFullYear() +
              "-" +
              (currentDate.getMonth() + 1).toString().padStart(2, "0") +
              "-" +
              currentDate.getDate().toString().padStart(2, "0");
            dates.push(dateStr);
            // 生成随机数据，范围在1-10之间
            values.push(Math.floor(Math.random() * 10) + 1);
          }
        } else {
          // 默认显示最近7天的数据
          for (let i = 6; i >= 0; i--) {
            const currentDate = new Date();
            currentDate.setDate(currentDate.getDate() - i);
            const dateStr =
              currentDate.getFullYear() +
              "-" +
              (currentDate.getMonth() + 1).toString().padStart(2, "0") +
              "-" +
              currentDate.getDate().toString().padStart(2, "0");
            dates.push(dateStr);
            // 生成随机数据，范围在1-10之间
            values.push(Math.floor(Math.random() * 10) + 1);
          }
        }

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

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

    /** 查询人员信息列表 */
    getList() {
      this.loading = true;
      listInfo(this.queryParams).then((response) => {
        this.infoList = response.records;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
      // 搜索时更新图表数据（添加这行）
      this.updateChart();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.personId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
  },
  /** 组件销毁时清理 */
  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>