<?php
/**
 * Created by PhpStorm.
 * User: qiuzijian
 * Date: 2021-04-17
 * Time: 16:56
 */

namespace Modules\Mine\Services;

use App\Enum\ApiEnum;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Modules\Admin\Traits\ClassifyMethod;
use Modules\Mine\Entities\MineList;

class MineServices{

    use ClassifyMethod;

    public function __construct()
    {

    }

    //初始化mine_list表
    public function initMineList()
    {
        $this->classify   = new MineList();
        $this->cacheTitle = 'MineManageList';
    }

    //获取矿区列表
    public static function getMineList()
    {
        $result['status'] = true;
        $result['msg']    = ApiEnum::RETURN_SUCCESS;

        $mine_list = MineList::orderBy('sort', 'desc')->orderBy('id', 'asc')->select(
            [
                'id as mine_id',
                'title as name',
                'parent_id',
            ]
        )->get()->toArray();

        if ($mine_list) {
            $mine_list = self::sortMineList($mine_list);
        }

        $result['data'] = $mine_list;

        return $result;
    }

    //递归排序矿区列表
    public static function sortMineList($mine_list, $pid = '0')
    {
        $arr = [];
        if (empty($mine_list)) {
            return '';
        }
        $num = 0;
        foreach ($mine_list as $key => $value) {
            if ($value['parent_id'] == $pid) {
                $arr[$num]          = $value;
                $arr[$num]['children'] = self::sortMineList($mine_list, $value['mine_id']);
                unset($arr[$num]['parent_id']);
                if (count($arr[$num]['children']) == 0) {
                    unset($arr[$num]['children']);
                }
                $num++;
            }
        }
        return $arr;
    }
}