<script setup lang="ts">
import { reactive, onMounted, ref, nextTick, watch } from "vue";
import { getStationDeviceList, removeDevice, getStationList } from "@/api/station";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { useRoute, useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { ExtDLabel, ExtDSelect } from "@/components/ExtForm";
import DeviceDialog from "./device-dialog.vue";
import DeviceUploadDialog from "./device-upload.vue";
import DeviceConfigDialog from "./device-config.vue";
import DeviceRemoteDialog from "./device-remote.vue";

defineOptions({
  name: "AdminStationDevice"
});

const route = useRoute();
const router = useRouter();
const queryRef = ref();
const tableRef = ref();
const dialogRef = ref();
const uploadDialogRef = ref();
const configDialogRef = ref();
const remoteDialogRef = ref();

const state = reactive({
  stationId: (route.query.stationId as string) || "",
  stationOptions: [] as Array<{ stationId: string; stationName: string }>,
  chooseDeviceList: [] as number[],
  formQuery: {
    stationId: "",
    shortId: "",
    deviceConfigName: "",
    productKey: "",
    deviceName: "",
    state: "",
    hasFoam: "",
    hasWater: ""
  },
  pageQuery: {
    pageNum: 1,
    pageSize: 10,
    total: 0
  },
  tableData: {
    height: 500,
    data: [] as Array<any>,
    loading: false,
    columns: [
      { label: "设备编号", prop: "shortId", width: 100 },
      { label: "站点名称", prop: "stationName", width: 180 },
      { label: "设备配置名", prop: "deviceConfigName", width: 120 },
      { label: "ProductKey", prop: "productKey", width: 180 },
      { label: "DeviceName", prop: "deviceName", width: 180 },
      { label: "状态", prop: "state", width: 90 },
      { label: "运行时长", prop: "uptimeMs", width: 120 },
      { label: "功能", prop: "functions", width: 180 },
      { label: "是否有泡沫", prop: "hasFoam", width: 100 },
      { label: "是否有水", prop: "hasWater", width: 100 },
      { label: "创建时间", prop: "createTime", width: 160 },
      { label: "更新时间", prop: "updateTime", width: 160 }
    ]
  }
});

watch(
  () => route.query.stationId,
  (newStationId) => {
    if (newStationId) {
      state.stationId = newStationId as string;
      state.formQuery.stationId = newStationId as string;
      loadData(true);
    }
  }
);

onMounted(() => {
  loadStationOptions();
  if (state.stationId) {
    state.formQuery.stationId = state.stationId;
  }
  loadData();
  nextTick(() => {
    const bodyHeight = document.body.clientHeight;
    const queryHeight = queryRef.value?.$el?.clientHeight || 0;
    state.tableData.height = bodyHeight - queryHeight - 280;
  });
});

const loadStationOptions = () => {
  getStationList({ pageSize: 1000 }).then((res: any) => {
    const { list } = res || {};
    state.stationOptions = list || [];
  });
};

const loadData = (refresh: boolean = false) => {
  if (refresh) {
    state.pageQuery.pageNum = 1;
  }
  state.tableData.loading = true;
  getStationDeviceList({
    ...state.formQuery,
    ...state.pageQuery
  })
    .then((res: any) => {
      const { list, total } = res || {};
      state.tableData.data = list || [];
      state.pageQuery.total = total || 0;
    })
    .catch(() => {
      state.tableData.data = [];
      ElMessage.error("加载设备列表失败");
    })
    .finally(() => {
      state.tableData.loading = false;
    });
};

const handleSizeChange = (size: number) => {
  state.pageQuery.pageSize = size;
  loadData(true);
};

const handleCurrentChange = (page: number) => {
  state.pageQuery.pageNum = page;
  loadData();
};

const handleSearch = () => {
  loadData(true);
};

const handleReset = () => {
  state.formQuery = {
    stationId: state.stationId || "",
    shortId: "",
    deviceConfigName: "",
    productKey: "",
    deviceName: "",
    state: "",
    hasFoam: "",
    hasWater: ""
  };
  loadData(true);
};

const handleBack = () => {
  router.push("/admin/station/list");
};

const handleAdd = () => {
  dialogRef.value?.open("add", { stationId: state.formQuery.stationId });
};

const handleEdit = (row: any) => {
  dialogRef.value?.open("edit", row);
};

const handleDelete = (row: any) => {
  ElMessageBox.confirm(`此操作将永久删除设备『${row.shortId}』，是否继续?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    removeDevice(row.id)
      .then(() => {
        ElMessage.success("删除成功");
        loadData(true);
      })
      .catch(() => {
        ElMessage.error("删除失败，请稍后重试");
      });
  });
};

const formatDuration = (ms: number) => {
  if (!ms) return "-";
  const seconds = Math.floor(ms / 1000);
  const days = Math.floor(seconds / 86400);
  const hours = Math.floor((seconds % 86400) / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);
  const secs = seconds % 60;

  const parts = [];
  if (days > 0) parts.push(`${days}天`);
  if (hours > 0) parts.push(`${hours}时`);
  if (minutes > 0) parts.push(`${minutes}分`);
  if (secs > 0 || parts.length === 0) parts.push(`${secs}秒`);

  return parts.join("");
};

const handleSelectionChange = (selection: any[]) => {
  state.chooseDeviceList = selection.map((k: any) => k.id);
};

const handleUpload = () => {
  uploadDialogRef.value?.open();
};

const handleBatchConfig = () => {
  if (state.chooseDeviceList.length === 0) {
    ElMessage.warning("请先选择要配置的设备");
    return;
  }
  configDialogRef.value?.open(state.chooseDeviceList);
};

const handleRemoteControl = (row: any) => {
  const canRemote = !["sleep", "maintenance", "fault"].includes(row.state);
  if (!canRemote) {
    ElMessage.warning("当前设备状态不支持远程控制");
    return;
  }
  remoteDialogRef.value?.open(row);
};
</script>

<template>
  <div class="page-container">
    <el-card shadow="hover">
      <template #header>
        <div class="card-header">
          <span>设备清单</span>
          <el-button :icon="useRenderIcon('ri/arrow-left-line')" @click="handleBack">
            返回站点列表
          </el-button>
        </div>
      </template>

      <el-form
        ref="queryRef"
        :model="state.formQuery"
        inline
        class="search-form"
      >
        <el-form-item label="站点">
          <el-select
            v-model="state.formQuery.stationId"
            placeholder="请选择站点"
            clearable
            filterable
            @change="handleSearch"
          >
            <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-input
            v-model="state.formQuery.shortId"
            placeholder="请输入设备编号"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="设备配置名">
          <el-input
            v-model="state.formQuery.deviceConfigName"
            placeholder="请输入设备配置名"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="状态">
          <ExtDSelect
            v-model="state.formQuery.state"
            type="Device.state"
            placeholder="请选择状态"
            @on-change="handleSearch"
          />
        </el-form-item>
        <el-form-item label="是否有泡沫">
          <ExtDSelect
            v-model="state.formQuery.hasFoam"
            type="YesNo"
            placeholder="请选择"
            @on-change="handleSearch"
          />
        </el-form-item>
        <el-form-item label="是否有水">
          <ExtDSelect
            v-model="state.formQuery.hasWater"
            type="YesNo"
            placeholder="请选择"
            @on-change="handleSearch"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            :icon="useRenderIcon('ri/search-line')"
            @click="handleSearch"
          >
            查询
          </el-button>
          <el-button
            :icon="useRenderIcon('ri/refresh-line')"
            @click="handleReset"
          >
            重置
          </el-button>
          <el-button
            type="success"
            :icon="useRenderIcon('ri/add-line')"
            @click="handleAdd"
          >
            新增
          </el-button>
          <el-button
            type="warning"
            :icon="useRenderIcon('ri/upload-line')"
            @click="handleUpload"
          >
            导入
          </el-button>
          <el-button
            type="primary"
            :icon="useRenderIcon('ri/settings-3-line')"
            @click="handleBatchConfig"
            :disabled="state.chooseDeviceList.length === 0"
          >
            批量配置
          </el-button>
        </el-form-item>
      </el-form>

      <el-table
        ref="tableRef"
        v-loading="state.tableData.loading"
        :data="state.tableData.data"
        :height="state.tableData.height"
        border
        stripe
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" />
        <template #empty>
          <el-empty description="暂无设备数据，点击「新增」按钮添加设备" />
        </template>
        <el-table-column
          v-for="col in state.tableData.columns"
          :key="col.prop"
          :prop="col.prop"
          :label="col.label"
          :width="col.width"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            <template v-if="col.prop === 'stationName'">
              <div class="station-name-cell">
                <span class="station-id">{{ row.stationId }}</span>
                <span class="station-divider"></span>
                <span class="station-name">{{ row.stationName }}</span>
              </div>
            </template>
            <template v-else-if="col.prop === 'state'">
              <ExtDLabel type="Device.state" :model-value="row.state" />
            </template>
            <template v-else-if="col.prop === 'uptimeMs'">
              {{ formatDuration(row.uptimeMs) }}
            </template>
            <template v-else-if="col.prop === 'hasFoam' || col.prop === 'hasWater'">
              <ExtDLabel type="YesNo" :model-value="row[col.prop]" />
            </template>
            <template v-else>
              {{ row[col.prop] }}
            </template>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="240" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link size="small" @click="handleRemoteControl(row)">
              远程控制
            </el-button>
            <el-button type="warning" link size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="danger" link size="small" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

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

    <DeviceDialog ref="dialogRef" @refresh="loadData(true)" />
    <DeviceUploadDialog ref="uploadDialogRef" @on-import-finish="loadData(true)" />
    <DeviceConfigDialog ref="configDialogRef" @refresh="loadData(true)" />
    <DeviceRemoteDialog ref="remoteDialogRef" @refresh="loadData(true)" />
  </div>
</template>

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

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 16px;
  font-weight: 600;
}

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

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

.station-name-cell {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;

  .station-id {
    color: var(--el-text-color-secondary);
    font-size: 12px;
  }

  .station-divider {
    display: block;
    width: 40px;
    height: 1px;
    background: var(--el-border-color-light);
  }

  .station-name {
    font-weight: 500;
  }
}
</style>
