<template>
  <div class="app-container">
    <div class="Pd20">
      <el-form :model="form" :inline="true" size="mini">
        <el-form-item>
          <el-select v-model="form.cameraName" placeholder="监控点位" clearable>
            <el-option
              v-for="(item, index) in cameraAdderss"
              :key="index"
              :value="item.positionId"
              :label="item.positionName"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="form.algorithmLevel"
            placeholder="算法报警等级"
            clearable
          >
            <el-option
              v-for="(item, index) in dict.type.algorithm_level"
              :key="index"
              :value="item.value"
              :label="item.label"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="form.alarmStatus"
            placeholder="报警处理状态"
            clearable
          >
            <el-option :value="2" label="待处理"></el-option>
            <el-option :value="1" label="正确报警"></el-option>
            <el-option :value="0" label="错误报警"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-input
            v-model="form.algorithmName"
            placeholder="算法名称"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="mini" @click="search">
            <i class="el-icon-search el-icon--left"></i>
            搜索
          </el-button>
        </el-form-item>
      </el-form>
      <el-table :data="tableList">
        <el-table-column
          label="摄像头ID"
          prop="cameraId"
          align="center"
        ></el-table-column>
        <el-table-column
          label="视频分析任务名称"
          prop="taskName"
          align="center"
        ></el-table-column>
        <el-table-column
          label="摄像头名称"
          prop="cameraName"
          align="center"
        ></el-table-column>
        <el-table-column label="报警图片" prop="alarmImageUrl" align="center">
          <template slot-scope="scope">
            <image-preview
              :src="scope.row.alarmImageUrl"
              :width="60"
              :height="40"
            />
          </template>
        </el-table-column>
        <el-table-column
          label="报警时间"
          prop="alarmTime"
          align="center"
        ></el-table-column>
        <el-table-column
          label="算法名称"
          prop="algorithmName"
          align="center"
        ></el-table-column>
        <el-table-column label="算法报警等级" prop="alarmLevel" align="center">
          <template slot-scope="scope">
            <dict-tag
              :options="dict.type.algorithm_level"
              :value="scope.row.alarmLevel"
            />
          </template>
        </el-table-column>
        <el-table-column label="推送负责人" prop="pushBy" align="center">
        </el-table-column>
        <el-table-column label="报警处理状态" align="center">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.alarmStatus === 2" type="warning"
              >待处理</el-tag
            >
            <el-tag v-if="scope.row.alarmStatus === 1" type="success"
              >正确报警</el-tag
            >
            <el-tag v-if="scope.row.alarmStatus === 0" type="danger"
              >错误报警</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200px">
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="pushBut(scope.row)">
              报警推送
            </el-button>

            <el-button
              type="text"
              size="mini"
              @click="deleteBut(scope.row.logId)"
            >
              <i class="el-icon-delete el-icon--left"></i>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
      <!-- 新增弹窗组件 -->
      <el-dialog
        title="推送用户选择"
        :visible.sync="pushDialogVisible"
        width="30%"
        center
      >
        <el-select
          v-model="selectedUsers"
          filterable
          placeholder="请选择要推送的用户"
          style="width: 100%"
        >
          <el-option
            v-for="user in userList"
            :key="user.userId"
            :label="user.userName"
            :value="user.userId"
          />
        </el-select>
        <span slot="footer" class="dialog-footer">
          <el-button @click="pushDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="confirmPush">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  getAlarmLogList,
  delAlarmLog,
  updateAlarmLog,
} from "@/api/business/alarmlog.js";
import { getCameraPositionList } from "@/api/business/cameraconfig.js";
import { listUser } from "@/api/system/user.js";
export default {
  dicts: ["algorithm_level"],
  name: "Alarmlog",
  props: {},
  components: {},
  data() {
    return {
      form: {
        id: 1, // 摄像头ID
        videoAnlysisTasksName: "", // 视频分析任务名称
        cameraName: "", // 摄像头名称
        alarmImg: "", // 报警图片
        alarmTime: "", // 报警时间
        algorithmName: "", // 算法名称
        algorithmLevel: null, // 算法报警等级
        alarmStatus: null, // 报警处理状态
        // 新增弹窗相关数据
        pushDialogVisible: false,
        selectedUsers: [],
        userList: [], // 用户列表
        currentLogId: null, // 当前操作的报警日志ID
      },
      tableList: [],
      cameraAdderss: [
        {
          name: "摄像头1", // 摄像头名称

          address: "地址一", // 摄像头地址
        },
      ], // 摄像头地址
      total: 0, // 总数量
      queryParams: {
        pageNum: 1, // 当前页码
        pageSize: 10, // 每页显示的数量
      },
      // 新增弹窗相关数据
      pushDialogVisible: false,
      selectedUsers: [],
      userList: [], // 用户列表
      currentLogId: null, // 当前操作的报警日志ID
    };
  },
  computed: {},
  watch: {},
  created() {
    this.getList();
    getCameraPositionList().then((res) => {
      if (res.code == 200) {
        // 处理空数组情况
        const rawData = Array.isArray(res.data) ? res.data : [];
        this.cameraAdderss = this.flattenJson(rawData).map((item) => ({
          positionName: item.positionName,
          positionId: item.positionId,
        }));
      } else {
        this.cameraAdderss = []; // 接口异常时设为空数组
      }
    });
  },
  mounted() {},
  methods: {
    // 新增扁平化方法
    flattenJson(arr) {
      return arr.reduce((acc, item) => {
        acc.push(item);
        if (item.children && item.children.length) {
          acc.push(...this.flattenJson(item.children));
        }
        return acc;
      }, []);
    },
    // 搜索
    search() {
      let params = { ...this.queryParams, ...this.form };
      getAlarmLogList(params).then((res) => {
        if (res.code == 200) {
          this.tableList = res.rows;
          this.total = res.total;
        }
      });
    },
    // 删除
    deleteBut(id) {
      delAlarmLog(id).then((res) => {
        if (res.code == 200) {
          this.$message({
            message: "删除成功",
            type: "success",
          });
          this.getList();
        } else {
          this.$message({
            message: res.msg,
            type: "error",
          });
        }
      });
    },
    // 编辑
    pushBut(row, alarmStatus) {
      this.currentLogId = row.logId;
      this.pushDialogVisible = true;
      this.loadUserList();
    },
    // 加载用户列表（需要对接后端API）
    async loadUserList() {
      try {
        const response = await listUser();
        if (response.code === 200) {
          this.userList = response.rows;
        }
      } catch (error) {
        console.error("获取用户列表失败:", error);
      }
    },

    // 确认推送
    async confirmPush() {
      try {
        const params = {
          logId: this.currentLogId,
          pushBy: this.selectedUsers,
        };

        const res = await updateAlarmLog(params);
        if (res.code === 200) {
          this.$message.success("推送成功");
          this.pushDialogVisible = false;
          this.selectedUsers = [];
          this.getList(); // 刷新表格数据
        }
      } catch (error) {
        this.$message.error("推送失败");
        console.error("推送异常:", error);
      }
    },
    // 获取数据列表
    getList() {
      getAlarmLogList({ ...this.queryParams, ...this.form }).then((res) => {
        if (res.code == 200) {
          this.tableList = res.rows;
          this.total = res.total;
        }
      });
    },
  },
};
</script>

<style scoped lang="scss"></style>
