<!-- 预警发布 -->
<template>
  <div class="app-container warning-release-page">
    <el-card shadow="never" class="page-card header-card">
      <div class="page-header">
        <div>
          <div class="page-title">预警发布</div>
          <div class="page-subtitle">支持按预警类型、预警级别、发布时间查询，并对预警信息进行新增、编辑、查看、发布等操作</div>
        </div>
        <div class="header-actions">
          <el-button type="primary" icon="Plus" @click="handleAdd">新增预警</el-button>
          <el-button icon="Refresh" @click="loadList">刷新</el-button>
        </div>
      </div>
    </el-card>

    <el-card shadow="never" class="page-card">
      <el-form :model="queryParams" :inline="true">
        <el-form-item label="预警名称">
          <el-input
            v-model="queryParams.warningName"
            placeholder="请输入预警名称"
            clearable
            style="width: 220px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="预警类型">
          <el-select v-model="queryParams.warningType" placeholder="请选择预警类型" clearable style="width: 180px">
            <el-option
              v-for="item in warningTypeOptions"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="预警级别">
          <el-select v-model="queryParams.warningLevel" placeholder="请选择预警级别" clearable style="width: 180px">
            <el-option
              v-for="item in warningLevelOptions"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="发布时间">
          <el-date-picker
            v-model="queryParams.dateRange"
            type="datetimerange"
            value-format="YYYY-MM-DD HH:mm:ss"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            style="width: 360px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">查询</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card shadow="never" class="page-card">
      <el-table v-loading="loading" :data="warningList">
        <el-table-column label="序号" width="70" align="center">
          <template #default="scope">
            {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column label="预警编号" prop="warningNo" width="180" />
        <el-table-column label="预警名称" prop="warningName" min-width="180" show-overflow-tooltip />
        <el-table-column label="预警类型" prop="warningTypeText" width="120" />
        <el-table-column label="预警级别" width="110" align="center">
          <template #default="scope">
            <el-tag :type="getLevelTagType(scope.row.warningLevel)">
              {{ scope.row.warningLevelText || scope.row.warningLevel || "-" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="预警位置" prop="location" min-width="180" show-overflow-tooltip />
        <el-table-column label="发布时间" prop="publishTime" width="180" />
        <el-table-column label="发布人" prop="publisher" width="120" />
        <el-table-column label="状态" width="120" align="center">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="280" align="center">
          <template #default="scope">
            <el-button link type="primary" @click="handleView(scope.row)">查看</el-button>
            <el-button link type="primary" @click="handleEdit(scope.row)" v-if="scope.row.status === 'DRAFT'">编辑</el-button>
            <el-button link type="success" @click="handlePublish(scope.row)" v-if="scope.row.status === 'DRAFT'">发布</el-button>
            <el-button link type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="loadList"
      />
    </el-card>

    <el-dialog v-model="editVisible" :title="dialogTitle" width="860px" append-to-body @close="resetForm">
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px">
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="预警类型" prop="warningType">
              <el-select v-model="formData.warningType" placeholder="请选择预警类型" style="width: 100%" @change="handleTypeLevelChange">
                <el-option
                  v-for="item in warningTypeOptions"
                  :key="item.dictValue"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预警级别" prop="warningLevel">
              <el-select v-model="formData.warningLevel" placeholder="请选择预警级别" style="width: 100%" @change="handleTypeLevelChange">
                <el-option
                  v-for="item in warningLevelOptions"
                  :key="item.dictValue"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预警专项">
              <el-input v-model="formData.warningSpecial" placeholder="请输入预警专项" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="权属单位">
              <el-input v-model="formData.ownershipUnit" placeholder="请输入权属单位" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发布人">
              <el-input v-model="formData.publisher" placeholder="自动填充当前用户" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="处置人">
              <el-input v-model="formData.handler" placeholder="请选择处置人" readonly @click="openUserPicker">
                <template #suffix>
                  <el-icon style="cursor: pointer;" @click="openUserPicker"><Search /></el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="预警名称" prop="warningName">
              <el-input v-model="formData.warningName" placeholder="请输入预警名称" maxlength="100" show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="预警位置" prop="location">
              <el-input v-model="formData.location" placeholder="请输入预警位置" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="经度">
              <el-input v-model="formData.longitude" placeholder="请输入经度" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="纬度">
              <el-input v-model="formData.latitude" placeholder="请输入纬度" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发布时间">
              <el-date-picker
                v-model="formData.publishTime"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择发布时间"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-select v-model="formData.status" style="width: 100%">
                <el-option
                  v-for="item in warningStatusOptions"
                  :key="item.dictValue"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="内容描述" prop="warningContent">
              <el-input
                v-model="formData.warningContent"
                type="textarea"
                :rows="4"
                maxlength="500"
                show-word-limit
                placeholder="请输入预警内容描述"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="reasonOptions.length">
            <el-form-item label="推荐原因">
              <div class="reason-wrap">
                <el-tag
                  v-for="item in reasonOptions"
                  :key="item.reasonId"
                  class="reason-tag"
                  effect="plain"
                  @click="appendReason(item)"
                >
                  {{ item.reasonName }}
                </el-tag>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="formData.remark" type="textarea" :rows="2" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="附件上传">
              <div class="attachment-panel">
                <el-upload
                  ref="uploadRef"
                  action="#"
                  :auto-upload="false"
                  :show-file-list="false"
                  multiple
                  :on-change="handleUploadChange"
                  :on-exceed="handleUploadExceed"
                  :limit="9"
                  accept=".pdf,.doc,.docx,.xls,.xlsx,.zip,.jpg,.jpeg,.png"
                >
                  <el-button type="primary">选择附件</el-button>
                </el-upload>
                <div class="attachment-tip">支持常见文档、压缩包和图片，新增或编辑时会随保存接口一起上传。</div>
                <div v-if="formAttachments.length" class="attachment-list">
                  <div v-for="item in formAttachments" :key="item.uid || item.attachmentId || item.name" class="attachment-item">
                    <el-link
                      v-if="item.url"
                      :href="item.url"
                      target="_blank"
                      type="primary"
                      class="attachment-link"
                    >
                      {{ item.name }}
                    </el-link>
                    <span v-else class="attachment-link">{{ item.name }}</span>
                    <span class="attachment-meta">{{ item.sizeText || item.createTime || "" }}</span>
                    <el-button link type="danger" @click="removeAttachment(item)">移除</el-button>
                  </div>
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editVisible = false">取 消</el-button>
          <el-button type="primary" :loading="submitLoading" @click="submitForm">保 存</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="detailVisible" title="预警详情" width="900px" append-to-body>
      <template v-if="detailData.basicInfo">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="预警编号">{{ detailData.basicInfo.warningNo || "-" }}</el-descriptions-item>
          <el-descriptions-item label="预警名称">{{ detailData.basicInfo.warningName || "-" }}</el-descriptions-item>
          <el-descriptions-item label="预警类型">{{ formatTypeText(detailData.basicInfo.warningType) }}</el-descriptions-item>
          <el-descriptions-item label="预警级别">
            <el-tag :type="getLevelTagType(detailData.basicInfo.warningLevel)">
              {{ formatLevelText(detailData.basicInfo.warningLevel) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="预警专项">{{ detailData.basicInfo.warningSpecial || "-" }}</el-descriptions-item>
          <el-descriptions-item label="权属单位">{{ detailData.basicInfo.ownershipUnit || "-" }}</el-descriptions-item>
          <el-descriptions-item label="发布人">{{ detailData.basicInfo.publisher || "-" }}</el-descriptions-item>
          <el-descriptions-item label="处置人">{{ detailData.basicInfo.handler || "-" }}</el-descriptions-item>
          <el-descriptions-item label="预警位置" :span="2">{{ detailData.basicInfo.location || "-" }}</el-descriptions-item>
          <el-descriptions-item label="发布时间">{{ detailData.basicInfo.publishTime || "-" }}</el-descriptions-item>
          <el-descriptions-item label="状态">{{ getStatusText(detailData.basicInfo.status) }}</el-descriptions-item>
          <el-descriptions-item label="内容描述" :span="2">{{ detailData.basicInfo.warningContent || "-" }}</el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">{{ detailData.basicInfo.remark || "-" }}</el-descriptions-item>
        </el-descriptions>

        <el-divider content-position="left">关联报警</el-divider>
        <el-table :data="detailData.alarmList || []" border size="small">
          <el-table-column label="报警ID" prop="alarmId" min-width="160" />
          <el-table-column label="报警名称" prop="alarmName" min-width="180" show-overflow-tooltip />
          <el-table-column label="报警类型" min-width="120">
            <template #default="scope">
              {{ formatTypeText(scope.row.alarmType || scope.row.warningType) }}
            </template>
          </el-table-column>
        </el-table>

        <el-divider content-position="left">处置记录</el-divider>
        <el-table :data="detailData.disposalHistory || detailData.disposalList || []" border size="small">
          <el-table-column label="处置类型" prop="disposalTypeName" min-width="120" />
          <el-table-column label="处置人" prop="disposalUser" min-width="120" />
          <el-table-column label="处置内容" prop="disposalContent" min-width="220" show-overflow-tooltip />
          <el-table-column label="处置时间" prop="createTime" min-width="180" />
        </el-table>

        <el-divider content-position="left">附件信息</el-divider>
        <div v-if="(detailData.attachmentList || []).length" class="detail-attachment-list">
          <div v-for="item in detailData.attachmentList" :key="item.attachmentId || item.attachmentName" class="detail-attachment-item">
            <el-link :href="buildAttachmentUrl(item.attachmentUrl)" target="_blank" type="primary">
              {{ item.attachmentName || "附件" }}
            </el-link>
            <span>{{ item.createTime || "-" }}</span>
          </div>
        </div>
        <el-empty v-else description="暂无附件信息" />
      </template>
    </el-dialog>

    <!-- 处置人选择对话框 -->
    <el-dialog v-model="userPickerVisible" title="选择处置人" width="900px" append-to-body @open="loadUserPickerData">
      <div class="user-picker-container">
        <!-- 左侧部门树 -->
        <div class="user-picker-left">
          <div class="picker-title">部门列表</div>
          <el-input v-model="deptFilterText" placeholder="搜索部门" clearable style="margin-bottom: 12px;" />
          <el-tree
            ref="deptTreeRef"
            :data="deptTree"
            :props="{ label: 'label', children: 'children' }"
            :filter-node-method="filterDeptNode"
            :highlight-current="true"
            default-expand-all
            @node-click="handleDeptClick"
          />
        </div>
        <!-- 右侧用户列表 -->
        <div class="user-picker-right">
          <div class="picker-title">
            用户列表
            <span v-if="currentDeptName" class="current-dept">（{{ currentDeptName }}）</span>
          </div>
          <el-input v-model="userFilterText" placeholder="搜索用户" clearable style="margin-bottom: 12px;" @input="filterUserList" />
          <el-table
            v-loading="userPickerLoading"
            :data="filteredUserList"
            highlight-current-row
            @current-change="handleUserCurrentChange"
            height="400"
          >
            <el-table-column label="用户名称" prop="userName" min-width="120" show-overflow-tooltip />
            <el-table-column label="用户昵称" prop="nickName" min-width="120" show-overflow-tooltip />
            <el-table-column label="部门" prop="deptName" min-width="140" show-overflow-tooltip />
            <el-table-column label="手机号码" prop="phonenumber" width="130" />
          </el-table>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="userPickerVisible = false">取 消</el-button>
          <el-button type="primary" :disabled="!selectedUser" @click="confirmSelectUser">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {computed, onMounted, reactive, ref, watch} from "vue";
import {ElMessage, ElMessageBox} from "element-plus";
import { Search } from "@element-plus/icons-vue";
import useUserStore from "@/store/modules/user";
import { deptTreeSelect, listUser } from "@/api/system/user";
import {
  deleteYjxxData,
  getAlertTypeDictionaryData,
  getdbyjlistData,
  getWarningDetailData,
  getWarningReasonListData,
  releaseYjxxData,
  submitYjxxData,
  updateYjxxData
} from "@/api/smxyjldczxt/yjxxfb/yjfb.js";

const userStore = useUserStore();

const loading = ref(false);
const submitLoading = ref(false);
const total = ref(0);
const warningList = ref([]);
const warningTypeOptions = ref([]);
const warningLevelOptions = ref([]);
const warningStatusOptions = ref([]);
const reasonOptions = ref([]);
const uploadRef = ref();
const formAttachments = ref([]);
const minioBaseUrl = (import.meta.env.VITE_APP_MINIO_BASE_URL || "").trim();

const editVisible = ref(false);
const detailVisible = ref(false);
const userPickerVisible = ref(false);
const dialogTitle = ref("新增预警");
const isEdit = ref(false);
const formRef = ref();
const detailData = ref({});

// 用户选择器相关
const deptTree = ref([]);
const userList = ref([]);
const filteredUserList = ref([]);
const selectedDeptId = ref("");
const currentDeptName = ref("");
const selectedUser = ref(null);
const userPickerLoading = ref(false);
const deptFilterText = ref("");
const userFilterText = ref("");
const deptTreeRef = ref();

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  warningName: "",
  warningType: "",
  warningLevel: "",
  dateRange: []
});

const formData = reactive(createEmptyForm());

const formRules = {
  warningType: [{ required: true, message: "请选择预警类型", trigger: "change" }],
  warningLevel: [{ required: true, message: "请选择预警级别", trigger: "change" }],
  warningName: [{ required: true, message: "请输入预警名称", trigger: "blur" }],
  location: [{ required: true, message: "请输入预警位置", trigger: "blur" }],
  warningContent: [{ required: true, message: "请输入预警内容描述", trigger: "blur" }]
};

const warningTypeLabelMap = computed(() => {
  return warningTypeOptions.value.reduce((acc, item) => {
    acc[item.dictValue] = item.dictLabel;
    return acc;
  }, {});
});

const warningLevelLabelMap = computed(() => {
  return warningLevelOptions.value.reduce((acc, item) => {
    acc[item.dictValue] = item.dictLabel;
    return acc;
  }, {});
});

const warningStatusLabelMap = computed(() => {
  return warningStatusOptions.value.reduce((acc, item) => {
    acc[item.dictValue] = item.dictLabel;
    return acc;
  }, {});
});

function createEmptyForm() {
  return {
    warningId: "",
    warningNo: "",
    warningName: "",
    warningType: "",
    warningLevel: "",
    warningSpecial: "",
    location: "",
    longitude: "",
    latitude: "",
    ownershipUnit: "",
    publisher: "",
    publishTime: "",
    handler: "",
    status: "DRAFT",
    warningContent: "",
    remark: ""
  };
}

function resetForm() {
  Object.assign(formData, createEmptyForm());
  reasonOptions.value = [];
  formAttachments.value = [];
  uploadRef.value?.clearFiles?.();
  formRef.value?.clearValidate();
}

function formatFileSize(bytes) {
  if (!bytes) return "";
  const units = ["B", "KB", "MB", "GB"];
  const index = Math.floor(Math.log(bytes) / Math.log(1024));
  return `${(bytes / 1024 ** index).toFixed(2)} ${units[index]}`;
}

function buildAttachmentUrl(path) {
  if (!path) return "";
  if (/^https?:\/\//i.test(path)) {
    return path;
  }
  const base = minioBaseUrl.endsWith("/") ? minioBaseUrl : `${minioBaseUrl}/`;
  return `${base}${String(path).replace(/^\/+/, "")}`;
}

function normalizeExistingAttachment(item) {
  return {
    uid: item.attachmentId || item.attachmentName,
    name: item.attachmentName || "附件",
    url: buildAttachmentUrl(item.attachmentUrl),
    attachmentId: item.attachmentId,
    attachmentUrl: item.attachmentUrl,
    createTime: item.createTime || "",
    raw: null,
    sizeText: item.attachmentSize ? formatFileSize(item.attachmentSize) : ""
  };
}

function handleUploadChange(file) {
  if (!file?.raw) return;
  formAttachments.value.push({
    uid: file.uid,
    name: file.name,
    raw: file.raw,
    url: "",
    sizeText: formatFileSize(file.size)
  });
}

function handleUploadExceed() {
  ElMessage.warning("最多上传 9 个附件");
}

function removeAttachment(item) {
  formAttachments.value = formAttachments.value.filter((current) => current.uid !== item.uid);
}

function formatTypeText(value) {
  return warningTypeLabelMap.value[value] || value || "-";
}

function formatLevelText(value) {
  return warningLevelLabelMap.value[value] || value || "-";
}

function getLevelTagType(level) {
  return {
    "0": "danger",
    "1": "danger",
    "2": "warning",
    "3": "success",
    "4": "info"
  }[level] || "info";
}

function getStatusText(status) {
  return warningStatusLabelMap.value[status] || status || "-";
}

function getStatusTagType(status) {
  // 按照预警状态语义设置 tag 颜色
  return {
    DRAFT: "info",        // 草稿 - 灰色（未发布）
    PENDING: "warning",   // 待办 - 黄色（等待处置）
    PROCESSING: "warning", // 处置中 - 黄色（进行中）
    RELEASED: "success",  // 已发布 - 绿色
    HANDLED: "success",   // 已处置 - 绿色（已完成）
    CLOSED: "info"        // 已解除 - 灰色
  }[status] || "info";
}

function normalizeWarningRow(item) {
  const row = { ...item };
  row.warningId = item.warningId || item.warning_id || "";
  row.warningNo = item.warningNo || item.warning_no || "";
  row.warningName = item.warningName || item.warning_name || "";
  row.warningType = item.warningType || item.warning_type || "";
  row.warningLevel = item.warningLevel || item.warning_level || "";
  row.warningSpecial = item.warningSpecial || item.warning_special || "";
  row.location = item.location || "";
  row.longitude = item.longitude || "";
  row.latitude = item.latitude || "";
  row.ownershipUnit = item.ownershipUnit || item.ownership_unit || "";
  row.publisher = item.publisher || "";
  row.publishTime = item.publishTime || item.publish_time || "";
  row.handler = item.handler || "";
  row.status = item.status || "";
  row.warningContent = item.warningContent || item.warning_content || "";
  row.remark = item.remark || "";
  row.warningTypeText = formatTypeText(row.warningType);
  row.warningLevelText = formatLevelText(row.warningLevel);
  return row;
}

function normalizeAlarmRow(item) {
  return {
    ...item,
    alarmId: item.alarmId || item.alarm_id || "",
    alarmName: item.alarmName || item.alarm_name || item.deviceName || item.device_name || "",
    alarmType: item.alarmType || item.alarm_type || item.warningType || item.warning_type || ""
  };
}

function normalizeDisposalRow(item) {
  return {
    ...item,
    disposalTypeName: item.disposalTypeName || item.disposal_type_name || item.disposalType || item.disposal_type || "",
    disposalUser: item.disposalUser || item.disposal_user || "",
    disposalContent: item.disposalContent || item.disposal_content || "",
    createTime: item.createTime || item.create_time || ""
  };
}

async function loadDicts() {
  const [typeRes, levelRes, statusRes] = await Promise.all([
    getAlertTypeDictionaryData({ dictType: "alert_type" }),
    getAlertTypeDictionaryData({ dictType: "alert_level" }),
    getAlertTypeDictionaryData({ dictType: "pre_alarm_status" })
  ]);
  warningTypeOptions.value = typeRes.rows || [];
  warningLevelOptions.value = levelRes.rows || [];
  warningStatusOptions.value = statusRes.rows || [];
}

async function loadReasonOptions() {
  if (!formData.warningType || !formData.warningLevel) {
    reasonOptions.value = [];
    return;
  }
  const res = await getWarningReasonListData({
    warningType: formData.warningType,
    warningLevel: formData.warningLevel
  });
  reasonOptions.value = res.data || [];
}

function handleTypeLevelChange() {
  loadReasonOptions();
}

function appendReason(item) {
  const content = item.description ? `${item.reasonName}：${item.description}` : item.reasonName;
  formData.warningContent = formData.warningContent
    ? `${formData.warningContent}\n${content}`
    : content;
}

async function loadList() {
  loading.value = true;
  try {
    const params = {
      pageNum: queryParams.pageNum,
      pageSize: queryParams.pageSize,
      warningName: queryParams.warningName,
      warningType: queryParams.warningType,
      warningLevel: queryParams.warningLevel,
      startTime: queryParams.dateRange?.[0] || "",
      endTime: queryParams.dateRange?.[1] || ""
    };
    const res = await getdbyjlistData(params);
    warningList.value = (res.data?.records || []).map(normalizeWarningRow);
    total.value = res.data?.total || 0;
  } finally {
    loading.value = false;
  }
}

function handleQuery() {
  queryParams.pageNum = 1;
  loadList();
}

function resetQuery() {
  queryParams.pageNum = 1;
  queryParams.pageSize = 10;
  queryParams.warningName = "";
  queryParams.warningType = "";
  queryParams.warningLevel = "";
  queryParams.dateRange = [];
  loadList();
}

// 部门树过滤
watch(deptFilterText, (val) => {
  deptTreeRef.value?.filter(val);
});

function filterDeptNode(value, data) {
  if (!value) return true;
  return data.label.indexOf(value) !== -1;
}

// 用户选择器相关函数
async function loadUserPickerData() {
  userPickerLoading.value = true;
  try {
    await loadDeptTree();
    // 默认加载第一个部门的用户
    if (deptTree.value.length > 0) {
      const firstDept = deptTree.value[0];
      selectedDeptId.value = firstDept.id;
      currentDeptName.value = firstDept.label;
      await loadUserList(firstDept.id);
    }
  } finally {
    userPickerLoading.value = false;
  }
}

async function loadDeptTree() {
  const res = await deptTreeSelect();
  deptTree.value = res.data || [];
}

async function loadUserList(deptId) {
  userPickerLoading.value = true;
  try {
    const res = await listUser({ deptId, pageNum: 1, pageSize: 100 });
    userList.value = res.rows || [];
    filteredUserList.value = userList.value;
  } finally {
    userPickerLoading.value = false;
  }
}

function handleDeptClick(data) {
  selectedDeptId.value = data.id;
  currentDeptName.value = data.label;
  loadUserList(data.id);
  selectedUser.value = null;
  userFilterText.value = "";
}

function filterUserList() {
  const keyword = userFilterText.value.toLowerCase();
  if (!keyword) {
    filteredUserList.value = userList.value;
    return;
  }
  filteredUserList.value = userList.value.filter((user) => {
    const userName = (user.userName || "").toLowerCase();
    const nickName = (user.nickName || "").toLowerCase();
    const deptName = (user.deptName || "").toLowerCase();
    return userName.includes(keyword) || nickName.includes(keyword) || deptName.includes(keyword);
  });
}

function handleUserCurrentChange(row) {
  selectedUser.value = row;
}

function openUserPicker() {
  selectedUser.value = null;
  userFilterText.value = "";
  deptFilterText.value = "";
  userPickerVisible.value = true;
}

function confirmSelectUser() {
  if (!selectedUser.value) {
    ElMessage.warning("请选择用户");
    return;
  }
  formData.handler = selectedUser.value.userName;
  userPickerVisible.value = false;
}

function handleAdd() {
  isEdit.value = false;
  dialogTitle.value = "新增预警";
  resetForm();
  // 自动填充发布人为当前用户
  formData.publisher = userStore.name;
  editVisible.value = true;
}

async function handleEdit(row) {
  isEdit.value = true;
  dialogTitle.value = "编辑预警";
  resetForm();
  Object.assign(formData, { ...row });
  const detailRes = await getWarningDetailData(row.warningId);
  const detail = detailRes.data || {};
  formAttachments.value = (detail.attachmentList || []).map(normalizeExistingAttachment);
  await loadReasonOptions();
  editVisible.value = true;
}

async function submitForm() {
  await formRef.value?.validate();
  submitLoading.value = true;
  try {
    const payload = {
      warning: {
        warningId: formData.warningId,
        warningNo: formData.warningNo,
        warningName: formData.warningName,
        warningType: formData.warningType,
        warningLevel: formData.warningLevel,
        warningSpecial: formData.warningSpecial,
        location: formData.location,
        longitude: formData.longitude,
        latitude: formData.latitude,
        ownershipUnit: formData.ownershipUnit,
        publisher: formData.publisher,
        publishTime: formData.publishTime,
        handler: formData.handler,
        status: formData.status || "DRAFT",
        warningContent: formData.warningContent,
        remark: formData.remark
      },
      alarmIds: [],
      files: formAttachments.value.map((item) => item.raw).filter(Boolean)
    };
    const res = isEdit.value ? await updateYjxxData(payload) : await submitYjxxData(payload);
    if (res.code !== 200) {
      ElMessage.error(res.msg || "保存失败");
      return;
    }
    ElMessage.success(isEdit.value ? "修改成功" : "新增成功");
    editVisible.value = false;
    loadList();
  } finally {
    submitLoading.value = false;
  }
}

async function handleView(row) {
  const res = await getWarningDetailData(row.warningId);
  const detail = res.data || {};
  const basicSource = detail.basicInfo || detail;
  detailData.value = {
    ...detail,
    basicInfo: normalizeWarningRow({ ...row, ...basicSource }),
    alarmList: (detail.alarmList || []).map(normalizeAlarmRow),
    disposalHistory: (detail.disposalHistory || detail.disposalList || []).map(normalizeDisposalRow)
  };
  detailVisible.value = true;
}

async function handleDelete(row) {
  await ElMessageBox.confirm(`确认删除预警“${row.warningName}”吗？`, "提示", { type: "warning" });
  const res = await deleteYjxxData(row.warningId);
  if (res.code !== 200) {
    ElMessage.error(res.msg || "删除失败");
    return;
  }
  ElMessage.success("删除成功");
  loadList();
}

async function handlePublish(row) {
  await ElMessageBox.confirm(`确认发布预警“${row.warningName}”吗？`, "提示", { type: "warning" });
  const res = await releaseYjxxData(row.warningId);
  if (res.code !== 200) {
    ElMessage.error(res.msg || "发布失败");
    return;
  }
  ElMessage.success("发布成功");
  loadList();
}

onMounted(async () => {
  await loadDicts();
  await loadList();
});
</script>

<style scoped>
.warning-release-page {
  background: #f5f7fb;
}

.page-card {
  border-radius: 16px;
  margin-bottom: 16px;
}

.header-card {
  background: linear-gradient(135deg, #eff6ff, #f8fbff);
  border: 1px solid #dbeafe;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 16px;
}

.page-title {
  font-size: 22px;
  font-weight: 700;
  color: #1e3a8a;
}

.page-subtitle {
  margin-top: 8px;
  font-size: 13px;
  color: #64748b;
}

.header-actions {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.reason-wrap {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.reason-tag {
  cursor: pointer;
}

.attachment-panel {
  width: 100%;
}

.attachment-tip {
  margin-top: 8px;
  font-size: 12px;
  color: #64748b;
}

.attachment-list,
.detail-attachment-list {
  margin-top: 12px;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.attachment-item,
.detail-attachment-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
  padding: 10px 12px;
  border: 1px solid #e5e7eb;
  border-radius: 10px;
  background: #f8fafc;
}

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

.attachment-meta {
  font-size: 12px;
  color: #94a3b8;
  white-space: nowrap;
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
  }
}

/* 用户选择器样式 */
.user-picker-container {
  display: flex;
  gap: 16px;
  height: 460px;
}

.user-picker-left {
  width: 280px;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  padding: 12px;
  overflow-y: auto;
}

.user-picker-right {
  flex: 1;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  padding: 12px;
  overflow: hidden;
}

.picker-title {
  font-size: 14px;
  font-weight: 600;
  color: #374151;
  margin-bottom: 12px;
}

.picker-title .current-dept {
  font-weight: 400;
  color: #6b7280;
  font-size: 13px;
}
</style>
