<template>
  <div class="digger-monitor-warp">
    <div class="digger-monitor-left">
      <template v-if="currFileList?.length">
        <div class="flex items-center justify-center h-full monitor-left-top">
          <div class="file-preview-screen">
            <!-- // TODO 暂时不渲染 -->
            <img :src="currFileList?.[0]?.image_url" v-if="currFileList?.[0]?.image_url" />
            <div v-else class="w-full h-full bg-error-picture"></div>
          </div>
        </div>
      </template>
      <div class="empty-bg" v-else></div>
    </div>
    <div class="digger-monitor-right h-[100%]">
      <div class="module-header">
        <ContentHeader bgLayout="918">
          <template #title>
            <div class="w-[200px] bg_title bg_title_8"></div>
          </template>
          <template #extra>
            <div></div>
          </template>
        </ContentHeader>
      </div>
      <!-- 表格区域 -->
      <!-- 搜索区域 -->
      <div class="px-[16px]">
        <div class="digger-monitor-search-box">
          <!-- <el-select
            v-model="searchForm.station"
            placeholder="钩机编号"
            class="custom-select"
          >
            <el-option label="小觉站" value="小觉站"></el-option>
            <el-option label="东西站" value="东西站"></el-option>
            <el-option label="立杆区" value="立杆区"></el-option>
          </el-select> -->
          <el-input
            v-model="searchForm.train_number"
            placeholder="请输入列车号"
            class="custom-input"
            clearable
          />
          <el-input
            v-model="searchForm.train_carriage_number"
            placeholder="请输入车厢号"
            class="custom-input"
            clearable
          />
          <!-- <el-select
            v-model="searchForm.fault_type"
            placeholder="故障类型"
            class="custom-select"
          >
            <el-option label="下侧门板缺失" value="下侧门板缺失"></el-option>
            <el-option label="门折页座脱落" value="门折页座脱落"></el-option>
            <el-option label="小门塔扣丢失" value="小门塔扣丢失"></el-option>
            <el-option label="小窗裂纹" value="小窗裂纹"></el-option>
            <el-option label="搭扣未搭" value="搭扣未搭"></el-option>
            <el-option label="小门外胀" value="小门外胀"></el-option>
          </el-select> -->
          <el-button
            type="primary"
            @click="handleQuery"
            class="basic-btn query-btn"
          >
            <span class="icon"></span> 查询
          </el-button>
          <el-button @click="handleReset" class="basic-btn reset-btn">
            <span class="icon"></span> 重置
          </el-button>
        </div>
        <!-- 右侧表格区域 -->
        <div class="w-full right-panel">
          <div class="bg-transparent baseTable_wrap">
            <template v-if="pagination.total > 0">
              <BaseTable
                class="bg-transparent baseTable_box"
                :total="pagination.total"
                :pageSize="pagination.pageSize"
                :dataSource="listData"
                :isFixedPagination="true"
                :columns="columns"
                :page="pagination.currentPage"
                @change="handleTableChange"
                :row-class-name="handleRowClassName"
                @row-click="handleRowClick"
              >
                <template #created_at="{ row }">
                  <div>{{ row }}</div>
                </template>
              </BaseTable>
            </template>
          </div>
        </div>
      </div>
    </div>
    <DiggerAlarmModal
      v-model:value="isAlarmOpen"
      :info="currentRow"
      :fileList="currFileList"
      @close="isAlarmOpen = false"
    />
    <BaseDelete
      v-model:value="isDeleteOpen"
      :deleteContent="`
    <p>
      确定删除“
      <span>${currentRow?.alarm_type}</span>
      ”相关告警记录吗？删除后将找不到此记录，请谨慎操作.
    </p>
    `"
      @delete-confirm="handleDeleteConfirm"
      :info="currentRow"
      @close="isDeleteOpen = false"
    />
  </div>
</template>
<script lang="ts" setup>
import Player from "@/components/videoPlayer/Player.vue";
import SwiperPlayer from "./components/SwiperPlayer.vue";
import ContentHeader from "@/components/ContentHeader.vue";
import { BaseDelete, BaseTable } from "@/components/CustomTable";
import { Swiper, SwiperSlide } from "swiper/vue";
import { Navigation, Scrollbar } from "swiper/modules";
import {
  getAppearanceMonitorApi,
  getAppearanceMonitorDetailApi,
  getBeforeMonitorDetailApi,
  deleteAppearanceMonitorApi,
} from "@/api/dashboard";
import { isSuccessApi } from "@/utils/forApi";
import DiggerAlarmModal from "./components/DiggerAlarmModal.vue";
import { useWebSocketStore } from "@/stores/websocketStore";
import { onBeforeRouteLeave } from "vue-router";

import "swiper/css";
import "swiper/scss";
import "swiper/scss/navigation";
import { color } from "echarts";
const modules = [Navigation, Scrollbar];
const activeIndex = ref(-1);
const swiperRef = ref(null);
const isAlarmOpen = ref<Boolean>(false); //详情弹窗
const isDeleteOpen = ref<Boolean>(false); //删除弹窗
const websocketStore = useWebSocketStore();
// 监听 messages 的变化
watch(
  () => websocketStore.messages,
  (newMessages: string[], oldMessages: string[]) => {
    // console.log('新消息数组:', newMessages[newMessages?.length - 1].content);
    // console.log('旧消息数组:', oldMessages);
    // if (newMessages?.length > oldMessages?.length) {
    //     // 说明有新消息到来
    //     const newMessage = newMessages[newMessages?.length - 1];
    //     // console.log('接收到新的 WebSocket 消息:', newMessage);

    //     // 这里可以添加更多的处理逻辑，例如弹出提示框等
    // }
    if (newMessages?.length > 0 && !isAlarmOpen.value) {
      console.log(
        newMessages[newMessages?.length - 1],
        "newMessages[newMessages?.length - 1]"
      );
      currentRow.value = newMessages[newMessages?.length - 1];
      currFileList.value = newMessages[newMessages?.length - 1]?.images;
      isAlarmOpen.value = true;
    }
  },
  { deep: true, immediate: true }
);
const pagination = ref({ currentPage: 1, pageSize: 10, total: 0 });

const columns = [
  {
    label: "钩机编号",
    type: "index",
    index: (index: number) =>
      `No.${
        index +
        1 +
        (pagination.value.currentPage - 1) * pagination.value.pageSize
      }`,
    width: 90,
  },
  {
    label: "车号",
    property: "train_number",
    width: 185,
  },
  {
    label: "车型",
    property: "train_model",
    width: 70,
  },
  {
    label: "车厢号",
    property: "train_carriage_number",
    width: 125,
  },
  {
    label: "告警",
    property: "alarm_type",
    width: 120,
  },
  //   {
  //     label: "等级",
  //     property: "level",
  //     width: 60,
  //   },
  //   {
  //     label: "复核",
  //     property: "is_reviewed",
  //     formatter: ({ is_reviewed }) => {
  //       return is_reviewed === true ? "是" : "否";
  //     },
  //     width: 60,
  //   },
  {
    label: "时间",
    property: "created_at",
  },
  {
    slot: "operation",
    label: "操作",
    width: 140,
    formatter: (row) => {
      return h(
        "div",
        {
          style: {
            fontSize: "14px",
            color: "#37EBFF",
          },
        },
        [
          h(
            "span",
            {
              fontSize: "14px",
              class: "pf-1",
            },
            [
              h(
                "i",
                {
                  style: {
                    fontSize: "14px",
                    letterSpacing: "2px",
                    marginRight: "4px",
                    color: "#009DFF",
                  },
                  onClick: (row) => {
                    console.log("row.id");
                    // 这里可以添加按钮点击后的具体逻辑
                    isAlarmOpen.value = true;
                    console.log(isAlarmOpen.value);
                    currentRow.value = row;
                  },
                },
                "详情"
              ),
              h(
                "i",
                {
                  style: {
                    fontSize: "14px",
                    letterSpacing: "2px",
                    marginRight: "4px",
                    color: "#FF2727",
                  },
                  onClick: (row) => {
                    // console.log(row.id);
                    // 这里可以添加按钮点击后的具体逻辑
                    isDeleteOpen.value = true;
                    currentRow.value = row;
                  },
                },
                "删除"
              ),
            ]
          ),
        ]
      );
    },
  },
];

const listData = ref([]); // 列表数据
const currentRow = ref<Record<string, any>>({}); // 当前选中行
const currFileList = ref<Record<string, any>[]>([]); // 详情的文件列表
const currBeforeFileList = ref<Record<string, any>[]>([]); // 故障前详情的文件列表
const currFile = ref<Record<string, any>>({}); // 详情数据
// 搜索表单
const searchForm = reactive({
  train_number: "",
  train_carriage_number: "",
  fault_type: "",
  station: "",
  type: "distance", // TODO 接口正常时约定替换 distance
});
const dataLoading = ref(true);
// 文件详情
const getFileList = async () => {
  try {
    const res = await getAppearanceMonitorDetailApi({
      id: currentRow.value?.id,
      current: 1,
      pageSize: 1000,
    });
    console.log(res.data, "getDetailList_data");
    if (isSuccessApi(res)) {
      currFileList.value = res.data.data;
      currFile.value = res.data.data[0];
      activeIndex.value = 0;
    }
  } catch (error) {
    console.log(error, "getDetailList_error");
  }
};

// 故障前详情
const getBeforeFileList = async () => {
  try {
    const res = await getBeforeMonitorDetailApi({
      id: currentRow.value?.id,
      current: 1,
      pageSize: 1000,
    });
    console.log(res.data, "getDetailList_data");
    if (isSuccessApi(res)) {
      currBeforeFileList.value = res.data.data;
    }
  } catch (error) {
    console.log(error, "getDetailList_error");
  }
};

// TODO mock 获取视频列表数据
// const getFileList = async () => {
//   try {
//     const resAll = await fetch('/api/v1/record/record_detail_list/', {
//       method: 'POST'
//     })
//     const res = await resAll.json()
//     if (isSuccessApi(res)) {
//       currFileList.value = res.data.data;
//       currFile.value = res.data.data[0];
//       activeIndex.value = 0;
//     }
//   } catch (error) {
//     console.error('获取数据失败:', error)
//   }
// }

function loadDetail() {
  currentRow.value = listData.value[0];
  console.log(currentRow.value, "currentRow");
  getFileList();
  getBeforeFileList();
}

// 获取列表
const getList = async () => {
  try {
    const { currentPage, pageSize } = pagination.value;
    const res = await getAppearanceMonitorApi({
      ...searchForm,
      current: currentPage,
      pageSize,
    });
    console.log(res.data, "getList_data");
    if (isSuccessApi(res)) {
      listData.value = res.data.data;
      loadDetail();
      pagination.value = {
        ...pagination.value,
        total: res.data.total,
      };
    }
  } catch (error) {
    console.error("获取数据失败:", error);
  }
};

// 查询方法
const handleQuery = () => {
  getList();
};

// 重置方法
const handleReset = () => {
  searchForm.train_number = "";
  searchForm.station = "";
  searchForm.train_carriage_number = "";
  searchForm.fault_type = "";
  getList();
};

function handleTableChange(record) {
  console.log("handleTableChange_record", record);
  pagination.value = {
    ...pagination.value,
    currentPage: record.page,
    pageSize: record.pageSize,
  };
  getList();
}

// 删除操作
const handleDeleteConfirm = async (row) => {
  try {
    const res = await deleteAppearanceMonitorApi({ id: row.id });
    console.log(res, "deleteData");
    if (res.code === 200) {
      isDeleteOpen.value = false;
    }
  } catch (error) {
    console.error("获取数据失败:", error);
  }
};

// 定义行类名方法
const handleRowClassName = ({ row }) => {
  return row.id === currentRow.value.id ? "selected-row" : "";
};

// 行点击事件处理
const handleRowClick = (row, event, rowIndex) => {
  currentRow.value = row;
  getFileList();
  getBeforeFileList();
};

onBeforeRouteLeave(() => {
  isAlarmOpen.value = false;
  currentRow.value = {};
  currFileList.value = [];
});

onMounted(() => {
  getList();
});
</script>
<style lang="scss">
@import url("./DiggerMonitor.scss");
</style>
