<script setup lang="ts">
import { reactive, onMounted, ref } from "vue";
import {
  getRechargeConfigGroupList,
  removeRechargeConfigGroup,
  getRechargeConfigItemList,
  removeRechargeConfigItem,
  removeStationFromGroup
} from "@/api/platform";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { ElMessage, ElMessageBox } from "element-plus";
import GroupDialog from "./recharge-config-group-dialog.vue";
import AssignStationDialog from "./recharge-config-assign-dialog.vue";
import ItemDialog from "./recharge-config-item-dialog.vue";

defineOptions({ name: "AdminRechargeConfig" });

const groupDialogRef = ref();
const assignStationDialogRef = ref();
const itemDialogRef = ref();

interface GroupRow {
  group: any;
  stationIds: string[];
  items: any[];
  itemsLoading: boolean;
}

const state = reactive({
  loading: false,
  groups: [] as GroupRow[]
});

onMounted(() => {
  loadData();
});

const loadData = () => {
  state.loading = true;
  getRechargeConfigGroupList()
    .then((groups: any) => {
      state.groups = (groups || []).map((g: any) => ({
        group: g.group,
        stationIds: g.stationIds || [],
        items: [],
        itemsLoading: false
      }));
      state.groups.forEach(g => loadItems(g));
      state.loading = false;
    })
    .catch(() => {
      state.loading = false;
    });
};

const loadItems = (g: GroupRow) => {
  g.itemsLoading = true;
  getRechargeConfigItemList({ groupId: g.group.id })
    .then((items: any) => {
      g.items = items || [];
      g.itemsLoading = false;
    })
    .catch(() => {
      g.itemsLoading = false;
    });
};

const handleGroupAdd = () => {
  groupDialogRef.value.open("add", null);
};

const handleGroupRemove = (group: any) => {
  ElMessageBox.confirm("此操作将永久删除该分组及其所有配置项，是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    removeRechargeConfigGroup(group.id)
      .then(() => {
        ElMessage.success("删除成功");
        loadData();
      })
      .catch(() => {
        ElMessage.error("删除失败");
      });
  });
};

const handleAssignStation = (groupId: number) => {
  assignStationDialogRef.value.open(groupId);
};

const handleRemoveStation = (groupId: number, stationId: string) => {
  removeStationFromGroup({ groupId, stationId })
    .then(() => {
      ElMessage.success("已移除");
      loadData();
    });
};

const handleItemAdd = (groupId: number) => {
  itemDialogRef.value.open("add", { groupId });
};

const handleItemEdit = (groupId: number, row: any) => {
  itemDialogRef.value.open("edit", { ...row, groupId });
};

const handleItemRemove = (row: any) => {
  ElMessageBox.confirm("此操作将永久删除该配置项，是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    removeRechargeConfigItem(row.id)
      .then(() => {
        ElMessage.success("删除成功");
        loadData();
      })
      .catch(() => {
        ElMessage.error("删除失败");
      });
  });
};

const formatMoney = (fen: number) => {
  if (fen == null) return "-";
  return `¥${(fen / 100).toFixed(2)}`;
};
</script>

<template>
  <div class="page-container">
    <el-card shadow="hover">
      <template #header>
        <span class="card-header">充值配置</span>
      </template>
      <div class="page-header mb10">
        <el-button size="default" type="success" :icon="useRenderIcon('ri/folder-add-line')" @click="handleGroupAdd">
          创建分组
        </el-button>
      </div>

      <div v-loading="state.loading">
        <el-empty v-if="!state.loading && state.groups.length === 0" description="暂无充值配置分组" />

        <div v-for="g in state.groups" :key="g.group.id" class="group-card">
          <div class="group-header">
            <div class="group-info">
              <span class="group-title">
                <el-tag v-if="g.group.isDefault" type="danger" effect="light">默认</el-tag>
                {{ g.group.name || (g.group.isDefault ? '平台默认配置' : '未命名分组') }}
              </span>
              <div class="station-tags">
                <el-tag
                  v-for="sid in g.stationIds"
                  :key="sid"
                  type="success"
                  size="small"
                  closable
                  @close="handleRemoveStation(g.group.id, sid)"
                >
                  {{ sid }}
                </el-tag>
                <el-button size="small" text type="primary" @click="handleAssignStation(g.group.id)">
                  + 关联站点
                </el-button>
              </div>
            </div>
            <div class="group-actions">
              <el-button size="small" type="primary" plain @click="handleItemAdd(g.group.id)">
                + 配置项
              </el-button>
              <el-button size="small" type="danger" plain @click="handleGroupRemove(g.group)">
                删除
              </el-button>
            </div>
          </div>
          <div class="item-table-wrap">
            <el-table border :data="g.items" size="small" v-loading="g.itemsLoading">
              <template #empty>
                <el-empty :image-size="40" description="暂无配置项" />
              </template>
              <el-table-column label="充值金额" prop="rechargeAmount" width="140">
                <template #default="{ row }">
                  {{ formatMoney(row.rechargeAmount) }}
                </template>
              </el-table-column>
              <el-table-column label="赠款金额" prop="grantsAmount" width="140">
                <template #default="{ row }">
                  {{ formatMoney(row.grantsAmount) }}
                </template>
              </el-table-column>
              <el-table-column label="标签" prop="label" min-width="120">
                <template #default="{ row }">
                  {{ row.label || '-' }}
                </template>
              </el-table-column>
              <el-table-column label="操作" prop="action" width="160" align="center" fixed="right">
                <template #default="{ row }">
                  <el-button type="warning" size="small" text @click="handleItemEdit(g.group.id, row)">
                    编辑
                  </el-button>
                  <el-button type="danger" size="small" text @click="handleItemRemove(row)">
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>
    </el-card>
  </div>

  <GroupDialog ref="groupDialogRef" @refresh="loadData" />
  <AssignStationDialog ref="assignStationDialogRef" @refresh="loadData" />
  <ItemDialog ref="itemDialogRef" @refresh="loadData" />
</template>

<style scoped lang="scss">
.card-header { font-size: 16px; font-weight: 600; }

.page-container {
  padding: 15px;
}

.page-header {
  display: flex;
  align-items: center;
  gap: 10px;
}

.group-card {
  margin-bottom: 16px;

  .group-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 12px 16px;
    background-color: var(--el-fill-color-light);
    border-radius: 6px 6px 0 0;
    border: 1px solid var(--el-border-color-light);
    border-bottom: none;

    .group-info {
      display: flex;
      align-items: center;
      gap: 12px;

      .group-title {
        font-weight: 600;
        font-size: 15px;
      }
    }

    .group-actions {
      display: flex;
      gap: 8px;
    }
  }

  .item-table-wrap {
    border: 1px solid var(--el-border-color-light);
    border-top: none;
    border-radius: 0 0 6px 6px;
    padding: 0;
  }
}

.station-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  margin-top: 4px;
}
</style>
