<?php


namespace App\Http\Services;

//后台用户相关信息服务
use App\Model\RedisModel;
use App\Model\SupplierBlacklistModel;
use App\Model\SupplierChannelModel;
use http\Exception\InvalidArgumentException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

//处理多个系统的图片替换问题
class DealImageService
{
    public static function getAllImage($text)
    {
        $pattern = '/<img [^>]*src\s*=\s*["\']?([^"\'>]*img\.ichunt\.com[^"\'>]*)/i';
        preg_match_all($pattern, $text, $matches);
        $imageUrls = $matches[1];

        $pattern = '/<img [^>]*src\s*=\s*["\']?([^"\'>]*file\.liexindev\.net[^"\'>]*)/i';
        preg_match_all($pattern, $text, $matches);
        $imageUrls = array_merge($imageUrls, $matches[1]);

        $pattern = '/<img [^>]*src\s*=\s*["\']?([^"\'>]*file\.ichunt\.net[^"\'>]*)/i';
        preg_match_all($pattern, $text, $matches);
        $imageUrls = array_merge($imageUrls, $matches[1]);

        return $imageUrls;
    }

    public static function checkImage($link)
    {
        if (strpos($link, 'img.ichunt.com') !== false || strpos($link, 'file.ichunt.net') !== false || strpos($link, 'file.liexindev.net') !== false) {
            return $link;
        } else {
            return '';
        }
    }

    //先去处理芯媒体的图片链接
    public static function dealNewsImage()
    {
        $newsList = DB::connection('liexin')->table('article')->orderBy('art_id', 'desc')->limit(1000)->get();
        $redis = new RedisModel();
        foreach ($newsList as $news) {
            $addon = DB::connection('liexin')->table('article_addon')->where('art_id', $news['art_id'])->first();
            if (empty($addon)) {
                continue;
            }
            $news = array_merge($news, $addon);
            if (!DB::connection('liexin')->table('article')->where('art_id', $news['art_id'])->exists()) {
                dump("不存在的文章");
                continue;
            }

            $imageUrls = self::getAllImage($news['body']);
            if (empty($imageUrls)) {
                continue;
            }
            if (!$redis->hget('image_news_backup_xian', $news['art_id'])) {
                $redis->hset('image_news_backup_xian', $news['art_id'], $news['body']);
            }
            //dump($imageUrls);  // 输出所有提取出的 'img.ichunt.com' 图片链接
            $imageMap = self::downloadAndUploadToPicServer($imageUrls);

            //进行全局替换
            foreach ($imageMap as $originImage => $newImage) {
                $news['body'] = str_replace($originImage, $newImage, $news['body']);
            }

            DB::connection('liexin')->table('article_addon')->where('art_id', $news['art_id'])->update([
                'body' => $news['body'],
            ]);

            // DB::connection('liexin')->table('article')->where('art_id', $news['art_id'])->update([
            //     'deal_status' => 1,
            // ]);


            dump('处理文章id : ' . $news['art_id']);

        }
    }

    //处理cms的图片链接
    public static function dealCmsImage()
    {
        $redis = new RedisModel();
        //先去找出所有带有图片的cms数据
        $bcatIdList = DB::connection('mysql')->table('lie_base_cat')->where('bcat_name', 'like', "%爱智%")->pluck('bcat_id');
        $baseList = DB::connection('mysql')->table('lie_base')->whereIn('bcat_id', $bcatIdList)->where('images', '!=', '')->limit(1000)->get();

        foreach ($baseList as $base) {
            $imageUrl = self::checkImage($base['images']);
            if (empty($imageUrl)) {
                continue;
            }
            if (!$redis->hget('image_cms_backup_xian', $base['base_id'])) {
                $redis->hset('image_cms_backup_xian', $base['base_id'], $base['images']);
            }
            $imageMap = self::downloadAndUploadToPicServer([$imageUrl]);
            //进行全局替换
            foreach ($imageMap as $originImage => $newImage) {
                $base['images'] = str_replace($originImage, $newImage, $base['images']);
            }
            dump($base['base_id']);
            //回写到数据库
            DB::connection('mysql')->table('lie_base')->where('base_id', $base['base_id'])->update([
                'images' => $base['images']
            ]);
        }
    }

    public static function replaceCmsImage()
    {
        $bcatIdList = DB::connection('mysql')->table('lie_base_cat')->where('bcat_name', 'like', "%爱智%")->pluck('bcat_id');
        $baseList = DB::connection('mysql')->table('lie_base')->whereIn('bcat_id', $bcatIdList)->where('images', '!=', '')->limit(1000)->get();
        foreach ($baseList as $base) {

            if (strpos($base['images'], 'imgscdn.ichunt.com/show/big') !== false || strpos($base['images'], 'image.liexindev.net/show/big') !== false) {
                $base['images'] = str_replace('big', 'origin', $base['images']);
                //回写到数据库
                DB::connection('mysql')->table('lie_base')->where('base_id', $base['base_id'])->update([
                    'images' => $base['images']
                ]);

            }
            dump($base['base_id']);
        }
    }

    //处理新闻的缩略图
    public static function dealNewsPic()
    {
        $newsList = DB::connection('liexin')->table('article')->orderBy('art_id', 'desc')->limit(20)->get();
        $redis = new RedisModel();
        foreach ($newsList as $news) {
            $imageUrl = self::checkImage($news['litpic']);
            if (empty($imageUrl)) {
                continue;
            }
            if (!$redis->hget('pic_news_backup_xian', $news['art_id'])) {
                $redis->hset('pic_news_backup_xian', $news['art_id'], $news['litpic']);
            }
            $imageMap = self::downloadAndUploadToPicServer([$imageUrl]);
            //进行全局替换
            foreach ($imageMap as $originImage => $newImage) {
                $news['litpic'] = str_replace($originImage, $newImage, $news['litpic']);
            }
            dump($news['art_id']);
            //回写到数据库
            DB::connection('liexin')->table('article')->where('art_id', $news['art_id'])->update([
                'litpic' => $news['litpic']
            ]);
        }
    }

    //处理sku详细描述
    public static function dealSkuDetailAndImage()
    {
        //先找出所有爱智的sku,按搜索的来
        //先去搜索找出所有华云的数据
        $data = self::searchIedgeSku();
        //获取总数
        $total = !empty($data['data']['total']) ? $data['data']['total'] : 0;
        if (!$total) {
            dump("找不到sku数据");
            return;
        }
        dump("需要处理的总数 : " . $total);
        $count = 0;
        $totalPage = (int)ceil($total / 20);

        $redis = new RedisModel();
        //进入修复循环
        for ($i = 1; $i <= $totalPage; $i = $i + 1) {
            $itemList = self::searchIedgeSku($i);
            if (empty($itemList['data']['goods_id'])) {
                continue;
            }
            foreach ($itemList['data']['goods_id'] as $skuId) {
                $skuDetail = DB::connection('mongo')->table('sku_detail')->where('sku_id', (string)$skuId)->first();
                $detail = $skuDetail['detail'];
                if (empty($detail)) {
                    continue;
                }
                //替换图片地址并且上传
                $imageUrls = self::getAllImage($detail);
                if (empty($imageUrls)) {
                    continue;
                }
                if (!$redis->hget('image_sku_detail_backup_xian', $skuId)) {
                    $redis->hset('image_sku_detail_backup_xian', $skuId, $detail);
                }
                //dump($imageUrls);  // 输出所有提取出的 'img.ichunt.com' 图片链接
                $imageMap = self::downloadAndUploadToPicServer($imageUrls);
                //进行全局替换
                foreach ($imageMap as $originImage => $newImage) {
                    $detail = str_replace($originImage, $newImage, $detail);
                }
                //回写到mongo
                DB::connection('mongo')->table('sku_detail')->where('sku_id', (string)$skuId)->update([
                    'update_time' => time(),
                    'detail' => $detail,
                ]);
            }
            //break;

            foreach ($itemList['data']['goods_id'] as $skuId) {
                //处理主图
                $dbInfo = getSpuSkuDb($skuId);
                $connection = DB::connection($dbInfo["db"]);
                $table = $dbInfo['table'];
                $selectFields = ['goods_images', 'goods_id'];
                $skuDBData = $connection->table($table)->select($selectFields)->where('goods_id', $skuId)->first();
                $imageUrl = self::checkImage($skuDBData['goods_images']);
                if (empty($imageUrl)) {
                    continue;
                }
                if (!$redis->hget('image_goods_backup_xian', $skuId)) {
                    $redis->hset('image_goods_backup_xian', $skuId, $skuDBData['goods_images']);
                }


                $imageMap = self::downloadAndUploadToPicServer([$imageUrl]);
                //进行全局替换
                foreach ($imageMap as $originImage => $newImage) {
                    $skuDBData['goods_images'] = str_replace($originImage, $newImage, $skuDBData['goods_images']);
                }
                $connection->table($table)->where('goods_id', $skuId)->update([
                    'goods_images' => $skuDBData['goods_images'],
                ]);
                dump($skuId);

                //redis也要修改
                $skuCache = json_decode($redis->hget('sku', $skuId), true);
                $skuCache['goods_images'] = $skuDBData['goods_images'];
                $redis->hset('sku', $skuId, json_encode($skuCache));
                $count++;
            }
        }
        dump('已处理sku数量 : ' . $count);

    }

    public static function getSearchDomain()
    {
        $host = request()->getHost();
        if (strpos($host, 'ichunt.net') !== false) {
            return 'https://icso.ichunt.com';
        } else {
            return 'http://search.liexindev.net';
        }
    }

    public static function searchIedgeSku($page = 1)
    {
        $url = self::getSearchDomain() . '/search/es/searchSku';
        $map['p'] = $page;
        $map['show_status'] = 1;

        $map['offset'] = 20;

        $map['supplier_id/sr'] = "gt,0";
        $map['admin'] = 1; // 后台搜索
        $map['no_rule'] = "1122"; // 后台搜索
        $map['org_id/eq'] = 3;
        $client = new \GuzzleHttp\Client();

        //$res = Http::get($url, $map)->body();
        //$data = json_decode($res, true);
        $response = $client->request('POST', $url, [
            'form_params' => $map
        ]);

        if ($response->getStatusCode() != 200) {
            throw new InvalidArgumentException('搜索服务不正常!');
        }

        $content = $response->getBody()->getContents();

        $content = json_decode($content, true);

        $code = array_get($content, 'error_code', -1);
        if ($code !== 0) {
            return [];
        }

        return $content;
    }

    //根据url下载图片并且上传到图片服务
    public static function downloadAndUploadToPicServer($urlList)
    {
        $imageMap = [];
        $path = '';
        foreach ($urlList as $url) {
            if (str_contains($url, 'comhttp')) {
                continue;
            }
            try {
                $info = pathinfo($url);
                $path = storage_path('logs/') . md5($url);
                $client = new \GuzzleHttp\Client();
                $response = $client->get($url);
                $contents = $response->getBody()->getContents();
                file_put_contents($path, $contents);

                //然后上传到图片服务器
                $response = $client->request('POST', env('IMAGE_SERVER_URL') . '/uploadImage?sys_type=5&create_uid=1000', [
                    'multipart' => [
                        [
                            'name' => 'file',
                            'contents' => fopen($url, 'r')
                        ]
                    ]
                ]);
                if ($response->getStatusCode() != 200) {
                    dump('上传网络错误');
                    continue;
                }

                $res = json_decode($response->getBody()->getContents(), true);
                if (isset($res['code'])) {
                    if ($res['code'] == 0) {
                        $ossFileUrl = $res['data']['oss_image_url'];
                        $imageMap[$url] = $ossFileUrl;
                    } else {
                        dump('上传服务接口返回错误 : ' . json_encode($res));
                        continue;
                    }
                } else {
                    dump('上传网络错误,返回不一致的响应 : ' . json_encode($res));
                    continue;
                }


            } catch (\Exception $exception) {
                dump("发生错误 : " . $exception->getMessage());
            } finally {
                if (file_exists($path)) {
                    //最后删除本地的文件
                    unlink($path);
                }

            }

        }
        return $imageMap;

    }
}