<?php
// +----------------------------------------------------------------------
// | saiadmin [ saiadmin快速开发框架 ]
// +----------------------------------------------------------------------
namespace plugin\saiadmin\app\logic\system;

use app\dice\service\DiceChannelConfigService;
use plugin\saiadmin\app\service\SystemRoleChannelService;
use plugin\saiadmin\basic\think\BaseLogic;
use plugin\saiadmin\exception\ApiException;
use plugin\saiadmin\app\model\system\SystemDept;
use plugin\saiadmin\app\model\system\SystemUser;

/**
 * 渠道逻辑层（表 sa_system_dept）
 */
class SystemDeptLogic extends BaseLogic
{
    public function __construct()
    {
        $this->model = new SystemDept();
    }

    public function add($data): mixed
    {
        $data = $this->handleData($data);
        $this->model->save($data);
        $deptId = (int) $this->model->getKey();
        if ($deptId > 0) {
            (new DiceChannelConfigService())->copyDefaultConfigToDept($deptId);
            (new SystemRoleChannelService())->copyDefaultRolesToDept($deptId, false);
        }
        return $deptId;
    }

    public function edit($id, $data): mixed
    {
        $data = $this->handleData($data);
        return $this->model->update($data, ['id' => $id]);
    }

    public function destroy($ids): bool
    {
        $count = SystemUser::where('dept_id', 'in', $ids)->count();
        if ($count > 0) {
            throw new ApiException('This channel has users, please delete or transfer them first');
        }
        return $this->model->destroy($ids);
    }

    /**
     * 带关联选项删除渠道
     */
    public function destroyWithRelations(int $deptId, array $deleteTables): bool
    {
        (new SystemRoleChannelService())->deleteRolesByDept($deptId);
        (new DiceChannelConfigService())->destroyDeptWithRelations($deptId, $deleteTables);
        return true;
    }

    public function getDestroyPreview(array $deptIds): array
    {
        return (new DiceChannelConfigService())->getDestroyPreview($deptIds);
    }

    public function syncAllChannelConfigs(): array
    {
        $config = (new DiceChannelConfigService())->syncAllChannelsFromDefault();
        $roles = (new SystemRoleChannelService())->syncAllChannelsFromDefault();
        return ['config' => $config, 'roles' => $roles];
    }

    protected function handleData($data)
    {
        $data['level'] = '0';
        $data['parent_id'] = 0;
        return $data;
    }

    public function tree(array $where = []): array
    {
        $query = $this->search($where);
        $query->order('sort', 'desc');
        $query->with(['leader']);
        return $this->getAll($query);
    }

    public function accessDept(array $where = []): array
    {
        $query = $this->search($where);
        if (isset($this->adminInfo['id']) && $this->adminInfo['id'] > 1) {
            $deptId = $this->resolveAccessibleDeptId();
            if ($deptId > 0) {
                $query->where('id', $deptId);
            } else {
                return [];
            }
        }
        $query->field('id, id as value, name as label');
        $query->order('sort', 'desc');
        return $this->getAll($query);
    }

    /**
     * 当前管理员可操作的渠道 ID（deptList 缺失时回退 dept_id）
     */
    public function resolveAccessibleDeptId(?array $adminInfo = null): int
    {
        $adminInfo = $adminInfo ?? $this->adminInfo ?? [];
        if (empty($adminInfo['id']) || (int) $adminInfo['id'] <= 1) {
            return 0;
        }
        $deptList = $adminInfo['deptList'] ?? [];
        if (is_array($deptList) && isset($deptList['id']) && (int) $deptList['id'] > 0) {
            return (int) $deptList['id'];
        }
        $deptId = $adminInfo['dept_id'] ?? null;
        if ($deptId !== null && $deptId !== '' && (int) $deptId > 0) {
            return (int) $deptId;
        }

        return 0;
    }
}
