<?php
namespace app\adminapi\service\material;

use core\base\BaseService;
use app\adminapi\model\material\MaterialCategory;
use app\adminapi\model\material\Material;

/**
 * 素材分类服务（多级）
 */
class MaterialCategoryService extends BaseService
{
    public function __construct()
    {
        parent::__construct();
        $this->model = new MaterialCategory();
    }

    public function tree(array $params): array
    {
        $where = [];
        if (!empty($params['type'])) {
            $where[] = ['type', '=', $params['type']];
        }
        $list = $this->model->where($where)->order('id asc')->select()->toArray();

        // 项目内 helper：pid 字段转 tree
        return tree($list, 'children', 'id', 'pid', 0);
    }

    public function add(array $params): void
    {
        $pid = (int)($params['pid'] ?? 0);
        if ($pid > 0 && !$this->model->where('id', $pid)->find()) {
            throw new \RuntimeException('父级分类不存在');
        }
        $data = [
            'pid' => $pid,
            'name' => (string)$params['name'],
            'type' => (string)($params['type'] ?? 'image'),
            'create_time' => time(),
        ];
        $this->model->save($data);
    }

    public function edit(array $params): void
    {
        $id = (int)$params['id'];
        $row = $this->model->where('id', $id)->find();
        if (!$row) throw new \RuntimeException('分类不存在');

        $update = [];
        if (isset($params['pid'])) {
            $pid = (int)$params['pid'];
            if ($pid === $id) throw new \RuntimeException('父级分类不能是自己');
            if ($pid > 0 && !$this->model->where('id', $pid)->find()) {
                throw new \RuntimeException('父级分类不存在');
            }
            $update['pid'] = $pid;
        }
        if (isset($params['name']) && $params['name'] !== '') $update['name'] = (string)$params['name'];
        if (isset($params['type']) && $params['type'] !== '') $update['type'] = (string)$params['type'];

        if ($update) {
            $update['update_time'] = time();
            $this->model->where('id', $id)->update($update);
        }
    }

    public function delete(int $id)
    {
        $row = $this->model->where('id', $id)->find();
        if (!$row) {
            self::setError('分类不存在');
            return false;
        }

        // 获取所有要删除的分类ID（包含子子孙孙）
        $ids = array_merge([$id], $this->getChildIds($id));

        $this->model->startTrans();
        try {
            // 获取这些分类下的所有素材ID
            $materialIds = (new Material())->whereIn('category_id', $ids)->column('id');

            // 删除素材
            if (!empty($materialIds)) {
                (new MaterialService())->delete($materialIds);
            }

            // 删除分类
            $this->model->whereIn('id', $ids)->delete();

            $this->model->commit();
            return true;
        } catch (\Exception $e) {
            $this->model->rollback();
            self::setError($e->getMessage());
            return false;
        }
    }

    protected function getChildIds(int $pid): array
    {
        $ids = [];
        $children = $this->model->where('pid', $pid)->column('id');
        foreach ($children as $childId) {
            $ids[] = $childId;
            $ids = array_merge($ids, $this->getChildIds($childId));
        }
        return $ids;
    }
}
