<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="农机编号" prop="machineCode">
        <el-input v-model="queryParams.machineCode" placeholder="请输入农机编号关键词" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="农机名称" prop="machineName">
        <el-input v-model="queryParams.machineName" placeholder="请输入农机名称关键词" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item label="告警等级" prop="alarmLevel">
        <el-select v-model="queryParams.alarmLevel" placeholder="所有告警等级" clearable>
          <el-option v-for="dict in dict.type.machine_alarm_level" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>


      <el-form-item label="农机类型" prop="machineType">
        <el-select v-model="queryParams.machineType" placeholder="所有农机类型" clearable>
          <el-option v-for="dict in dict.type.agricultural_machine_type" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>



      <el-form-item label="所属农场" prop="deptIdList">
        <treeselect v-model="queryParams.deptIdList" :options="deptOptions" multiple :flat="true" :limit="1"
          :limitText="count => `+${count}`" style="width:200px" :show-count="true" placeholder="请选所属农场" />
      </el-form-item>

      <el-form-item label="告警时间">
        <el-date-picker v-model="daterangeAlarmTime" 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 label="处理状态" prop="handledStatus">
        <el-select v-model="queryParams.handledStatus" placeholder="所有状态" clearable>
          <el-option v-for="dict in dict.type.machine_handled_status" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>

      <el-form-item>
        <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="statistics-panel">
      <el-row :gutter="20">
        <el-col :span="6">
          <div class="stat-card total">
            <div class="stat-header">
              <span class="stat-title">今日告警总数</span>
            </div>
            <div class="stat-content">
              <div class="stat-number">{{ todayStatistics.total }}</div>
              <div class="stat-change" :class="todayStatistics.change >= 0 ? 'increase' : 'decrease'">
                <span>较昨日 {{ todayStatistics.change >= 0 ? '+' : '' }}{{ todayStatistics.change }}</span>
              </div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card emergency">
            <div class="stat-header">
              <span class="stat-title">紧急告警</span>
            </div>
            <div class="stat-content">
              <div class="stat-number">{{ levelStatistics.emergency.total }}</div>
              <div class="stat-detail">
                <span>未处理: {{ levelStatistics.emergency.unprocessed }}</span>
              </div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card warning">
            <div class="stat-header">
              <span class="stat-title">警告</span>
            </div>
            <div class="stat-content">
              <div class="stat-number">{{ levelStatistics.warning.total }}</div>
              <div class="stat-detail">
                <span>未处理: {{ levelStatistics.warning.unprocessed }}</span>
              </div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card info">
            <div class="stat-header">
              <span class="stat-title">提示信息</span>
            </div>
            <div class="stat-content">
              <div class="stat-number">{{ levelStatistics.info.total }}</div>
              <div class="stat-detail">
                <span>未处理: {{ levelStatistics.info.unprocessed }}</span>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['base:machineAlarmRecords:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="machineAlarmRecordsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="告警ID" align="center" prop="id" />
      <!-- <el-table-column label="告警等级" align="center" prop="alarmLevel">
        <template slot-scope="scope">
          <span :class="['custom-tag', 'level-tag', getAlertLevelClass(scope.row.alarmLevel)]">
            {{ getAlertLevelText(scope.row.alarmLevel) }}
          </span>
        </template>
</el-table-column> -->


      <el-table-column label="告警等级" align="center" prop="alarmLevel">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.machine_alarm_level" :value="scope.row.alarmLevel" />
        </template>
      </el-table-column>

      <el-table-column label="农机名称" align="center" key="machineName" prop="machineName" />

      <el-table-column label="农机编号" align="center" prop="machineCode" />

      <!--  <el-table-column label="农机类型" align="center" prop="machineType">
        <template slot-scope="scope">
          <span>{{ getMachineType(scope.row.machineId) }}</span>
        </template>
      </el-table-column> -->

      <el-table-column label="农机类型" align="center" prop="machineType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.agricultural_machine_type" :value="scope.row.machineType" />
        </template>
      </el-table-column>

      <el-table-column label="所属农场" align="center" key="deptName" prop="deptName" />


      <!-- <el-table-column label="所属农场" align="center" prop="farmName">
        <template slot-scope="scope">
          <span>{{ getFarmName(scope.row.machineId) }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="告警类型" align="center" prop="alarmType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.machine_alarm_type" :value="scope.row.alarmType" />
        </template>
      </el-table-column>
      <el-table-column label="告警内容" align="center" prop="alarmDesc" />
      <el-table-column label="告警时间" align="center" prop="alarmTime" width="180">
        <template slot-scope="scope">
          <span>{{ scope.row.alarmTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="处理状态" align="center" prop="handledStatus">
        <template slot-scope="scope">
          <span :class="['custom-tag', 'status-tag', getProcessStatusClass(scope.row.handledStatus)]">
            {{ getProcessStatusText(scope.row.handledStatus) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="处理人" align="center" prop="handlerName" />
      <el-table-column label="处理时间" align="center" prop="handleTime" width="180">
        <template slot-scope="scope">
          <span>{{ scope.row.handleTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleDetail(scope.row)">查看</el-button>
          <el-button
            v-if="scope.row.handledStatus == 0 || scope.row.handledStatus == '0' || scope.row.handledStatus == 2 || scope.row.handledStatus == '2'"
            size="mini" type="text" icon="el-icon-edit" @click="handleProcess(scope.row)"
            v-hasPermi="['base:machineAlarmRecords:edit']">处理</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="detailOpen" width="600px" append-to-body>
      <div class="alert-detail">
        <!-- 主要告警信息卡片 -->
        <div class="alert-card">
          <!-- 头部信息 -->
          <div class="alert-header">
            <div class="alert-level-tag">
              <span :class="['custom-tag', 'level-tag', getAlertLevelClass(currentRecord.alarmLevel)]">
                {{ getAlertLevelText(currentRecord.alarmLevel) }}
              </span>
            </div>
            <div class="alert-time">{{ parseTime(currentRecord.alarmTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</div>
          </div>

          <!-- 告警内容 -->
          <div class="alert-content">
            {{ getAlertContent(currentRecord) }}
          </div>
        </div>

        <!-- 设备信息 -->
        <div class="section">
          <div class="section-title">设备信息</div>
          <div class="device-info">
            <div class="info-grid">
              <div class="info-item">
                <span class="label">农机名称</span>
                <span class="value">{{ currentRecord.machineName }}</span>
              </div>
              <div class="info-item">
                <span class="label">农机编号</span>
                <span class="value">{{ currentRecord.machineCode }}</span>
              </div>
              <div class="info-item">
                <span class="label">农机类型</span>
                <span class="value status">
                  <dict-tag :options="dict.type.agricultural_machine_type" :value="currentRecord.machineType" />
                </span>
              </div>
              <div class="info-item">
                <span class="label">所属农场</span>
                <span class="value">{{ currentRecord.deptName }}</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 处理状态 -->
        <div class="section">
          <div class="section-title">处理状态</div>
          <div class="status-info">
            <div class="status-item">
              <span class="label">当前状态</span>
              <span class="value status">
                <!-- <span :class="['custom-tag', 'status-tag', getProcessStatusClass(currentRecord.handledStatus)]">
                  {{ getProcessStatusText(currentRecord.handledStatus) }}
                </span> -->
                <dict-tag :options="dict.type.machine_handled_status" :value="currentRecord.handledStatus" />
              </span>
            </div>
            <div class="status-item">
              <span class="label">处理人</span>
              <span class="value">{{ currentRecord.handlerName || '-' }}</span>
            </div>
            <div class="status-item">
              <span class="label">处理时间</span>
              <span class="value">{{
                currentRecord.handleTime

                }}</span>
            </div>
            <div class="status-item full-width">
              <span class="label">处理记录</span>
              <div class="process-record">
                {{ currentRecord.handleDesc || '暂无处理记录' }}
              </div>
            </div>
          </div>
        </div>

        <!-- 附件信息 -->
        <div class="section">
          <div class="section-title">附件信息</div>
          <div class="attachment-info">
            <div v-if="currentRecord.attachments && currentRecord.attachments.length > 0" class="attachment-list">
              <div v-for="(attachment, index) in getAttachmentList(currentRecord.attachments)" :key="index"
                class="attachment-item">
                <div class="attachment-preview">
                  <i v-if="isImage(attachment.name)" class="el-icon-picture-outline"></i>
                  <i v-else class="el-icon-document"></i>
                </div>
                <div class="attachment-details">
                  <div class="attachment-name" :title="attachment.name">{{ attachment.name }}</div>
                  <div class="attachment-size">{{ formatFileSize(attachment.size) }}</div>
                </div>
                <div class="attachment-actions">
                  <el-button size="mini" type="text" @click="downloadAttachment(attachment)">下载</el-button>
                  <el-button v-if="isImage(attachment.name)" size="mini" type="text"
                    @click="previewImage(attachment)">预览</el-button>
                </div>
              </div>
            </div>
            <div v-else class="no-attachment">
              <i class="el-icon-folder-opened"></i>
              <span>暂无附件</span>
            </div>
          </div>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="detailOpen = false">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 处理告警对话框 -->
    <el-dialog title="处理告警" :visible.sync="processOpen" width="500px" append-to-body>
      <el-form ref="processForm" :model="processForm" :rules="processRules" label-width="80px">
        <el-form-item label="告警信息">
          <div class="process-alert-info">
            <div class="info-item-row">
              <span class="label">农机编号:</span>
              <span class="value">{{ processForm.machineCode }}</span>
            </div>
            <div class="info-item-row">
              <span class="label">农机名称:</span>
              <span class="value">{{ processForm.machineName }}</span>
            </div>
            <div class="alert-content-preview">
              {{ getAlertContent(processForm) }}
            </div>
          </div>
        </el-form-item>
        <el-form-item label="处理结果" prop="handledStatus">
          <el-select v-model="processForm.handledStatus" placeholder="请选择处理结果">
            <el-option label="未处理" :value="0"></el-option>
            <el-option label="已处理" :value="1"></el-option>
            <el-option label="处理中" :value="2"></el-option>
            <el-option label="忽略" :value="3"></el-option>
          </el-select>

        </el-form-item>
        <el-form-item label="处理备注" prop="handleDesc">
          <el-input v-model="processForm.handleDesc" type="textarea" :rows="4" placeholder="请输入处理备注..." maxlength="500"
            show-word-limit />
        </el-form-item>
        <el-form-item label="附件上传">
          <file-upload v-model="processForm.attachments" :limit="5" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitProcess" :loading="processLoading">确 定</el-button>
        <el-button @click="cancelProcess">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改农机故障告警记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="农机ID" prop="machineId">
          <el-input v-model="form.machineId" placeholder="请输入农机ID" />
        </el-form-item>
        <el-form-item label="报警类型" prop="alarmType">
          <el-select v-model="form.alarmType" placeholder="请选择报警类型">
            <el-option v-for="dict in dict.type.machine_alarm_type" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="报警级别" prop="alarmLevel">
          <el-select v-model="form.alarmLevel" placeholder="请选择报警级别">
            <el-option v-for="dict in dict.type.machine_alarm_level" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="报警描述" prop="alarmDesc">
          <el-input v-model="form.alarmDesc" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="报警时间" prop="alarmTime">
          <el-date-picker clearable v-model="form.alarmTime" type="date" value-format="yyyy-MM-dd"
            placeholder="请选择报警时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="报警位置信息" prop="locationInfo">
          <el-input v-model="form.locationInfo" placeholder="请输入报警位置信息" />
        </el-form-item>
        <el-form-item label="处理状态" prop="handledStatus">
          <el-radio-group v-model="form.handledStatus">
            <el-radio v-for="dict in dict.type.machine_handled_status" :key="dict.value"
              :label="parseInt(dict.value)">{{
                dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="处理人ID" prop="handlerId">
          <el-input v-model="form.handlerId" placeholder="请输入处理人ID" />
        </el-form-item>
        <el-form-item label="处理人姓名" prop="handlerName">
          <el-input v-model="form.handlerName" placeholder="请输入处理人姓名" />
        </el-form-item>
        <el-form-item label="处理时间" prop="handleTime">
          <el-date-picker clearable v-model="form.handleTime" type="date" value-format="yyyy-MM-dd"
            placeholder="请选择处理时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="处理描述" prop="handleDesc">
          <el-input v-model="form.handleDesc" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="解决时间" prop="resolvedTime">
          <el-date-picker clearable v-model="form.resolvedTime" type="date" value-format="yyyy-MM-dd"
            placeholder="请选择解决时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listMachineAlarmRecords, getMachineAlarmRecords, delMachineAlarmRecords, addMachineAlarmRecords, updateMachineAlarmRecords } from "@/api/base/machineAlarmRecords"
import { deptTreeSelect } from "@/api/system/user";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  name: "MachineAlarmRecords",
  components: { Treeselect },
  dicts: ['machine_alarm_level', 'machine_alarm_type', 'machine_handled_status', 'agricultural_machine_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 农机故障告警记录表格数据
      machineAlarmRecordsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 告警详情对话框
      detailOpen: false,
      // 当前记录
      currentRecord: {},
      // 处理告警对话框
      processOpen: false,
      // 处理表单
      processForm: {},
      // 处理规则
      processRules: {
        handledStatus: [{ required: true, message: '请选择处理结果', trigger: 'change' }],
        handleDesc: [{ required: true, message: '请输入处理备注', trigger: 'blur' }],
      },

      // 部门树选项
      deptOptions: undefined,
      // 处理按钮加载中
      processLoading: false,
      // 告警时间范围
      daterangeAlarmTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        machineCode: null,
        machineName: null,
        alarmLevel: null,
        machineType: null,
        handledStatus: null,
        farmId: null,
        alarmTime: null,
        deptIdList: [],
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        machineId: [
          { required: true, message: "农机ID不能为空", trigger: "blur" }
        ],
        alarmType: [
          { required: true, message: "报警类型不能为空", trigger: "change" }
        ],
        alarmDesc: [
          { required: true, message: "报警描述不能为空", trigger: "blur" }
        ],
      },
      // 今日统计数据
      todayStatistics: {
        total: 0,
        change: 0
      },
      // 各等级统计数据
      levelStatistics: {
        emergency: {
          total: 0,
          unprocessed: 0
        },
        warning: {
          total: 0,
          unprocessed: 0
        },
        info: {
          total: 0,
          unprocessed: 0
        }
      }
    }
  },
  created() {
    this.getList()
    this.getDeptTree();
    //this.getStatistics()
  },
  methods: {

    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data;
      });
    },


    /** 查询农机故障告警记录列表 */
    getList() {
      this.loading = true
      this.queryParams.params = {}
      if (null != this.daterangeAlarmTime && '' != this.daterangeAlarmTime) {
        this.queryParams.params["beginAlarmTime"] = this.daterangeAlarmTime[0]
        this.queryParams.params["endAlarmTime"] = this.daterangeAlarmTime[1]
      }
      listMachineAlarmRecords(this.queryParams).then(response => {
        this.machineAlarmRecordsList = response.rows
        this.total = response.total
        this.loading = false
        // 获取列表后更新统计数据
        this.updateStatisticsFromList()
      })
    },
    /** 获取统计数据 */
    getStatistics() {
      // 这里可以调用专门的统计API
      // 暂时使用模拟数据
      this.todayStatistics = {
        total: 24,
        change: 8
      }
      this.levelStatistics = {
        emergency: {
          total: 2,
          unprocessed: 1
        },
        warning: {
          total: 3,
          unprocessed: 2
        },
        info: {
          total: 1,
          unprocessed: 0
        }
      }
    },
    /** 从列表数据更新统计 */
    updateStatisticsFromList() {
      if (!this.machineAlarmRecordsList || this.machineAlarmRecordsList.length === 0) {
        return
      }

      // 重置统计数据
      this.levelStatistics = {
        emergency: { total: 0, unprocessed: 0 },
        warning: { total: 0, unprocessed: 0 },
        info: { total: 0, unprocessed: 0 }
      }

      // 今日日期
      const toDateStr = (dateLike) =>
        new Date(dateLike).toISOString().slice(0, 10);

      const today = toDateStr(new Date());
      const yesterday = toDateStr(Date.now() - 86400000);

      let todayCount = 0;
      let yesterdayCount = 0;

      // 遍历记录统计
      this.machineAlarmRecordsList.forEach(record => {
        // 统计今日告警
        if (!record.alarmTime) return;          // 空值跳过
        const alertDay = toDateStr(record.alarmTime);

        if (alertDay === today) todayCount++;
        if (alertDay === yesterday) yesterdayCount++;

        // 统计各等级告警
        const level = record.alarmLevel
        const isUnprocessed = record.handledStatus == 0 || record.handledStatus == '0' || record.handledStatus == 2 || record.handledStatus == '2'

        // 根据告警等级统计 (1-紧急, 2-告警, 3-提示)
        // 根据告警等级统计 (1-提示, 2-告警, 3-紧急)
        if (level == 1 || level === '1') {
          this.levelStatistics.info.total++
          if (isUnprocessed) this.levelStatistics.info.unprocessed++
        } else if (level == 2 || level === '2') {
          this.levelStatistics.warning.total++
          if (isUnprocessed) this.levelStatistics.warning.unprocessed++
        } else if (level == 3 || level === '3') {
          this.levelStatistics.emergency.total++
          if (isUnprocessed) this.levelStatistics.emergency.unprocessed++
        }
      })

      // 更新今日统计 (这里只是示例，实际应该从后端获取完整统计)
      this.todayStatistics.change = todayCount - yesterdayCount;
      if (todayCount > 0) {
        this.todayStatistics.total = todayCount
      }
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        machineId: null,
        machineCode: null,
        machineName: null,
        alarmType: null,
        alarmLevel: null,
        alarmDesc: null,
        alarmTime: null,
        locationInfo: null,
        handledStatus: null,
        handlerId: null,
        handlerName: null,
        handleTime: null,
        handleDesc: null,
        resolvedTime: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeAlarmTime = []
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加农机故障告警记录"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getMachineAlarmRecords(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改农机故障告警记录"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateMachineAlarmRecords(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addMachineAlarmRecords(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除农机故障告警记录编号为"' + ids + '"的数据项？').then(function () {
        return delMachineAlarmRecords(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => { })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('base/machineAlarmRecords/export', {
        ...this.queryParams
      }, `machineAlarmRecords_${new Date().getTime()}.xlsx`)
    },
    /** 根据农机ID获取农机名称 */
    getMachineName(machineId) {
      const machineNames = {
        1: '约翰迪尔拖拉机',
        2: '久保田收割机',
        3: '雷沃旋耕机',
        4: '东方红播种机',
        5: '福田插秧机'
      }
      return machineNames[machineId] || '未知农机'
    },
    /** 根据农机ID获取农机类型 */
    getMachineType(machineId) {
      const machineTypes = {
        1: '拖拉机',
        2: '收割机',
        3: '旋耕机',
        4: '播种机',
        5: '插秧机'
      }
      return machineTypes[machineId] || '未知类型'
    },
    /** 根据农机ID获取所属农场 */
    getFarmName(machineId) {
      const farmNames = {
        1: '绿野农场',
        2: '丰收农场',
        3: '田园农场',
        4: '生态农场',
        5: '科技农场'
      }
      return farmNames[machineId] || '未知农场'
    },
    /** 获取处理状态文本 */
    getProcessStatusText(status) {
      const statusMap = {
        '0': '未处理',
        '1': '已处理',
        '2': '处理中',
        '3': '忽略',
        0: '未处理',
        1: '已处理',
        2: '处理中',
        3: '忽略'
      }
      return statusMap[status] || '未知状态'
    },
    /** 获取处理状态样式类 */
    getProcessStatusClass(status) {
      const statusMap = {
        '0': 'pending',
        '1': 'processed',
        '2': 'processing',
        '3': 'ignored',
        0: 'pending',
        1: 'processed',
        2: 'processing',
        3: 'ignored'
      }
      return statusMap[status] || 'pending'
    },
    /** 获取告警等级样式类 */
    getAlertLevelClass(level) {
      const levelMap = {
        '1': 'emergency',
        '2': 'warning',
        '3': 'info',
        1: 'emergency',
        2: 'warning',
        3: 'info'
      }
      return levelMap[level] || 'info'
    },
    /** 获取告警等级文本 */
    getAlertLevelText(level) {
      const levelMap = {
        '1': '紧急',
        '2': '告警',
        '3': '提示',
        1: '紧急',
        2: '告警',
        3: '提示'
      }
      return levelMap[level] || '未知'
    },
    /** 查看告警详情 */
    handleDetail(record) {
      // 可以根据需要调用API获取更详细的信息
      // getMachineAlarmRecords(record.id).then(response => {
      //   this.currentRecord = response.data
      //   this.detailOpen = true
      // })

      // 当前直接使用列表数据显示
      this.currentRecord = { ...record }
      this.detailOpen = true
    },
    /** 获取告警内容 */
    getAlertContent(record) {
      if (!record.alarmDesc) {
        return '暂无告警内容'
      }

      let content = record.alarmDesc

      // 尝试去掉设备名称前缀
      // 匹配模式：设备XXX + 告警内容
      const devicePatterns = [
        // 匹配"设备D1001温度异常"格式
        /^设备[A-Za-z0-9]+(.+)$/,
        // 匹配"D1001温度异常"格式  
        /^[A-Za-z0-9]+(.+)$/,
        // 匹配设备名称开头的格式
        /^.+?号(.+)$/,
        /^.+?站(.+)$/
      ]

      // 如果告警内容包含设备信息，尝试去掉设备前缀
      if (record.machineId && content.includes(record.machineId)) {
        // 去掉设备编号前缀
        content = content.replace(new RegExp(`^.*?${record.machineId}`, ''), '')
      } else {
        // 使用通用模式尝试去掉设备前缀
        for (let pattern of devicePatterns) {
          const match = content.match(pattern)
          if (match && match[1]) {
            content = match[1]
            break
          }
        }
      }

      // 清理开头的标点符号
      content = content.replace(/^[：:，,\s]+/, '')

      return content || record.alarmDesc
    },
    /** 处理告警 */
    handleProcess(record) {
      this.resetProcessForm()
      // this.currentRecord = { ...record }
      this.processForm = {
        ...record
      }
      this.processOpen = true
    },
    /** 提交处理 */
    submitProcess() {
      this.$refs.processForm.validate((valid) => {
        if (valid) {
          this.processLoading = true

          // 准备要更新的数据
          const updateData = {
            id: this.processForm.id,
            handledStatus: this.processForm.handledStatus,
            handleDesc: this.processForm.handleDesc,
            attachments: this.processForm.attachments
          }

          updateMachineAlarmRecords(updateData).then(response => {
            this.$modal.msgSuccess("处理成功")
            this.processOpen = false
            this.processLoading = false
            this.resetProcessForm()
            // 刷新列表
            this.getList()
          }).catch(() => {
            this.processLoading = false
          })
        }
      })
    },
    /** 取消处理 */
    cancelProcess() {
      this.processOpen = false
      this.resetProcessForm()
    },
    /** 重置处理表单 */
    resetProcessForm() {
      this.processForm = {
        id: null,
        machineId: null,
        alarmType: null,
        alarmLevel: null,
        alarmDesc: null,
        alarmTime: null,
        locationInfo: null,
        handledStatus: 0,
        handleDesc: null,
        handlerName: null,
        attachments: null
      }
      if (this.$refs.processForm) {
        this.$refs.processForm.resetFields()
      }
    },
    /** 获取附件列表 */
    getAttachmentList(attachments) {
      if (!attachments) return []
      // 如果attachments是字符串，尝试解析为JSON
      if (typeof attachments === 'string') {
        try {
          return JSON.parse(attachments)
        } catch (e) {
          // 如果解析失败，按逗号分割处理
          return attachments.split(',').map(url => ({
            name: this.getFileNameFromUrl(url),
            url: url,
            size: 0
          }))
        }
      }
      // 如果是数组直接返回
      return Array.isArray(attachments) ? attachments : []
    },
    /** 从URL中提取文件名 */
    getFileNameFromUrl(url) {
      if (!url) return '未知文件'
      const parts = url.split('/')
      return parts[parts.length - 1] || '未知文件'
    },
    /** 判断是否为图片 */
    isImage(fileName) {
      if (!fileName) return false
      const imageExts = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp']
      const ext = fileName.toLowerCase().substring(fileName.lastIndexOf('.'))
      return imageExts.includes(ext)
    },
    /** 格式化文件大小 */
    formatFileSize(size) {
      if (!size || size === 0) return '未知大小'
      if (size < 1024) return size + ' B'
      if (size < 1024 * 1024) return (size / 1024).toFixed(1) + ' KB'
      return (size / (1024 * 1024)).toFixed(1) + ' MB'
    },
    /** 下载附件 */
    downloadAttachment(attachment) {
      if (attachment.url) {
        window.open(attachment.url, '_blank')
      } else {
        this.$modal.msgError('附件链接无效')
      }
    },
    /** 预览图片 */
    previewImage(attachment) {
      if (attachment.url) {
        this.$modal.msgInfo('图片预览功能暂未实现，请点击下载查看')
        // 这里可以集成图片预览组件
        // this.$imagePreview([attachment.url])
      }
    }
  }
}
</script>

<style scoped>
/* 自定义标签样式 */
.custom-tag {
  display: inline-block;
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
  text-align: center;
  min-width: 50px;
  line-height: 1.2;
}

/* 告警等级标签 */
.level-tag.emergency {
  background-color: #fef2f2;
  color: #dc2626;
  border: 1px solid #fecaca;
}

.level-tag.warning {
  background-color: #fffbeb;
  color: #d97706;
  border: 1px solid #fed7aa;
}

.level-tag.info {
  background-color: #eff6ff;
  color: #2563eb;
  border: 1px solid #bfdbfe;
}

/* 处理状态标签 */
.status-tag.pending {
  background-color: #fef2f2;
  color: #dc2626;
  border: 1px solid #fecaca;
}

.status-tag.processing {
  background-color: #fffbeb;
  color: #d97706;
  border: 1px solid #fed7aa;
}

.status-tag.processed {
  background-color: #f0fdf4;
  color: #16a34a;
  border: 1px solid #bbf7d0;
}

.status-tag.ignored {
  background-color: #f9fafb;
  color: #6b7280;
  border: 1px solid #d1d5db;
}

/* 统计面板样式 */
.statistics-panel {
  margin-bottom: 16px;
  padding: 20px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
}

/* 统一各部分间距 */
.app-container .el-form {
  margin-bottom: 16px;
}

.app-container .mb8 {
  margin-bottom: 16px !important;
}

.app-container .el-table {
  margin-top: 0;
}

.stat-card {
  border-radius: 12px;
  padding: 20px;
  height: 140px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  transition: all 0.3s ease;
  cursor: pointer;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1), 0 2px 6px rgba(0, 0, 0, 0.05);
  position: relative;
  overflow: hidden;
  color: #fff;
}

.stat-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15), 0 4px 10px rgba(0, 0, 0, 0.1);
}

.stat-card.total {
  background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%);
}

.stat-card.emergency {
  background: linear-gradient(135deg, #ef4444 0%, #f97316 100%);
}

.stat-card.warning {
  background: linear-gradient(135deg, #f59e0b 0%, #eab308 100%);
}

.stat-card.info {
  background: linear-gradient(135deg, #06b6d4 0%, #3b82f6 100%);
}

.stat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.stat-title {
  font-size: 14px;
  font-weight: 600;
  color: rgba(255, 255, 255, 0.9);
  margin-bottom: 0;
  line-height: 1.2;
}

.stat-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: flex-start;
}

.stat-number {
  font-size: 36px;
  font-weight: 700;
  line-height: 1.0;
  margin: 8px 0;
  color: #fff;
}

.stat-change {
  font-size: 12px;
  font-weight: 500;
  color: rgba(255, 255, 255, 0.8);
  line-height: 1.2;
  margin: 0;
}

.stat-change.increase {
  color: rgba(255, 255, 255, 0.9);
}

.stat-change.decrease {
  color: rgba(255, 255, 255, 0.9);
}

.stat-detail {
  font-size: 12px;
  font-weight: 500;
  color: rgba(255, 255, 255, 0.85);
  line-height: 1.2;
  margin: 0;
}

/* 告警详情对话框样式 */
.alert-detail {
  padding: 10px;
}

.alert-card {
  background-color: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  border: 1px solid #e9ecef;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  border-left: 4px solid #f56c6c;
}

.alert-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 12px;
  border-bottom: 1px solid #e9ecef;
}

.alert-level-tag {
  font-weight: bold;
}

.alert-time {
  color: #909399;
  font-size: 14px;
}

.alert-content {
  color: #606266;
  line-height: 1.6;
  font-size: 14px;
}

.section {
  margin-bottom: 20px;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 15px;
  padding-bottom: 8px;
  border-bottom: 1px solid #ebeef5;
}

.device-info .info-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 15px;
}

.info-item {
  display: flex;
  flex-direction: column;
}

.info-item .label {
  color: #909399;
  font-size: 14px;
  margin-bottom: 5px;
}

.info-item .value {
  color: #303133;
  font-weight: 500;
  font-size: 15px;
}

.status-info {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 15px;
}

.status-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.status-item.full-width {
  grid-column: 1 / -1;
  flex-direction: column;
  align-items: flex-start;
  gap: 8px;
}

.status-item .label {
  color: #606266;
  font-size: 14px;
  font-weight: 500;
  min-width: 80px;
  flex-shrink: 0;
}

.status-item .value {
  color: #303133;
  font-weight: 600;
  flex: 1;
}

.status-item .value.status {
  display: flex;
  align-items: center;
}

.process-record {
  color: #606266;
  font-size: 14px;
  padding: 12px;
  background-color: #f8f9fa;
  border-radius: 4px;
  border: 1px solid #e9ecef;
  width: 100%;
  min-height: 50px;
  display: flex;
  align-items: center;
}

.dialog-footer {
  text-align: right;
}

.process-alert-info {
  background-color: #f8f9fa;
  border-radius: 4px;
  padding: 15px;
  margin-bottom: 10px;
  border: 1px solid #e9ecef;
}

.process-alert-info .info-item {
  display: inline-block;
  margin-right: 20px;
  margin-bottom: 8px;
}

.process-alert-info .info-item-row {
  display: block;
  margin-bottom: 8px;
}

.process-alert-info .label {
  color: #606266;
  font-size: 14px;
  margin-right: 5px;
}

.process-alert-info .value {
  color: #303133;
  font-weight: 500;
}

.alert-content-preview {
  color: #606266;
  font-size: 14px;
  line-height: 1.5;
  margin-top: 10px;
  padding-top: 10px;
  border-top: 1px solid #e9ecef;
}

/* 附件信息样式 */
.attachment-info {
  margin-top: 10px;
}

.attachment-list {
  background-color: #f8f9fa;
  border-radius: 4px;
  padding: 10px;
  border: 1px solid #e9ecef;
}

.attachment-item {
  display: flex;
  align-items: center;
  padding: 8px;
  background-color: #fff;
  border-radius: 4px;
  margin-bottom: 8px;
  border: 1px solid #e9ecef;
  transition: all 0.3s;
}

.attachment-item:hover {
  background-color: #f5f7fa;
  border-color: #409eff;
}

.attachment-item:last-child {
  margin-bottom: 0;
}

.attachment-preview {
  width: 32px;
  height: 32px;
  margin-right: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f0f2f5;
  border-radius: 4px;
  color: #606266;
  font-size: 16px;
}

.attachment-details {
  flex: 1;
  min-width: 0;
}

.attachment-name {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.attachment-size {
  font-size: 12px;
  color: #909399;
}

.attachment-actions {
  margin-left: 12px;
  flex-shrink: 0;
}

.no-attachment {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #909399;
  font-size: 14px;
  padding: 40px 20px;
  background-color: #f8f9fa;
  border-radius: 4px;
  border: 1px dashed #e9ecef;
}

.no-attachment i {
  font-size: 32px;
  margin-bottom: 8px;
  color: #c0c4cc;
}
</style>
