<script setup lang="ts">
import { reactive, onMounted, ref, nextTick, onBeforeUnmount } from "vue";
import { getSubscriberList, generateQrcode, unsubscribe, getFaultRecords } from "@/api/fault-subscriber";
import { getStationList } from "@/api/station";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { ElMessage, ElMessageBox } from "element-plus";

defineOptions({ name: "AdminStationFault" });

const state = reactive({
  activeTab: "subscriber",
  tableHeight: 400,
  // 订阅管理
  formQuery: {
    stationId: "" as string
  },
  stationOptions: [] as Array<{ stationId: string; stationName: string }>,
  subscriberData: [] as Array<any>,
  subscriberLoading: false,
  // 故障记录
  faultQuery: {
    stationId: "" as string,
    faultType: "" as string,
    isRecovered: null as number | null
  },
  faultRecordData: [] as Array<any>,
  faultRecordLoading: false,
  faultPageQuery: {
    pageNum: 1,
    pageSize: 10,
    total: 0
  },
  // 二维码弹窗
  qrcodeDialogVisible: false,
  qrcodeUrl: "",
  currentStationId: ""
});

const faultTypeLabel = (type: string) => {
  switch (type) {
    case "offline": return "设备离线";
    case "water_shortage": return "缺水";
    case "foam_shortage": return "缺泡沫";
    default: return type;
  }
};

onMounted(() => {
  loadStations();
  nextTick(() => {
    const bodyHeight = document.body.clientHeight;
    state.tableHeight = bodyHeight - 280;
  });
});

const loadStations = () => {
  getStationList({ pageNum: 1, pageSize: 200 }).then((res: any) => {
    state.stationOptions = res?.list || res?.records || [];
  }).catch(() => {});
};

const handleTabClick = () => {
  if (state.activeTab === "faultRecord") {
    loadFaultRecords(true);
  }
};

// ============ 订阅管理 ============

const loadSubscribers = () => {
  if (!state.formQuery.stationId) {
    state.subscriberData = [];
    return;
  }
  state.subscriberLoading = true;
  getSubscriberList({ stationId: state.formQuery.stationId })
    .then((res: any) => {
      state.subscriberData = res?.data || res || [];
    })
    .catch(() => {
      state.subscriberData = [];
    })
    .finally(() => {
      state.subscriberLoading = false;
    });
};

const handleGenerateQrcode = () => {
  if (!state.formQuery.stationId) {
    ElMessage.warning("请先选择站点");
    return;
  }
  const loading = ElMessage({ message: "生成中...", type: "info", duration: 0 });
  generateQrcode({ stationId: state.formQuery.stationId })
    .then((res: any) => {
      loading.close();
      const data = res?.data || res;
      state.qrcodeUrl = data.url || data;
      state.currentStationId = state.formQuery.stationId;
      state.qrcodeDialogVisible = true;
    })
    .catch(() => {
      loading.close();
      ElMessage.error("生成二维码失败");
    });
};

const handleUnsubscribe = (row: any) => {
  ElMessageBox.confirm(
    `确定要解绑 ${row.openid} 吗？解绑后该用户将不再接收故障通知。`,
    "解绑确认",
    { confirmButtonText: "确定", cancelButtonText: "取消", type: "warning" }
  ).then(() => {
    unsubscribe({ openid: row.openid, stationId: row.stationId })
      .then(() => {
        ElMessage.success("解绑成功");
        loadSubscribers();
      })
      .catch(() => {
        ElMessage.error("解绑失败");
      });
  }).catch(() => {});
};

// ============ 故障记录 ============

const loadFaultRecords = (refresh: boolean = false) => {
  if (refresh) {
    state.faultPageQuery.pageNum = 1;
  }
  state.faultRecordLoading = true;
  const params: any = { ...state.faultPageQuery };
  if (state.faultQuery.stationId) params.stationId = state.faultQuery.stationId;
  if (state.faultQuery.faultType) params.faultType = state.faultQuery.faultType;
  if (state.faultQuery.isRecovered !== null && state.faultQuery.isRecovered !== undefined) {
    params.isRecovered = state.faultQuery.isRecovered;
  }

  getFaultRecords(params)
    .then((res: any) => {
      const data = res?.data || res || [];
      if (Array.isArray(data)) {
        state.faultRecordData = data;
        state.faultPageQuery.total = data.length;
      } else if (data.list) {
        state.faultRecordData = data.list;
        state.faultPageQuery.total = data.total || 0;
      } else {
        state.faultRecordData = data;
      }
    })
    .catch(() => {
      state.faultRecordData = [];
    })
    .finally(() => {
      state.faultRecordLoading = false;
    });
};

const handleFaultSizeChange = (size: number) => {
  state.faultPageQuery.pageSize = size;
  loadFaultRecords(true);
};

const handleFaultCurrentChange = (page: number) => {
  state.faultPageQuery.pageNum = page;
  loadFaultRecords();
};

const handleFaultSearch = () => loadFaultRecords(true);

const handleFaultReset = () => {
  state.faultQuery = { stationId: "", faultType: "", isRecovered: null };
  loadFaultRecords(true);
};

const formatTime = (value: string) => {
  if (!value) return "-";
  return value;
};
</script>

<template>
  <div class="page-container">
    <el-card shadow="hover">
      <el-tabs v-model="state.activeTab" @tab-click="handleTabClick">
        <!-- 订阅管理 -->
        <el-tab-pane label="订阅管理" name="subscriber">
          <el-form :model="state.formQuery" inline class="search-form">
            <el-form-item label="站点">
              <el-select
                v-model="state.formQuery.stationId"
                placeholder="请选择站点"
                clearable
                style="width: 220px"
                @change="loadSubscribers"
              >
                <el-option
                  v-for="item in state.stationOptions"
                  :key="item.stationId"
                  :label="item.stationName"
                  :value="item.stationId"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                :icon="useRenderIcon('ri/search-line')"
                @click="loadSubscribers"
              >
                查询
              </el-button>
              <el-button
                v-if="state.formQuery.stationId"
                type="success"
                :icon="useRenderIcon('ri/qr-code-line')"
                @click="handleGenerateQrcode"
              >
                生成绑定二维码
              </el-button>
            </el-form-item>
          </el-form>

          <el-table
            v-loading="state.subscriberLoading"
            :data="state.subscriberData"
            :height="state.tableHeight"
            border
            stripe
          >
            <template #empty>
              <el-empty description="请选择站点后查询" />
            </template>
            <el-table-column label="OpenID" prop="openid" width="260" show-overflow-tooltip />
            <el-table-column label="昵称" prop="nickname" width="150" />
            <el-table-column label="站点" prop="stationName" width="120" />
            <el-table-column label="绑定时间" prop="subscribeTime" width="170">
              <template #default="{ row }">{{ formatTime(row.subscribeTime) }}</template>
            </el-table-column>
            <el-table-column label="状态" prop="status" width="90">
              <template #default="{ row }">
                <el-tag :type="row.status === 1 ? 'success' : 'info'" size="small">
                  {{ row.status === 1 ? "已订阅" : "已解绑" }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100" align="center" fixed="right">
              <template #default="{ row }">
                <el-button v-if="row.status === 1" type="danger" link size="small" @click="handleUnsubscribe(row)">
                  解绑
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <!-- 故障记录 -->
        <el-tab-pane label="故障记录" name="faultRecord">
          <el-form :model="state.faultQuery" inline class="search-form">
            <el-form-item label="站点">
              <el-select
                v-model="state.faultQuery.stationId"
                placeholder="站点（可选）"
                clearable
                style="width: 200px"
              >
                <el-option
                  v-for="item in state.stationOptions"
                  :key="item.stationId"
                  :label="item.stationName"
                  :value="item.stationId"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="故障类型">
              <el-select
                v-model="state.faultQuery.faultType"
                placeholder="故障类型"
                clearable
                style="width: 150px"
              >
                <el-option label="设备离线" value="offline" />
                <el-option label="缺水" value="water_shortage" />
                <el-option label="缺泡沫" value="foam_shortage" />
              </el-select>
            </el-form-item>
            <el-form-item label="恢复状态">
              <el-select
                v-model="state.faultQuery.isRecovered"
                placeholder="恢复状态"
                clearable
                style="width: 150px"
              >
                <el-option label="未恢复" :value="0" />
                <el-option label="已恢复" :value="1" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                :icon="useRenderIcon('ri/search-line')"
                @click="handleFaultSearch"
              >
                查询
              </el-button>
              <el-button
                :icon="useRenderIcon('ri/refresh-line')"
                @click="handleFaultReset"
              >
                重置
              </el-button>
            </el-form-item>
          </el-form>

          <el-table
            v-loading="state.faultRecordLoading"
            :data="state.faultRecordData"
            :height="state.tableHeight"
            border
            stripe
          >
            <template #empty>
              <el-empty description="暂无故障记录" />
            </template>
            <el-table-column label="站点" prop="stationId" width="100" />
            <el-table-column label="设备" prop="deviceName" width="150" />
            <el-table-column label="故障类型" prop="faultType" width="110">
              <template #default="{ row }">
                <el-tag
                  :type="row.faultType === 'offline' ? 'danger' : 'warning'"
                  size="small"
                >
                  {{ faultTypeLabel(row.faultType) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="故障时间" prop="faultTime" width="170">
              <template #default="{ row }">{{ formatTime(row.faultTime) }}</template>
            </el-table-column>
            <el-table-column label="是否通知" prop="isNotified" width="90">
              <template #default="{ row }">
                <el-tag :type="row.isNotified === 1 ? 'success' : 'warning'" size="small">
                  {{ row.isNotified === 1 ? "已通知" : "未通知" }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="通知时间" prop="notifyTime" width="170">
              <template #default="{ row }">{{ row.notifyTime ? formatTime(row.notifyTime) : "-" }}</template>
            </el-table-column>
            <el-table-column label="是否恢复" prop="isRecovered" width="90">
              <template #default="{ row }">
                <el-tag :type="row.isRecovered === 1 ? 'success' : 'danger'" size="small">
                  {{ row.isRecovered === 1 ? "已恢复" : "未恢复" }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="恢复时间" prop="recoverTime" width="170">
              <template #default="{ row }">{{ row.recoverTime ? formatTime(row.recoverTime) : "-" }}</template>
            </el-table-column>
          </el-table>

          <div class="pagination-container">
            <el-pagination
              v-model:current-page="state.faultPageQuery.pageNum"
              v-model:page-size="state.faultPageQuery.pageSize"
              :total="state.faultPageQuery.total"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleFaultSizeChange"
              @current-change="handleFaultCurrentChange"
            />
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 二维码弹窗 -->
    <el-dialog v-model="state.qrcodeDialogVisible" title="故障通知绑定二维码" width="420px" center>
      <div style="text-align: center">
        <img v-if="state.qrcodeUrl" :src="state.qrcodeUrl" style="width: 260px; height: 260px; margin: 20px auto; display: block; border: 1px solid #eee;" alt="绑定二维码" />
        <div style="text-align: center; color: #999; font-size: 13px; margin-top: 10px;">
          请使用微信扫描二维码<br />
          扫描后关注公众号即可绑定，再次扫描可解绑<br />
          站点：{{ state.currentStationId }}
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.page-container {
  padding: 20px;
}

.search-form {
  margin-bottom: 16px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>
