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

defineOptions({
  name: "AdminStationList"
});

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

const state = reactive({
  formQuery: {
    stationName: "",
    stationStatus: "",
    stationType: "",
    address: ""
  },
  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 - 280;
  });
});

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 = [];
    })
    .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: "",
    stationStatus: "",
    stationType: "",
    address: ""
  };
  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 handleGotoDevice = (row: any) => {
  window.location.href = `/#/admin/station/device?stationId=${row.stationId}`;
};
</script>

<template>
  <div class="page-container">
    <el-card shadow="hover">
      <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 label="站点状态">
          <ExtDSelect
            v-model="state.formQuery.stationStatus"
            type="Station.status"
            placeholder="请选择站点状态"
            @on-change="handleSearch"
          />
        </el-form-item>
        <el-form-item label="站点类型">
          <ExtDSelect
            v-model="state.formQuery.stationType"
            type="Station.type"
            placeholder="请选择站点类型"
            @on-change="handleSearch"
          />
        </el-form-item>
        <el-form-item label="地址">
          <el-input
            v-model="state.formQuery.address"
            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-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">
                <div class="station-id">{{ row.stationId }}</div>
                <el-divider direction="horizontal" />
                <div class="station-name">{{ row.stationName }}</div>
              </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" />

    <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: 15px;
}

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

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

.station-name-cell {
  text-align: center;
  
  .station-id {
    color: var(--el-text-color-secondary);
    font-size: 12px;
  }
  
  .station-name {
    font-weight: 500;
  }
  
  .el-divider {
    margin: 4px 0;
  }
}

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