<?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\Input;
use Illuminate\Support\Facades\Log;
use Modules\Admin\Traits\ClassifyMethod;
use Modules\Camera\Enum\CameraEnum;
use Modules\Camera\Http\Controllers\Api\HaiKangController;
use Modules\Mine\Entities\MineList;
use Modules\Mine\Entities\MineListExt;
use Modules\Mine\Enum\MineEnum;
use DB;

class MineServices{

    use ClassifyMethod;

    public function __construct()
    {

    }

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

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

        $mine_list = MineList::orderBy('sort', 'desc')->orderBy('id', 'asc')->where(
            [
                'parent_id' => 0
            ]
        );

        if ($mine_code) {
            $mine_list = $mine_list->where('slug', 'like', '%' . $mine_code . '%');
        }

        $mine_list = $mine_list->select(
            [
                'id',
                'title as name',
            ]
        )->get()->toArray();

        $result['data'] = $mine_list;

        return $result;
    }

    //获取矿区列表
    public static function getAreaList($mine_code = '')
    {
        $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 as pid',
            ]
        )->get()->toArray();

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

        if ($mine_code) {
            if (strstr($mine_code, ',')) {
                $mine_code = explode(',', $mine_code);
                $mine_one  = [];
                $mine_id   = [];
                foreach ($mine_code as $k => $v) {
                    $mine_id[] = MineList::where('slug', 'like', '%' . $v . '%')->where('parent_id', 0)->value('id');
                }
                foreach ($mine_list as $key => $val) {
                    if (in_array($val['mine_id'], $mine_id)) {
                        $mine_one[] = $val;
                    }
                }
                $result['data'] = $mine_one;
            } else {
                $mine_id = MineList::where('slug', 'like', '%' . $mine_code . '%')->where('parent_id', 0)->value('id');
                $mine_one = [];
                foreach ($mine_list as $key => $val) {
                    if ($val['mine_id'] == $mine_id) {
                        $mine_one[] = $val;
                    }
                }
                $result['data'] = $mine_one;
            }
        } else {
            $result['data'] = $mine_list;
        }

        return $result;
    }

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

    //矿区扩展信息表入库
    public static function insertMineListExt($mine_id, $params)
    {
        $result = MineListExt::insert(
            [
                'mine_id'    => $mine_id,
                'ip'         => $params['ip'],
                'port'       => $params['port'],
                'key'        => $params['key'],
                'secret'     => $params['secret'],
                'is_hak'     => $params['is_hak'],
                'sOrgId'     => $params['sOrgId'],
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s'),
            ]
        );

        return $result;
    }

    //编辑矿区扩展信息表
    public static function editMineListExt($mine_id, $params)
    {
        $query = MineListExt::where('mine_id', $mine_id)->first();

        if ($query) {
            $result = MineListExt::where('mine_id', $mine_id)->update(
                [
                    'ip'         => $params['ip'],
                    'port'       => $params['port'],
                    'key'        => $params['key'],
                    'secret'     => $params['secret'],
                    'is_hak'     => $params['is_hak'],
                    'sOrgId'     => $params['sOrgId'],
                    'updated_at' => date('Y-m-d H:i:s'),
                ]
            );
        } else {
            $result = MineListExt::insert(
                [
                    'mine_id'    => $mine_id,
                    'ip'         => $params['ip'],
                    'port'       => $params['port'],
                    'key'        => $params['key'],
                    'secret'     => $params['secret'],
                    'is_hak'     => $params['is_hak'],
                    'created_at' => date('Y-m-d H:i:s'),
                    'updated_at' => date('Y-m-d H:i:s'),
                ]
            );
        }

        return $result;
    }

    //查询后台矿区列表
    public static function getAdminMineList($staff_num)
    {
        //查询当前登录用户权限内的区域
        $user = DB::table('users')->where('staff_num',$staff_num)->first();
        $mine_array = explode(';',$user->mine_role);//权限内的矿区
        $mine_all = DB::table('mine_list')->where('deleted_at',null)->get();//所有区域
        $mine_use = [];//权限内矿区下所有区域
        foreach($mine_all as $k=>$v){
            if(in_array(explode('|',$v->degree)[0],$mine_array)){
                $mine_use[] = $v->id;
            }
        }

        $mine_list = MineList::whereIn('id',$mine_use)->orderBy('sort', 'desc')->get()->toArray();

        if ($mine_list) {
            $result = self::sortMineListExt($mine_list);
            foreach ($result as $key => $val) {
                if (isset($val['child'])) {
                    $sort = array_column($val['child'], 'sort');
                    array_multisort($sort, SORT_ASC, $val['child']);
                }
            }
            return $result;
        }
        return [];
    }

    //递归查询矿区扩展信息
    public static function sortMineListExt($mine_list, $pid = '0')
    {
        $arr = [];
        if (empty($mine_list)) {
            return [];
        }
        $num = 0;
        foreach ($mine_list as $key => $val) {
            if ($val['parent_id'] == $pid) {
                $arr[$num]          = $val;
                $query = MineListExt::where('mine_id', $val['id'])->first();
                if ($query) {
                    $res = '';
                    if($query->is_hak == MineEnum::IS_HAK_YES){
                        $res = '海康';
                    }elseif($query->is_hak == MineEnum::IS_HAK_TD){
                        $res = '天地伟业';
                    }else{
                        $res = '其它';
                    }
                    $arr[$num]['ip']     = $query->ip;
                    $arr[$num]['port']   = $query->port;
                    $arr[$num]['key']    = $query->key;
                    $arr[$num]['secret'] = $query->secret;
                    $arr[$num]['is_hak'] = $res;
                } else {
                    $arr[$num]['ip']     = '';
                    $arr[$num]['port']   = '';
                    $arr[$num]['key']    = '';
                    $arr[$num]['secret'] = '';
                    $arr[$num]['is_hak'] = '其它';
                }
                $arr[$num]['child'] = self::sortMineListExt($mine_list, $val['id']);
                if (count($arr[$num]['child']) == 0) {
                    unset($arr[$num]['child']);
                }
                $num++;
            }
        }
        return $arr;
    }

    //查询后台单个矿区
    public static function getAdminMineOne($mine_id)
    {
        $mine_list = MineList::find($mine_id);
        $mine_list->ip = '';
        $mine_list->port = '';
        $mine_list->key = '';
        $mine_list->secret = '';
        $mine_list->is_hak = MineEnum::IS_HAK_NO;

        $mine_list_ext = MineListExt::where('mine_id', $mine_id)->first();

        if ($mine_list_ext) {
            $mine_list->ip     = $mine_list_ext->ip;
            $mine_list->port   = $mine_list_ext->port;
            $mine_list->key    = $mine_list_ext->key;
            $mine_list->secret = $mine_list_ext->secret;
            $mine_list->is_hak = $mine_list_ext->is_hak;
            $mine_list->sOrgId = $mine_list_ext->sOrgId;
        }

        return $mine_list;
    }

    //查询海康矿井区域
    public static function getHaiKangArea($mine_id, $type = CameraEnum::REQUEST_TYPE_API)
    {
        $result['status'] = true;
        $result['msg']    = ApiEnum::RETURN_SUCCESS;
        $result['data']   = [];

        $query = MineListExt::where('mine_id', $mine_id)->first();

        Input::replace(
            [
                'url'     => trim($query->ip, '/') . ':' . $query->port,
                'key'     => $query->key,
                'secret'  => $query->secret,
                'type'    => $type,
                'mine_id' => $mine_id,
            ]
        );
        $haikang   = new HaiKangController();
        $result_hk = $haikang->getRegionsList();

        $result['data'] = $result_hk['data']['list'];
        
        return $result;
    }
}