<?php
// +----------------------------------------------------------------------
// | saiadmin [ saiadmin快速开发框架 ]
// +----------------------------------------------------------------------
// | Author: your name
// +----------------------------------------------------------------------
namespace app\dice\logic\ante_config;

use app\dice\helper\AdminScopeHelper;
use app\dice\helper\ConfigScopeEditHelper;
use app\dice\model\ante_config\DiceAnteConfig;
use app\dice\basic\DiceBaseLogic;

/**
 * 底注配置逻辑层
 */
class DiceAnteConfigLogic extends DiceBaseLogic
{
    public function __construct()
    {
        $this->model = new DiceAnteConfig();
    }

    public function add(array $data): mixed
    {
        return $this->transaction(function () use ($data) {
            $this->applyNameTitleFromMult($data);
            $this->normalizeDefaultField($data);
            $deptId = AdminScopeHelper::resolveConfigDeptId(null, $data['dept_id'] ?? AdminScopeHelper::DEFAULT_TEMPLATE_DEPT);
            if ((int) ($data['is_default'] ?? 0) === 1) {
                $this->clearOtherDefaults(null, $deptId);
            }
            return parent::add($data);
        });
    }

    public function edit($id, array $data, ?array $adminInfo = null, $requestDeptId = null): mixed
    {
        $pickedDeptId = AdminScopeHelper::pickRequestDeptId($requestDeptId, $data);
        $deptId = AdminScopeHelper::resolveConfigDeptId($adminInfo, $pickedDeptId);
        return $this->transaction(function () use ($id, $data, $deptId, $adminInfo, $pickedDeptId) {
            $this->applyNameTitleFromMult($data);
            $this->normalizeDefaultField($data);
            if ((int) ($data['is_default'] ?? 0) === 1) {
                $this->clearOtherDefaults((int) $id, $deptId);
            }
            return ConfigScopeEditHelper::updateByPkAndDept(
                $this->model,
                $id,
                $deptId,
                $data,
                ['id', 'dept_id', 'create_time', 'update_time', 'delete_time', 'row_id'],
                $adminInfo,
                $pickedDeptId
            );
        });
    }

    /**
     * 防止删除后全表无默认：若删除了默认项，自动把最小 id 设为默认。
     */
    public function destroy($ids): bool
    {
        return $this->transaction(function () use ($ids) {
            $idList = is_array($ids) ? $ids : explode(',', (string) $ids);
            $intIds = [];
            foreach ($idList as $v) {
                $iv = (int) $v;
                if ($iv > 0) {
                    $intIds[] = $iv;
                }
            }
            if ($intIds === []) {
                return false;
            }

            $deletedDefaultCount = $this->model->whereIn('id', $intIds)->where('is_default', 1)->count();
            $result = $this->model->destroy($intIds);
            if ($result && $deletedDefaultCount > 0) {
                $first = $this->model->order('id', 'asc')->find();
                if ($first) {
                    $this->model->where('id', (int) $first['id'])->update(['is_default' => 1]);
                }
            }
            return (bool) $result;
        });
    }

    private function normalizeDefaultField(array &$data): void
    {
        if (!array_key_exists('is_default', $data)) {
            return;
        }
        $data['is_default'] = ((int) $data['is_default']) === 1 ? 1 : 0;
    }

    /** 名称、标题随底注倍率自动设为 xN */
    private function applyNameTitleFromMult(array &$data): void
    {
        if (!array_key_exists('mult', $data)) {
            return;
        }
        $mult = (int) $data['mult'];
        if ($mult <= 0) {
            return;
        }
        $label = 'x' . $mult;
        $data['name'] = $label;
        $data['title'] = $label;
    }

    private function clearOtherDefaults(?int $excludeId = null, int $deptId = AdminScopeHelper::DEFAULT_TEMPLATE_DEPT): void
    {
        $query = $this->model->where('is_default', 1);
        ConfigScopeEditHelper::applyDeptIdWhere($query, $deptId);
        if ($excludeId !== null && $excludeId > 0) {
            $query->where('id', '<>', $excludeId);
        }
        $query->update(['is_default' => 0]);
    }
}
