<script setup lang="ts">
import { reactive, onMounted, ref, nextTick } from "vue";
import { useRouter } from "vue-router";
import { getStationList, removeStation } from "@/api/station";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { ElMessage, ElMessageBox } from "element-plus";
import { ExtDLabel } from "@/components/ExtForm";
import StationDialog from "./dialog.vue";
import StationUploadDialog from "./upload.vue";

defineOptions({
  name: "AdminStationList"
});

const router = useRouter();
const queryRef = ref();
const tableRef = ref();
const dialogRef = ref();
const uploadDialogRef = ref();
const qrDialogVisible = ref(false);
const currentQrCode = ref("");
const currentStationName = ref("");

const state = reactive({
  formQuery: {
    stationName: ""
  },
  pageQuery: {
    pageNum: 1,
    pageSize: 10,
    total: 0
  },
  tableData: {
    height: 500,
    data: [] as Array<any>,
    loading: false,
    columns: [
      { label: "站点名称", prop: "stationName", width: 200 },
      { label: "站点照片", prop: "pictures", width: 120 },
      { label: "站点状态", prop: "stationStatus", width: 100 },
      { label: "站点类型", prop: "stationType", width: 100 },
      { label: "地址", prop: "address", width: 250 },
      { label: "服务电话", prop: "serviceTel", width: 130 },
      { label: "营业时间", prop: "businessHours", width: 150 },
      { label: "工位数量", prop: "parkingNum", width: 90 },
      { label: "停车费用", prop: "parkingFee", width: 200 },
      { label: "停车减免二维码", prop: "parkingQrCode", width: 150 },
      { label: "创建时间", prop: "createTime", width: 160 }
    ]
  }
});

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

const loadData = (refresh: boolean = false) => {
  if (refresh) {
    state.pageQuery.pageNum = 1;
  }
  state.tableData.loading = true;
  getStationList({ ...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.stationName = "";
  loadData(true);
};

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

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

const handleAdd = () => {
  dialogRef.value?.open("add");
};

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

const handleShowQrCode = (row: any) => {
  currentQrCode.value = row.parkingQrCode;
  currentStationName.value = row.stationName;
  qrDialogVisible.value = true;
};

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

const handleGotoDevice = (row: any) => {
  router.push(`/admin/station/device?stationId=${row.stationId}`);
};
</script>

<template>
  <div class="page-container">
    <el-card shadow="hover">
      <template #header>
        <span class="card-header">站点清单</span>
      </template>
      <el-form
        ref="queryRef"
        :model="state.formQuery"
        inline
        class="search-form"
      >
        <el-form-item label="站点名称">
          <el-input
            v-model="state.formQuery.stationName"
            placeholder="请输入站点名称"
            clearable
            @keyup.enter="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-form-item>
      </el-form>

      <el-table
        ref="tableRef"
        v-loading="state.tableData.loading"
        :data="state.tableData.data"
        :height="state.tableData.height"
        border
        stripe
      >
        <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 === 'pictures'">
              <el-image
                v-if="row.pictures && row.pictures.length > 0"
                :src="row.pictures[0]"
                :preview-src-list="row.pictures"
                style="width: 60px; height: 60px"
                fit="cover"
              />
              <span v-else>-</span>
            </template>
            <template v-else-if="col.prop === 'stationStatus'">
              <ExtDLabel type="Station.status" :model-value="row.stationStatus" />
            </template>
            <template v-else-if="col.prop === 'stationType'">
              <ExtDLabel type="Station.type" :model-value="row.stationType" />
            </template>
            <template v-else-if="col.prop === 'parkingQrCode'">
              <el-button
                v-if="row.parkingQrCode"
                type="primary"
                link
                size="small"
                @click="handleShowQrCode(row)"
              >
                查看二维码
              </el-button>
              <span v-else>-</span>
            </template>
            <template v-else>
              {{ row[col.prop] }}
            </template>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link size="small" @click="handleGotoDevice(row)">
              设备清单
            </el-button>
            <el-button type="primary" link size="small" @click="handleView(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>

    <StationDialog ref="dialogRef" @refresh="loadData" />

    <StationUploadDialog ref="uploadDialogRef" @on-import-finish="loadData(true)" />

    <el-dialog
      v-model="qrDialogVisible"
      :title="`${currentStationName} - 停车减免二维码`"
      width="400px"
    >
      <div class="qr-code-container">
        <img :src="currentQrCode" alt="停车减免二维码" style="width: 100%" />
      </div>
    </el-dialog>
  </div>
</template>

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

.card-header {
  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;
  }
}

.qr-code-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
}
</style>
