<style scoped lang="scss">
.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>
<template>
  <div class="system-container layout-padding">
    <el-card shadow="hover" class="layout-padding-auto">
      <div class="page-search mb10" style="display: flex; align-items: center; gap: 10px;">
        <el-button v-auth="'rechargeConfig.add'" size="default" plain type="success" @click="handleGroupAdd">
          <SvgIcon name="ele-FolderAdd"/>
          创建分组
        </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 v-auth="'rechargeConfig.add'" size="small" type="primary" plain @click="handleItemAdd(g.group.id)">+ 配置项</el-button>
              <el-button v-auth="'rechargeConfig.remove'" 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="170">
                <template #default="{ row }">
                  {{ u.fmt.fmtMoney(row.rechargeAmount) }}
                  <el-tag v-if="row.isDefault" type="warning" size="small" effect="light" style="margin-left:4px">默认</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="赠款金额" prop="grantsAmount" width="140">
                <template #default="{ row }">
                  {{ u.fmt.fmtMoney(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="220" align="center" fixed="right">
                <template #default="{ row }">
                  <el-button v-if="!row.isDefault" v-auth="'rechargeConfig.modify'" type="primary" size="small" text @click="handleSetDefault(row)">设为默认</el-button>
                  <el-button v-auth="'rechargeConfig.modify'" type="warning" size="small" text @click="handleItemEdit(g.group.id, row)">编辑</el-button>
                  <el-button v-auth="'rechargeConfig.remove'" 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>

<script setup lang="ts" name="AdminRechargeConfig">
import { defineAsyncComponent, reactive, onMounted, ref } from 'vue';
import { $body, $get } from "/@/utils/request";
import u from '/@/utils/u'
import { Msg } from "/@/utils/message";

const GroupDialog = defineAsyncComponent(() => import("./groupDialog.vue"));
const AssignStationDialog = defineAsyncComponent(() => import("./assignStationDialog.vue"));
const ItemDialog = defineAsyncComponent(() => import("./itemDialog.vue"));

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;
  $get('/rechargeConfig/group/list').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;
  $get('/rechargeConfig/item/list', { 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) => {
  Msg.confirm('此操作将永久删除该分组及其所有配置项，是否继续?').then(() => {
    $get(`/rechargeConfig/group/remove/${group.id}`).then(() => {
      Msg.message("删除成功", 'success');
      loadData();
    }).catch(() => {
      Msg.message("删除失败", 'error');
    });
  });
};

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

const handleRemoveStation = (groupId: number, stationId: string) => {
  $body('/rechargeConfig/group/removeStation', { groupId, stationId }).then(() => {
    Msg.message("已移除", '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) => {
  Msg.confirm('此操作将永久删除该配置项，是否继续?').then(() => {
    $get(`/rechargeConfig/item/remove/${row.id}`).then(() => {
      Msg.message("删除成功", 'success');
      loadData();
    }).catch(() => {
      Msg.message("删除失败", 'error');
    });
  });
};

const handleSetDefault = (row: any) => {
  $body('/rechargeConfig/item/modify', { ...row, isDefault: true }).then(() => {
    Msg.message("已设为默认", 'success');
    loadData();
  }).catch(() => {
    Msg.message("操作失败", 'error');
  });
};
</script>
