<?php

use think\migration\Migrator;

class SeedPriceAdjustCateRule extends Migrator
{
    public function up(): void
    {
        $now = time();
        $db  = $this->getAdapter()->getConnection();

        // 动态查找「财务模块」（基础数据-财务管理）节点 ID
        $financeMenu = $db->query("SELECT id FROM `oa_admin_rule` WHERE title='财务模块' AND module='finance' LIMIT 1")
                          ->fetchAll(\PDO::FETCH_ASSOC);
        if (empty($financeMenu)) {
            throw new \RuntimeException('找不到财务模块菜单节点，请确认基础数据已安装');
        }
        $financePid = $financeMenu[0]['id'];

        // 动态查找超级权限角色 ID
        $superGroup = $db->query("SELECT id FROM `oa_admin_group` WHERE title='超级权限角色' LIMIT 1")
                         ->fetchAll(\PDO::FETCH_ASSOC);
        if (empty($superGroup)) {
            throw new \RuntimeException('找不到超级权限角色，请确认基础数据已安装');
        }
        $superGroupId = $superGroup[0]['id'];

        // 菜单节点
        $this->execute("INSERT INTO `oa_admin_rule`
            (`pid`, `src`, `title`, `name`, `module`, `icon`, `menu`, `sort`, `status`, `create_time`)
            VALUES
            ({$financePid}, 'finance/priceadjustcate/datalist', '调价类型', '调价类型管理', 'finance', '', 1, 51, 1, {$now})");

        $ruleId = $db->lastInsertId();

        // 子权限节点
        $this->execute("INSERT INTO `oa_admin_rule`
            (`pid`, `src`, `title`, `name`, `module`, `icon`, `menu`, `sort`, `status`, `create_time`)
            VALUES
            ({$ruleId}, 'finance/priceadjustcate/datalist', '列表',      '调价类型-列表',     'finance', '', 2, 1, 1, {$now}),
            ({$ruleId}, 'finance/priceadjustcate/add',      '添加/编辑', '调价类型-添加编辑', 'finance', '', 2, 2, 1, {$now}),
            ({$ruleId}, 'finance/priceadjustcate/del',      '删除',      '调价类型-删除',     'finance', '', 2, 3, 1, {$now}),
            ({$ruleId}, 'finance/priceadjustcate/set',      '设置',      '调价类型-设置',     'finance', '', 2, 4, 1, {$now})");

        // 授权给超级权限角色
        $this->execute("UPDATE `oa_admin_group`
            SET `rules` = CONCAT(`rules`, ',', (
                SELECT GROUP_CONCAT(t.id) FROM (
                    SELECT id FROM `oa_admin_rule` WHERE id = {$ruleId} OR pid = {$ruleId}
                ) t
            ))
            WHERE `id` = {$superGroupId}");
    }

    public function down(): void
    {
        $db = $this->getAdapter()->getConnection();

        $ruleIds = $db->query("SELECT id FROM `oa_admin_rule` WHERE src LIKE 'finance/priceadjustcate/%'")
                      ->fetchAll(\PDO::FETCH_COLUMN);
        if (!empty($ruleIds)) {
            $this->removeRulesFromGroups($ruleIds);
            $in = implode(',', array_map('intval', $ruleIds));
            $this->execute("DELETE FROM `oa_admin_rule` WHERE id IN ({$in})");
        }
    }

    /**
     * 从所有角色的 rules 字段中剔除指定权限节点 ID
     *
     * @param array<int, int|string> $ruleIds
     */
    protected function removeRulesFromGroups(array $ruleIds): void
    {
        $db      = $this->getAdapter()->getConnection();
        $ruleIds = array_map('strval', $ruleIds);
        $groups  = $db->query("SELECT id, rules FROM `oa_admin_group`")->fetchAll(\PDO::FETCH_ASSOC);
        foreach ($groups as $group) {
            $rules = array_filter(explode(',', (string) $group['rules']), static fn($v) => $v !== '');
            $kept  = array_values(array_diff($rules, $ruleIds));
            if (count($kept) !== count($rules)) {
                $newRules = implode(',', $kept);
                $this->execute("UPDATE `oa_admin_group` SET `rules` = '{$newRules}' WHERE `id` = {$group['id']}");
            }
        }
    }
}