<?php

namespace app\model;

use think\Collection;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

/**
 * 商家分类
 * Class Disease
 * @package app\model
 */
class Category extends Base
{
    /**
     * 根据父级ID 获取列表
     *
     * @param int $pid
     * @param string[] $fields
     * @return Disease[]|array|Collection
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function getListByPid(int $pid = 0, array $fields = ['pid', 'name', 'id'])
    {
        return self::where('pid', $pid)->order('id', 'desc')->field($fields)->select();
    }

    /**
     *  获取上下级
     * */
    public static function getByGroup()
    {
        $top = self::column(['pid', 'name', 'id'], "id");

        foreach ($top as $key => $value) {
            if (isset($top[$value["pid"]])) {
                $top[$value["pid"]]['children'][] = $value;
                unset($top[$key]);
            }
        }
        return $top;
    }

    /**
     * 获取全部列表
     *
     * @return Collection
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function getList()
    {
        return self::field('id,pid,name,commision')->order('id', 'desc')->select();
    }

    /**
     * 病种 xmSelect json数据
     *
     * @param int $pid
     * @param array $selected
     * @param array $disabled
     * @return array|Collection
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function diseaseXmJson(int $pid = 0, array $selected = [], array $disabled = [])
    {
        $list = self::getListByPid($pid);
        foreach ($list as $k => $m) {
            $list[$k]['selected'] = in_array($m['id'], $selected);
            $list[$k]['disabled'] = in_array($m['id'], $disabled);
        }

        return $list;
    }
}