<?php


namespace App\Http\Services;


use App\Model\BrandModel;
use App\Model\SpuBrandModel;
use App\Model\RedisModel;
use App\Model\StandardBrandMappingModel;
use App\Model\StandardBrandModel;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class StandardBrandService
{
    public function getStandardBrandList($params)
    {
        $limit = array_get($params, 'limit', 30);
        $searchBrandName = array_get($params, 'brand_name');
        $standardBrandModel = new StandardBrandModel();
        $query = $standardBrandModel->selectRaw('brand_name,standard_brand_id as brand_id')
            ->where('status', 1);
        $flag = false;
        //这里搜索的普通品牌名字,要根据普通品牌名字去搜索出相关的标准品牌名称
        if (!empty($searchBrandName)) {
            $brandIds = SpuBrandModel::where('brand_name', 'like', "%$searchBrandName%")->limit(100)->pluck('brand_id');
            if (!empty($brandIds)) {
                $standardBrandIds = StandardBrandMappingModel::whereIn('brand_id',
                    $brandIds)->pluck('standard_brand_id');
                if (!empty($standardBrandIds)) {
                    $query->whereIn('standard_brand_id', $standardBrandIds)->orWhere('brand_name', 'like',
                        "%$searchBrandName%")->orderByRaw("CASE WHEN brand_name LIKE '${searchBrandName}' THEN 1 WHEN brand_name LIKE '${searchBrandName}%' THEN 2 WHEN brand_name LIKE '%${searchBrandName}' THEN 4 ELSE 3 END");
                    $flag = true;
                }
            }
        }
        $list = $query->paginate($limit)->toArray();
        //如果有根据普通品牌搜出标准品牌,那么还要补充数据显示
        if ($flag) {
            $list['data'] = array_map(function ($value) use ($searchBrandName) {
                $brandIds = StandardBrandMappingModel::where('standard_brand_id',
                    $value['brand_id'])->pluck('brand_id')->toArray();
                $brandNames = SpuBrandModel::whereIn('brand_id', $brandIds)->where('brand_name', 'like',
                    "%${searchBrandName}%")->limit(10)->pluck('brand_name')->toArray();
                //去除原始数据那些换行或者tab符号,原始数据是很乱的
                $brandNames = array_map(function ($value) {
                    return $value ? str_replace("\t", '', $value) : $value;
                }, $brandNames);
                $value['mapping_brand_names'] = $brandNames ? implode($brandNames, ' | ') : '-';
                $value['show_name'] = $value['brand_name'];
                return $value;
            }, $list['data']);
        } else {
            $list['data'] = array_map(function ($value) {
                $value['mapping_brand_names'] = '-';
                $value['show_name'] = $value['brand_name'];
                return $value;
            }, $list['data']);
        }

        return $list;
    }

    //获取供应商一开始给xm-select用的保存的品牌数据
    public function getBrandInitValue($brandIds)
    {
        if (!trim($brandIds, ',')) {
            return [];
        }
        $brandIds = explode(',', $brandIds);
        $brands = StandardBrandModel::whereIn('standard_brand_id', $brandIds)->select([
            'brand_name',
            'standard_brand_id as brand_id',
        ])->get();
        $brands = !empty($brands) ? $brands->toArray() : [];
        $brands = array_map(function ($brand) {
            $brand['show_name'] = $brand['brand_name'];
            $brand['mapping_brand_names'] = '-';
            return $brand;
        }, $brands);
        //还要遵循原始排序
        $result = [];
        foreach ($brandIds as $brandId) {
            foreach ($brands as $brand) {
                if ($brandId == $brand['brand_id']) {
                    $result[] = $brand;
                }
            }
        }
        return $result ?: [];
    }

    public function getBatchAddMainBrandsData($standardBrandNames)
    {
        $standardBrandNames = explode(',', trim($standardBrandNames, ','));
        $standardBrandIds = StandardBrandModel::whereIn('brand_name', $standardBrandNames)->pluck('standard_brand_id')->toArray();
        return $this->getBrandInitValue(implode(',',$standardBrandIds));
    }

    //根据品牌id获取标准品牌名字列表
    public function getStandardBrandNameListByBrandIds($brandIds)
    {
        $brandIds = explode(',', trim($brandIds, ','));
        if (empty($brandIds)) {
            return '';
        }
        $redis = Redis::connection();
        $brands = $redis->hmget('standard_brand', $brandIds);
        $standardBrandNameList = [];
        foreach ($brands as $brand) {
            $brand = json_decode($brand, true);
            $standardBrandNameList[] = $brand['brand_name'];
        }
        return $standardBrandNameList ? implode(',', $standardBrandNameList) : '';
    }

    public function checkStandardBrandNameList($standardBrandNameList = [])
    {
        //去数据库查询
        $validStandardBrandList =StandardBrandModel::whereIn('brand_name',
            $standardBrandNameList)
            ->pluck('brand_name', 'standard_brand_id')->toArray();
        $validStandardBrandMap = array_flip($validStandardBrandList);
        $invalidBrandNameList = [];
        $validStandardBrandNameList = [];
        $validStandardBrandIds = [];
        //判断哪些是错误的,哪些是正确的
        $redis = Redis::connection();
        foreach ($standardBrandNameList as $key => $standardBrandName) {
            if (in_array($standardBrandName, array_values($validStandardBrandList))) {
                $validStandardBrandIds[] = $validStandardBrandMap[$standardBrandName];
                $validStandardBrandNameList[] = $standardBrandName;
                unset($standardBrandNameList[$key]);
            }
        }
        //剩下没有能直接找到标准品牌的,先当作普通品牌处理,然后去找出标准品牌,如果还是找不到,那就是无效品牌了
        foreach ($standardBrandNameList as $key => $checkStandardBrandName) {
            //先去找对应的标准品牌
            $brandId = BrandModel::where('brand_name', $checkStandardBrandName)->value('brand_id');
            $standardBrandId = $redis->hget('standard_brand_mapping', $brandId);
            if (empty($standardBrandId)) {
                $invalidBrandNameList[] = $checkStandardBrandName;
                continue;
            }
            $standardBrand = $redis->hget('standard_brand', $standardBrandId);
            $standardBrand = json_decode($standardBrand, true);
            $standardBrandName = array_get($standardBrand, 'brand_name', '');
            $standardBrandId = array_get($standardBrand, 'standard_brand_id', '');
            if (empty($standardBrandName)) {
                $invalidBrandNameList[] = $checkStandardBrandName;
                continue;
            }
            $validStandardBrandIds[] = $standardBrandId;
            $validStandardBrandNameList[] = $standardBrandName;
        }
        //整合数据,返回标准的数据和无效的数据
        return [
            'invalid_brand_name_list' => $invalidBrandNameList,
            'valid_brand_name_list' => $validStandardBrandNameList,
            'valid_brand_ids' => $validStandardBrandIds,
        ];
    }
}