/**
 * 后台字典/系统参数管理
 * Banner 配置存于 sys_parameter，key：bannerListImage、bannerDetailImage、bannerListIndex
 */
const { sys_parameter, op } = require('../../middleware/baseModel');

const BANNER_KEYS = ['bannerListImage', 'bannerDetailImage', 'bannerListIndex'];

module.exports = {

    // all 接口
    'GET /sys_parameter/all': async (ctx, next) => {
        const rows = await sys_parameter.findAll({
            where: {},
            attributes: ['key', 'value']
        });
        return ctx.success(rows);
    },


    /**
     * 获取 Banner 配置（三个 key 的 value）
     */
    'GET /sys_parameter/banner_config': async (ctx, next) => {
        const rows = await sys_parameter.findAll({
            where: {
                key: { [op.in]: ['bannerListImage', 'bannerDetailImage', 'bannerListIndex'] }
            },
            attributes: ['key', 'value']
        });
        const data = {
            bannerListImage: '',
            bannerDetailImage: '',
            bannerListIndex: '0'
        };
        if (rows && rows.length) {
            rows.forEach((row) => {
                const key = row.key;
                if (BANNER_KEYS.includes(key)) {
                    data[key] = row.value != null ? String(row.value).replace(/\n/g, '') : '';
                }
            });
        }
        return ctx.success(data);
    },

    /**
     * 保存 Banner 配置
     * body: { bannerListImage?, bannerDetailImage?, bannerListIndex? }
     */
    'POST /sys_parameter/banner_config': async (ctx, next) => {
        const body = ctx.getBody() || {};
        const updates = [
            { key: 'bannerListImage', value: body.bannerListImage != null ? String(body.bannerListImage).trim() : '' },
            { key: 'bannerDetailImage', value: body.bannerDetailImage != null ? String(body.bannerDetailImage).trim() : '' },
            { key: 'bannerListIndex', value: body.bannerListIndex != null ? String(body.bannerListIndex).trim() : '0' }
        ];

        for (const item of updates) {
            let row = await sys_parameter.findOne({ where: { key: item.key } });
            if (row) {
                await row.update({ value: item.value });
            } else {
                await sys_parameter.create({
                    key: item.key,
                    value: item.value,
                    remark: item.key === 'bannerListIndex' ? '列表下标或关闭(0关闭)' : 'Banner图片URL',
                    is_modified: 0
                });
            }
        }

        return ctx.success({}, '保存成功');
    }
};
