2 Commits

Author SHA1 Message Date
c602c0d67d 游戏-游戏配置-优化样式 2026-04-02 11:06:21 +08:00
9786dab979 修复框架权限鉴权报错 2026-04-02 11:04:57 +08:00
12 changed files with 1041 additions and 868 deletions

View File

@@ -0,0 +1,278 @@
<?php
namespace app\admin\controller\game;
use Throwable;
use app\common\controller\Backend;
use support\Response;
use Webman\Http\Request as WebmanRequest;
/**
* 游戏配置
*/
class Config extends Backend
{
/**
* GameConfig模型对象
* @var object|null
* @phpstan-var \app\common\model\GameConfig|null
*/
protected ?object $model = null;
protected string|array $defaultSortField = 'group,desc';
protected array $withJoinTable = ['channel'];
protected array|string $preExcludeFields = ['create_time', 'update_time'];
protected string|array $quickSearchField = ['ID'];
/** 权重之和必须为 100 的配置标识 */
private const WEIGHT_SUM_100_NAMES = ['default_tier_weight', 'default_kill_score_weight'];
protected function initController(WebmanRequest $request): ?Response
{
$this->model = new \app\common\model\GameConfig();
return null;
}
/**
* @throws Throwable
*/
protected function _add(): Response
{
if ($this->request && $this->request->method() === 'POST') {
$data = $this->request->post();
if (!$data) {
return $this->error(__('Parameter %s can not be empty', ['']));
}
$data = $this->applyInputFilter($data);
$data = $this->excludeFields($data);
$err = $this->validateGameWeightPayload($data, null);
if ($err !== null) {
return $this->error($err);
}
if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
$data[$this->dataLimitField] = $this->auth->id;
}
$result = false;
$this->model->startTrans();
try {
if ($this->modelValidate) {
$validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
if (class_exists($validate)) {
$validate = new $validate();
if ($this->modelSceneValidate) {
$validate->scene('add');
}
$validate->check($data);
}
}
$result = $this->model->save($data);
$this->model->commit();
} catch (Throwable $e) {
$this->model->rollback();
return $this->error($e->getMessage());
}
if ($result !== false) {
return $this->success(__('Added successfully'));
}
return $this->error(__('No rows were added'));
}
return $this->error(__('Parameter error'));
}
/**
* @throws Throwable
*/
protected function _edit(): Response
{
$pk = $this->model->getPk();
$id = $this->request ? ($this->request->post($pk) ?? $this->request->get($pk)) : null;
$row = $this->model->find($id);
if (!$row) {
return $this->error(__('Record not found'));
}
$dataLimitAdminIds = $this->getDataLimitAdminIds();
if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
return $this->error(__('You have no permission'));
}
if ($this->request && $this->request->method() === 'POST') {
$data = $this->request->post();
if (!$data) {
return $this->error(__('Parameter %s can not be empty', ['']));
}
$data = $this->applyInputFilter($data);
$data = $this->excludeFields($data);
if (!$this->auth->isSuperAdmin()) {
$data['channel_id'] = $row['channel_id'];
$data['group'] = $row['group'];
$data['name'] = $row['name'];
$data['title'] = $row['title'];
}
$err = $this->validateGameWeightPayload($data, $row['value'] ?? null);
if ($err !== null) {
return $this->error($err);
}
$result = false;
$this->model->startTrans();
try {
if ($this->modelValidate) {
$validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
if (class_exists($validate)) {
$validate = new $validate();
if ($this->modelSceneValidate) {
$validate->scene('edit');
}
$data[$pk] = $row[$pk];
$validate->check($data);
}
}
$result = $row->save($data);
$this->model->commit();
} catch (Throwable $e) {
$this->model->rollback();
return $this->error($e->getMessage());
}
if ($result !== false) {
return $this->success(__('Update successful'));
}
return $this->error(__('No rows updated'));
}
return $this->success('', [
'row' => $row
]);
}
/**
* game_weight校验数值、键不可改编辑、和为 100特定 name
*
* @param array<string, mixed> $data
*/
private function validateGameWeightPayload(array $data, ?string $originalValue): ?string
{
$group = $data['group'] ?? '';
if ($group !== 'game_weight') {
return null;
}
$name = $data['name'] ?? '';
$value = $data['value'] ?? '';
if (!is_string($value)) {
return __('Parameter error');
}
$decoded = json_decode($value, true);
if (!is_array($decoded)) {
return __('Parameter error');
}
$keys = [];
$numbers = [];
foreach ($decoded as $item) {
if (!is_array($item)) {
return __('Parameter error');
}
foreach ($item as $k => $v) {
$keys[] = $k;
if (!is_numeric($v)) {
return __('Game config weight value must be numeric');
}
$num = (float) $v;
if ($num > 100) {
return __('Game config weight each value must not exceed 100');
}
$numbers[] = $num;
}
}
if (count($numbers) === 0) {
return __('Parameter %s can not be empty', ['value']);
}
if ($originalValue !== null && $originalValue !== '') {
$oldKeys = $this->extractGameWeightKeys($originalValue);
if ($oldKeys !== $keys) {
return __('Game config weight keys cannot be modified');
}
}
if (in_array($name, self::WEIGHT_SUM_100_NAMES, true)) {
$sum = array_sum($numbers);
if (abs($sum - 100.0) > 0.000001) {
return __('Game config weight sum must equal 100');
}
}
return null;
}
/**
* @return list<string>
*/
private function extractGameWeightKeys(string $value): array
{
$decoded = json_decode($value, true);
if (!is_array($decoded)) {
return [];
}
$keys = [];
foreach ($decoded as $item) {
if (!is_array($item)) {
continue;
}
foreach ($item as $k => $_) {
$keys[] = $k;
}
}
return $keys;
}
/**
* 查看
* @throws Throwable
*/
protected function _index(): Response
{
// 如果是 select 则转发到 select 方法,若未重写该方法,其实还是继续执行 index
if ($this->request && $this->request->get('select')) {
return $this->select($this->request);
}
/**
* 1. withJoin 不可使用 alias 方法设置表别名,别名将自动使用关联模型名称(小写下划线命名规则)
* 2. 以下的别名设置了主表别名,同时便于拼接查询参数等
* 3. paginate 数据集可使用链式操作 each(function($item, $key) {}) 遍历处理
*/
list($where, $alias, $limit, $order) = $this->queryBuilder();
$res = $this->model
->withJoin($this->withJoinTable, $this->withJoinType)
->with($this->withJoinTable)
->visible(['channel' => ['name']])
->alias($alias)
->where($where)
->order($order)
->paginate($limit);
return $this->success('', [
'list' => $res->items(),
'total' => $res->total(),
'remark' => get_route_remark(),
]);
}
/**
* 若需重写查看、编辑、删除等方法,请复制 @see \app\admin\library\traits\Backend 中对应方法至此进行重写
*/
}

View File

@@ -95,4 +95,8 @@ return [
'%d records and files have been deleted' => '%d records and files have been deleted',
'Please input correct username' => 'Please enter the correct username',
'Group Name Arr' => 'Group Name Arr',
'Game config weight keys cannot be modified' => 'Weight config keys cannot be modified',
'Game config weight value must be numeric' => 'Weight values must be numeric',
'Game config weight each value must not exceed 100' => 'Each weight value must not exceed 100',
'Game config weight sum must equal 100' => 'The sum of weights for default_tier_weight / default_kill_score_weight must equal 100',
];

View File

@@ -114,4 +114,8 @@ return [
'%d records and files have been deleted' => '已删除%d条记录和文件',
'Please input correct username' => '请输入正确的用户名',
'Group Name Arr' => '分组名称数组',
'Game config weight keys cannot be modified' => '权重配置的键不可修改',
'Game config weight value must be numeric' => '权重值必须为数字',
'Game config weight each value must not exceed 100' => '每项权重不能超过100',
'Game config weight sum must equal 100' => 'default_tier_weight / default_kill_score_weight 的权重之和必须等于100',
];

View File

@@ -0,0 +1,32 @@
<?php
namespace app\common\model;
use support\think\Model;
/**
* GameConfig
*/
class GameConfig extends Model
{
// 表主键
protected $pk = 'ID';
// 表名
protected $name = 'game_config';
// 自动写入时间戳字段
protected $autoWriteTimestamp = true;
// 字段类型转换
protected $type = [
'create_time' => 'integer',
'update_time' => 'integer',
];
public function channel(): \think\model\relation\BelongsTo
{
return $this->belongsTo(\app\common\model\GameChannel::class, 'channel_id', 'id');
}
}

View File

@@ -0,0 +1,31 @@
<?php
namespace app\common\validate;
use think\Validate;
class GameConfig extends Validate
{
protected $failException = true;
/**
* 验证规则
*/
protected $rule = [
];
/**
* 提示消息
*/
protected $message = [
];
/**
* 验证场景
*/
protected $scene = [
'add' => [],
'edit' => [],
];
}

View File

@@ -204,7 +204,24 @@ if (!function_exists('get_controller_path')) {
if (count($parts) < 2) {
return $parts[0] ?? null;
}
return implode('/', array_slice($parts, 1, -1)) ?: $parts[1];
$segments = array_slice($parts, 1, -1);
if ($segments === []) {
return $parts[1] ?? null;
}
// ThinkPHP 风格段 game.Config -> game/config与 $request->controller 解析结果一致(否则权限节点对不上)
$normalized = [];
foreach ($segments as $seg) {
if (str_contains($seg, '.')) {
$dotPos = strpos($seg, '.');
$mod = substr($seg, 0, $dotPos);
$ctrl = substr($seg, $dotPos + 1);
$normalized[] = strtolower($mod);
$normalized[] = strtolower(preg_replace('/([a-z])([A-Z])/', '$1_$2', $ctrl));
} else {
$normalized[] = strtolower(preg_replace('/([a-z])([A-Z])/', '$1_$2', $seg));
}
}
return implode('/', $normalized);
}
}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,21 @@
export default {
ID: 'ID',
channel_id: 'channel_id',
channel__name: 'name',
group: 'group',
name: 'name',
title: 'title',
value: 'value',
'weight key': 'Key',
'weight value': 'Value',
'weight sum must 100': 'The sum of weights for default_tier_weight / default_kill_score_weight must equal 100',
'weight each max 100': 'Each weight value must not exceed 100',
'weight value numeric': 'Weight values must be valid numbers',
sort: 'sort',
instantiation: 'instantiation',
'instantiation 0': 'instantiation 0',
'instantiation 1': 'instantiation 1',
create_time: 'create_time',
update_time: 'update_time',
'quick Search Fields': 'ID',
}

View File

@@ -0,0 +1,21 @@
export default {
ID: 'ID',
channel_id: '渠道id',
channel__name: '渠道名',
group: '分组',
name: '配置标识',
title: '配置名称',
value: '值',
'weight key': '键',
'weight value': '数值',
'weight sum must 100': 'default_tier_weight / default_kill_score_weight 的权重之和必须等于 100',
'weight each max 100': '每项权重不能超过 100',
'weight value numeric': '权重值必须为有效数字',
sort: '排序',
instantiation: '实例化',
'instantiation 0': '不需要',
'instantiation 1': '需要',
create_time: '创建时间',
update_time: '更新时间',
'quick Search Fields': 'ID',
}

View File

@@ -0,0 +1,93 @@
<template>
<div v-if="isGameWeight && weightTagLabels.length" class="game-config-value-tags">
<el-tag
v-for="(label, idx) in weightTagLabels"
:key="idx"
class="m-4"
effect="light"
type="primary"
size="default"
>
{{ label }}
</el-tag>
</div>
<span v-else class="game-config-value-plain">{{ plainText }}</span>
</template>
<script setup lang="ts">
import { computed } from 'vue'
const props = defineProps<{
renderRow: TableRow
renderField: TableColumn
renderValue: unknown
renderColumn: import('element-plus').TableColumnCtx<TableRow>
renderIndex: number
}>()
const isGameWeight = computed(() => props.renderRow?.group === 'game_weight')
/**
* value 形如 [{"T1":"5"},{"T2":"20"},...] 或同结构的 JSON 字符串
*/
function parseWeightTagLabels(raw: unknown): string[] {
if (raw === null || raw === undefined || raw === '') {
return []
}
let arr: unknown[] = []
if (typeof raw === 'string') {
const s = raw.trim()
if (!s) return []
try {
const parsed = JSON.parse(s)
arr = Array.isArray(parsed) ? parsed : []
} catch {
return []
}
} else if (Array.isArray(raw)) {
arr = raw
} else {
return []
}
const labels: string[] = []
for (const item of arr) {
if (item !== null && typeof item === 'object' && !Array.isArray(item)) {
for (const [k, v] of Object.entries(item as Record<string, unknown>)) {
labels.push(`${k}:${String(v)}`)
}
}
}
return labels
}
const weightTagLabels = computed(() => parseWeightTagLabels(props.renderValue))
const plainText = computed(() => {
const v = props.renderValue
if (v === null || v === undefined) return ''
if (typeof v === 'object') {
try {
return JSON.stringify(v)
} catch {
return String(v)
}
}
return String(v)
})
</script>
<style scoped lang="scss">
.game-config-value-tags {
display: flex;
flex-wrap: wrap;
justify-content: center;
gap: 4px 0;
}
.m-4 {
margin: 4px;
}
.game-config-value-plain {
word-break: break-all;
}
</style>

View File

@@ -0,0 +1,164 @@
<template>
<div class="default-main ba-table-box">
<el-alert class="ba-table-alert" v-if="baTable.table.remark" :title="baTable.table.remark" type="info" show-icon />
<!-- 表格顶部菜单 -->
<!-- 自定义按钮请使用插槽甚至公共搜索也可以使用具名插槽渲染参见文档 -->
<TableHeader
:buttons="['refresh', 'add', 'edit', 'delete', 'comSearch', 'quickSearch', 'columnDisplay']"
:quick-search-placeholder="t('Quick search placeholder', { fields: t('game.config.quick Search Fields') })"
></TableHeader>
<!-- 表格 -->
<!-- 表格列有多种自定义渲染方式比如自定义组件具名插槽等参见文档 -->
<!-- 要使用 el-table 组件原有的属性直接加在 Table 标签上即可 -->
<Table ref="tableRef"></Table>
<!-- 表单 -->
<PopupForm />
</div>
</template>
<script setup lang="ts">
import { onMounted, provide, useTemplateRef } from 'vue'
import { useI18n } from 'vue-i18n'
import PopupForm from './popupForm.vue'
import GameConfigValueCell from './GameConfigValueCell.vue'
import { baTableApi } from '/@/api/common'
import { defaultOptButtons } from '/@/components/table'
import TableHeader from '/@/components/table/header/index.vue'
import Table from '/@/components/table/index.vue'
import baTableClass from '/@/utils/baTable'
defineOptions({
name: 'game/config',
})
const { t } = useI18n()
const tableRef = useTemplateRef('tableRef')
const optButtons: OptButton[] = defaultOptButtons(['edit', 'delete'])
/**
* baTable 内包含了表格的所有数据且数据具备响应性,然后通过 provide 注入给了后代组件
*/
const baTable = new baTableClass(
new baTableApi('/admin/game.Config/'),
{
pk: 'ID',
column: [
{ type: 'selection', align: 'center', operator: false },
{ label: t('game.config.ID'), prop: 'ID', align: 'center', width: 70, operator: 'RANGE', sortable: 'custom' },
// {
// label: t('game.config.channel_id'),
// prop: 'channel_id',
// align: 'center',
// show: false,
// enableColumnDisplayControl: false,
// operatorPlaceholder: t('Fuzzy query'),
// render: 'tags',
// operator: 'LIKE',
// comSearchRender: 'string',
// },
{
label: t('game.config.channel__name'),
prop: 'channel.name',
align: 'center',
minWidth: 100,
operatorPlaceholder: t('Fuzzy query'),
render: 'tags',
operator: 'LIKE',
comSearchRender: 'string',
},
{
label: t('game.config.group'),
prop: 'group',
align: 'center',
operatorPlaceholder: t('Fuzzy query'),
sortable: false,
operator: 'LIKE',
},
{
label: t('game.config.name'),
prop: 'name',
align: 'center',
minWidth: 180,
operatorPlaceholder: t('Fuzzy query'),
render: 'tag',
sortable: false,
operator: 'LIKE',
},
{
label: t('game.config.title'),
prop: 'title',
align: 'center',
minWidth: 85,
operatorPlaceholder: t('Fuzzy query'),
sortable: false,
operator: 'LIKE',
},
{
label: t('game.config.value'),
prop: 'value',
align: 'center',
minWidth: 220,
sortable: false,
operator: 'LIKE',
comSearchRender: 'string',
render: 'customRender',
customRender: GameConfigValueCell,
},
{
label: t('game.config.instantiation'),
prop: 'instantiation',
align: 'center',
operator: 'RANGE',
sortable: false,
render: 'tag',
replaceValue: { '0': t('game.config.instantiation 0'), '1': t('game.config.instantiation 1') },
},
{ label: t('game.config.sort'), prop: 'sort', align: 'center', sortable: false, operator: 'RANGE' },
{
label: t('game.config.create_time'),
prop: 'create_time',
align: 'center',
render: 'datetime',
operator: 'RANGE',
comSearchRender: 'datetime',
sortable: 'custom',
width: 160,
timeFormat: 'yyyy-mm-dd hh:MM:ss',
},
{
label: t('game.config.update_time'),
prop: 'update_time',
align: 'center',
render: 'datetime',
operator: 'RANGE',
comSearchRender: 'datetime',
sortable: 'custom',
width: 160,
timeFormat: 'yyyy-mm-dd hh:MM:ss',
},
{ label: t('Operate'), align: 'center', width: 100, render: 'buttons', buttons: optButtons, operator: false },
],
dblClickNotEditColumn: [undefined, 'instantiation'],
defaultOrder: { prop: 'group', order: 'desc' },
},
{
defaultItems: { sort: 100 },
}
)
provide('baTable', baTable)
onMounted(() => {
baTable.table.ref = tableRef.value
baTable.mount()
baTable.getData()?.then(() => {
baTable.initSort()
baTable.dragSort()
})
})
</script>
<style scoped lang="scss"></style>

View File

@@ -0,0 +1,375 @@
<template>
<!-- 对话框表单 -->
<!-- 建议使用 Prettier 格式化代码 -->
<!-- el-form 内可以混用 el-form-itemFormItemba-input 等输入组件 -->
<el-dialog
class="ba-operate-dialog"
:close-on-click-modal="false"
:model-value="['Add', 'Edit'].includes(baTable.form.operate!)"
@close="baTable.toggleForm"
>
<template #header>
<div class="title" v-drag="['.ba-operate-dialog', '.el-dialog__header']" v-zoom="'.ba-operate-dialog'">
{{ baTable.form.operate ? t(baTable.form.operate) : '' }}
</div>
</template>
<el-scrollbar v-loading="baTable.form.loading" class="ba-table-form-scrollbar">
<div
class="ba-operate-form"
:class="'ba-' + baTable.form.operate + '-form'"
:style="config.layout.shrink ? '' : 'width: calc(100% - ' + baTable.form.labelWidth! / 2 + 'px)'"
>
<el-form
v-if="!baTable.form.loading"
ref="formRef"
@submit.prevent=""
@keyup.enter="baTable.onSubmit(formRef)"
:model="baTable.form.items"
:label-position="config.layout.shrink ? 'top' : 'right'"
:label-width="baTable.form.labelWidth + 'px'"
:rules="rules"
>
<FormItem
:label="t('game.config.channel_id')"
type="remoteSelect"
v-model="baTable.form.items!.channel_id"
prop="channel_id"
:input-attr="{ ...channelRemoteAttr, disabled: metaFieldsDisabled }"
:placeholder="t('Please select field', { field: t('game.config.channel_id') })"
/>
<FormItem
:label="t('game.config.group')"
type="select"
v-model="baTable.form.items!.group"
prop="group"
:input-attr="{ content: groupSelectContentFiltered, disabled: metaFieldsDisabled }"
:placeholder="t('Please select field', { field: t('game.config.group') })"
/>
<FormItem
:label="t('game.config.name')"
type="string"
v-model="baTable.form.items!.name"
prop="name"
:input-attr="{ disabled: metaFieldsDisabled }"
:placeholder="t('Please input field', { field: t('game.config.name') })"
/>
<FormItem
:label="t('game.config.title')"
type="string"
v-model="baTable.form.items!.title"
prop="title"
:input-attr="{ disabled: metaFieldsDisabled }"
:placeholder="t('Please input field', { field: t('game.config.title') })"
/>
<!-- game_weight数组形式编辑存库仍为 JSON 字符串 -->
<el-form-item v-if="isGameWeight" :label="t('game.config.value')" prop="value">
<div class="weight-value-editor">
<div v-for="(row, idx) in weightRows" :key="idx" class="weight-value-row">
<el-input
v-model="row.key"
class="weight-key"
:readonly="weightKeyReadonly"
:clearable="!weightKeyReadonly"
:placeholder="t('Please input field', { field: t('game.config.weight key') })"
@input="onWeightRowChange"
/>
<span class="weight-sep">:</span>
<el-input
v-model="row.val"
class="weight-val"
:placeholder="t('Please input field', { field: t('game.config.weight value') })"
clearable
@input="onWeightRowChange"
/>
<el-button v-if="canEditWeightStructure" type="danger" link @click="removeWeightRow(idx)">
{{ t('Delete') }}
</el-button>
</div>
<el-button v-if="canEditWeightStructure" type="primary" link @click="addWeightRow">{{ t('Add') }}</el-button>
</div>
</el-form-item>
<FormItem
v-else
:label="t('game.config.value')"
type="textarea"
v-model="baTable.form.items!.value"
prop="value"
:input-attr="{ rows: 3 }"
@keyup.enter.stop=""
@keyup.ctrl.enter="baTable.onSubmit(formRef)"
:placeholder="t('Please input field', { field: t('game.config.value') })"
/>
<FormItem
:label="t('game.config.sort')"
type="number"
v-model="baTable.form.items!.sort"
prop="sort"
:input-attr="{ step: 1 }"
:placeholder="t('Please input field', { field: t('game.config.sort') })"
/>
<FormItem
:label="t('game.config.instantiation')"
type="switch"
v-model="baTable.form.items!.instantiation"
prop="instantiation"
:input-attr="{ content: { '0': t('game.config.instantiation 0'), '1': t('game.config.instantiation 1') } }"
/>
</el-form>
</div>
</el-scrollbar>
<template #footer>
<div :style="'width: calc(100% - ' + baTable.form.labelWidth! / 1.8 + 'px)'">
<el-button @click="baTable.toggleForm()">{{ t('Cancel') }}</el-button>
<el-button v-blur :loading="baTable.form.submitLoading" @click="baTable.onSubmit(formRef)" type="primary">
{{ baTable.form.operateIds && baTable.form.operateIds.length > 1 ? t('Save and edit next item') : t('Save') }}
</el-button>
</div>
</template>
</el-dialog>
</template>
<script setup lang="ts">
import type { FormItemRule } from 'element-plus'
import { computed, inject, reactive, ref, useTemplateRef, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import FormItem from '/@/components/formItem/index.vue'
import { useConfig } from '/@/stores/config'
import { useAdminInfo } from '/@/stores/adminInfo'
import type baTableClass from '/@/utils/baTable'
import { buildValidatorData } from '/@/utils/validate'
const config = useConfig()
const formRef = useTemplateRef('formRef')
const baTable = inject('baTable') as baTableClass
const adminInfo = useAdminInfo()
const { t } = useI18n()
const isSuperAdmin = computed(() => adminInfo.super === true)
/** 编辑且非超级管理员:渠道、分组、配置标识、配置名称不可改 */
const metaFieldsDisabled = computed(() => !isSuperAdmin.value && baTable.form.operate === 'Edit')
const channelRemoteAttr = {
pk: 'game_channel.id',
field: 'name',
remoteUrl: '/admin/game.Channel/index',
}
const groupSelectBase = {
game_config: 'game_config',
game_weight: 'game_weight',
}
/** 非超级管理员新增时不可选 game_weight需先由超级管理员建好键结构 */
const groupSelectContentFiltered = computed(() => {
if (!isSuperAdmin.value && baTable.form.operate === 'Add') {
return { game_config: groupSelectBase.game_config }
}
return groupSelectBase
})
/** game_weight编辑或非超管时键只读仅超管新增时可增删行、改键 */
const weightKeyReadonly = computed(() => {
if (!isGameWeight.value) return false
if (baTable.form.operate === 'Edit') return true
return !isSuperAdmin.value
})
const canEditWeightStructure = computed(() => isGameWeight.value && baTable.form.operate === 'Add' && isSuperAdmin.value)
type WeightRow = { key: string; val: string }
const weightRows = ref<WeightRow[]>([{ key: '', val: '' }])
const WEIGHT_SUM100_NAMES = ['default_tier_weight', 'default_kill_score_weight']
const isGameWeight = computed(() => baTable.form.items?.group === 'game_weight')
function parseValueToWeightRows(raw: unknown): WeightRow[] {
if (raw === null || raw === undefined || raw === '') {
return [{ key: '', val: '' }]
}
if (typeof raw === 'string') {
const s = raw.trim()
if (!s) return [{ key: '', val: '' }]
try {
const parsed = JSON.parse(s)
return arrayToWeightRows(parsed)
} catch {
return [{ key: '', val: '' }]
}
}
if (Array.isArray(raw)) {
return arrayToWeightRows(raw)
}
return [{ key: '', val: '' }]
}
function arrayToWeightRows(arr: unknown): WeightRow[] {
if (!Array.isArray(arr)) {
return [{ key: '', val: '' }]
}
const out: WeightRow[] = []
for (const item of arr) {
if (item !== null && typeof item === 'object' && !Array.isArray(item)) {
for (const [k, v] of Object.entries(item)) {
out.push({ key: k, val: v === null || v === undefined ? '' : String(v) })
}
}
}
return out.length ? out : [{ key: '', val: '' }]
}
function weightRowsToJsonString(rows: WeightRow[]): string {
const pairs: Record<string, string>[] = []
for (const r of rows) {
const k = r.key.trim()
if (k === '') continue
const one: Record<string, string> = {}
one[k] = r.val
pairs.push(one)
}
return JSON.stringify(pairs)
}
function syncWeightRowsToFormValue() {
const items = baTable.form.items
if (!items) return
items.value = weightRowsToJsonString(weightRows.value)
}
function onWeightRowChange() {
if (isGameWeight.value) {
syncWeightRowsToFormValue()
}
}
function addWeightRow() {
if (!canEditWeightStructure.value) return
weightRows.value.push({ key: '', val: '' })
syncWeightRowsToFormValue()
}
function removeWeightRow(idx: number) {
if (!canEditWeightStructure.value) return
if (weightRows.value.length <= 1) {
weightRows.value = [{ key: '', val: '' }]
} else {
weightRows.value.splice(idx, 1)
}
syncWeightRowsToFormValue()
}
function hydrateWeightRowsFromForm() {
if (!isGameWeight.value) return
weightRows.value = parseValueToWeightRows(baTable.form.items?.value)
}
watch(isGameWeight, (gw) => {
if (gw) {
hydrateWeightRowsFromForm()
}
})
watch(
() => baTable.form.loading,
(loading) => {
if (loading === false && baTable.form.items?.group === 'game_weight') {
hydrateWeightRowsFromForm()
}
}
)
watch(
() => baTable.form.items?.group,
() => {
if (baTable.form.items?.group === 'game_weight') {
hydrateWeightRowsFromForm()
}
}
)
function validateGameWeightRules(): string | undefined {
if (baTable.form.items?.group !== 'game_weight') {
return undefined
}
const name = baTable.form.items?.name ?? ''
const nums: number[] = []
for (const r of weightRows.value) {
const k = r.key.trim()
if (k === '') continue
const vs = r.val.trim()
if (vs === '') {
return t('Please input field', { field: t('game.config.weight value') })
}
const n = Number(vs)
if (!Number.isFinite(n)) {
return t('game.config.weight value numeric')
}
if (n > 100) {
return t('game.config.weight each max 100')
}
nums.push(n)
}
if (nums.length === 0) {
return t('Please input field', { field: t('game.config.value') })
}
if (WEIGHT_SUM100_NAMES.includes(name)) {
let sum = 0
for (const x of nums) {
sum += x
}
if (Math.abs(sum - 100) > 0.000001) {
return t('game.config.weight sum must 100')
}
}
return undefined
}
const rules: Partial<Record<string, FormItemRule[]>> = reactive({
group: [buildValidatorData({ name: 'required', title: t('game.config.group') })],
name: [buildValidatorData({ name: 'required', title: t('game.config.name') })],
title: [buildValidatorData({ name: 'required', title: t('game.config.title') })],
sort: [buildValidatorData({ name: 'number', title: t('game.config.sort') })],
instantiation: [buildValidatorData({ name: 'number', title: t('game.config.instantiation') })],
value: [
{
validator: (_rule, _val, callback) => {
const err = validateGameWeightRules()
if (err) {
callback(new Error(err))
return
}
callback()
},
trigger: ['blur', 'change'],
},
],
create_time: [buildValidatorData({ name: 'date', title: t('game.config.create_time') })],
update_time: [buildValidatorData({ name: 'date', title: t('game.config.update_time') })],
})
</script>
<style scoped lang="scss">
.weight-value-editor {
width: 100%;
}
.weight-value-row {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 8px;
}
.weight-key {
max-width: 140px;
}
.weight-val {
flex: 1;
min-width: 80px;
}
.weight-sep {
flex-shrink: 0;
color: var(--el-text-color-secondary);
}
</style>