<?php

namespace App\Repositories;

use App\Models\CmsContentTemplate;
use App\Models\CmsContentTemplateSet;
use App\Models\CmsSubjectProduct;
use App\Models\CmsSubject;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Redis;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Tymon\JWTAuth\Facades\JWTAuth;

class CmsContentTemplateSetRepository
{
    public function __construct(CmsContentTemplateSet $cmsContentTemplateSet, CmsContentTemplate $cmsContentTemplate, CmsSubjectProduct $cmsSubjectProduct, CmsSubject $cmsSubject)
    {

        $this->cmsContentTemplateSet = $cmsContentTemplateSet;
        $this->cmsContentTemplate = $cmsContentTemplate;
        $this->cmsSubjectProduct = $cmsSubjectProduct;
        $this->cmsSubject = $cmsSubject;
    }

    /**
     * 内容预览
     */
    public function preview($request)
    {
        $where = [
            'city_id' => $request['city_id'],
            'apply_type' => $request['type'],
            'is_open' => 1,
            'status' => 1,
            'deleted_at' => null
        ];
        $temalates = $this->cmsContentTemplate->select('title', 'id')->where($where)->orderBy('id', 'desc')->first();
        if (!$temalates) {
            throw new HttpException(500, '没有找到对应模板');
        }

        $group_array = [];
        $group_key = config('constants.CMS_GROUP');
        $market_key = config('constants.CMS_MARKET');
        //团购首页
        if ($request['type'] == 0) {
            if (Cache::has($group_key)) {
                return Cache::store('redis')->get($group_key);
            }
            $group_array['apply_type'] = "group";
            $group_array['title'] = $temalates->title;
            $group_array['content'] = [];
        } else {//菜市场首页
            if (Cache::has($market_key)) {
                return Cache::store('redis')->get($market_key);
            }
            $group_array['apply_type'] = "market";
            $group_array['title'] = $temalates->title;
            $group_array['content'] = [];
        }

        $group_array['content'][0]['area_type'] = "banner";

        $banner_rule = $this->cmsContentTemplateSet->select('id', 'rule')->where(['tpl_id' => $temalates->id, 'area_type' => 0, 'status' => 1])->get();
        $new_rule = [];
        foreach ($banner_rule->toArray() as $k => $v) {
            $decode_banner = \GuzzleHttp\json_decode($v['rule'], true);
            if (count($decode_banner) > 0) {
                foreach ($decode_banner as $key => $value) {
                    $new_rule[$key]['id'] = $key;
                    $new_rule[$key]['rule'] = $value;
                    $new_rule[$key]['rule']['b_id'] = strval($v['id']);
                    $new_rule[$key]['rule']['link_url'] = strval($value['link_url']);//强转link_url类型
                }
            }
        }
        $group_array['content'][0]['rule'] = $new_rule;

        $subject_rule = $this->cmsContentTemplateSet->select('id', 'rule')->where(['tpl_id' => $temalates->id, 'area_type' => 1, 'status' => 1])->get();

        $new_rule1 = [];
        foreach ($subject_rule->toArray() as $k => $v) {
            $new_rule1[$k]['id'] = $v['id'];
            $decode_subject = \GuzzleHttp\json_decode($v['rule'], true);
            $decode_subject['link_url'] = strval($decode_subject['link_url']);//强转link_url类型
            $new_rule1[$k]['rule'] = $decode_subject;
        }

        $floor_rule = $this->cmsContentTemplateSet->select('id', 'rule')->where(['tpl_id' => $temalates->id, 'area_type' => 2, 'status' => 1])->get();
        $new_rule2 = [];
        foreach ($floor_rule->toArray() as $k => $v) {
            $new_rule2[$k]['id'] = $v['id'];
            $decode_floor = \GuzzleHttp\json_decode($v['rule'], true);
            $decode_floor['link_url'] = strval($decode_floor['link_url']);//强转link_url类型
            $new_rule2[$k]['rule'] = $decode_floor;
        }

        foreach ($new_rule2 as $k => $v) {
            if ($v) {
                $rules = $v['rule'];
                $show_num = intval($rules['show_num']);
                $show_type = $this->cmsSubject->select('show_type')->where('id', $rules['link_url'])->first();
                $product = $this->cmsSubjectProduct->where('subject_id', $rules['link_url'])->orderBy('sort', 'asc')->limit($show_num)->get();
                $pro_array = $product->toArray();
                $res_id = implode(",", array_column($pro_array, 'product_id'));
                $new_rule2[$k]['product_id'] = $res_id;
                $new_rule2[$k]['subject_id'] = strval($rules['link_url']);
                $new_rule2[$k]['show_type'] = $show_type->show_type ?? '';
                unset($v['url']);
                unset($v['show_num']);
                unset($rules['link_url']);
                unset($v['link_type']);
            }
        }

        if ($request['type'] == 1) {
            $group_array['content'][1]['area_type'] = "category";
            $category_rule = $this->cmsContentTemplateSet->select('id', 'rule')->where(['tpl_id' => $temalates->id, 'area_type' => 3, 'status' => 1])->get();
            $new_rule3 = [];
            foreach ($category_rule->toArray() as $k => $v) {
                $new_rule3[$k]['id'] = $v['id'];
                $decode_category = \GuzzleHttp\json_decode($v['rule'], true);
                $decode_category['link_url'] = strval($decode_category['link_url']);//强转link_url类型
                $new_rule3[$k]['rule'] = $decode_category;
            }

            $group_array['content'][1]['rule'] = $new_rule3;
            $group_array['content'][2]['area_type'] = "special";
            $group_array['content'][2]['rule'] = $new_rule1;
            $group_array['content'][3]['area_type'] = "floor";
            $group_array['content'][3]['rule'] = $new_rule2;

            if (!Cache::has($market_key)) {
                Cache::store('redis')->put($market_key, $group_array, 600);//10分钟过期
            }

        } else {
            $group_array['content'][1]['area_type'] = "special";
            $group_array['content'][1]['rule'] = $new_rule1;
            $group_array['content'][2]['area_type'] = "floor";
            $group_array['content'][2]['rule'] = $new_rule2;

            if (!Cache::has($group_key)) {
                Cache::store('redis')->put($group_key, $group_array, 600);
            }
        }
        return $group_array;
    }

    public function getTemplate($cityId)
    {
        return $this->cmsContentTemplate->where(['city_id' => $cityId, 'is_open' => 1, 'status' => 1])->where('deleted_at', null)->select('id', 'title', 'apply_type')->orderBy('apply_type', 'asc')->get();
    }

    public function productList($request)
    {
        $product = $this->cmsSubjectProduct->where('subject_id', $request['subject_id'])->orderBy('sort', 'asc')->get();
        $pro_array = $product->toArray();
        $res_id = implode(",", array_column($pro_array, 'product_id'));

        try {
            $sign = generateSign(['ids' => $res_id], config('customer.app_secret'));
            $url = config("customer.app_service_url") . '/product/homeProduct';
            $array = [
                'json' => ['sign' => $sign, 'ids' => $res_id], 'query' => [], 'http_errors' => false, 'headers' => ['Authorization' => "Bearer " . JWTAuth::getToken()]
            ];

            return http($url, $array, 'get');
        } catch (\Exception $e) {
            return [];
        }

    }

    /**
     * 内容预览
     */
    public function exchangeMall($request)
    {
        $where = [
            'city_id' => 0,
            'apply_type' => 2,
            'is_open' => 1,
            'status' => 1,
            'deleted_at' => null
        ];
        $temalates = $this->cmsContentTemplate->select('title', 'id')->where($where)->orderBy('id', 'desc')->first();
        if (!$temalates) {
            throw new HttpException(500, '没有找到对应模板');
        }

        $group_array = [];
        $group_array['apply_type'] = "exchangeMall";
        $group_array['title'] = $temalates->title;
        $group_array['content'] = [];
        $exchange_key = config('constants.CMS_EXCHANGE');
        if (Cache::has($exchange_key)) {
            return Cache::store('redis')->get($exchange_key);
        }

        $banner_rule = $this->cmsContentTemplateSet->select('id', 'rule')->where(['tpl_id' => $temalates->id, 'area_type' => 0, 'status' => 1])->limit(1)->first();
        $new_rule = [];
        if (isset($banner_rule->rule)){
            $decode_banner = \GuzzleHttp\json_decode($banner_rule->rule, true);
            if (count($decode_banner) > 0){
                foreach ($decode_banner as $key => $value) {
                    $new_rule[$key]['url'] = $value['url'];
                    $new_rule[$key]['link_url'] = $value['link_url'];
                    $new_rule[$key]['link_type'] = $value['link_type'];
                }
            }
            $group_array['content'][0]['area_type'] = "banner";
            $group_array['content'][0]['id'] = $banner_rule->id ?? 0;
            $group_array['content'][0]['rule'] = $new_rule;
        }

        $all_subject = $this->cmsContentTemplateSet->select('id', 'rule', 'sort', 'name', 'floor_img', 'area_type')->where(['tpl_id' => $temalates->id, 'status' => 1])->whereIn('area_type', [4, 5])->orderBy('sort', 'asc')->get();
        $all_subject = $all_subject->toArray();
        $count = count($all_subject);
        $new_rule = [];
        foreach ($all_subject as $k => $v) {
            $decode_subject = \GuzzleHttp\json_decode($v['rule'], true);
            if (count($decode_subject) > 0) {
                if ($v['area_type'] == 4) {
                    $new_rule[$k]['area_type'] = "subject_one";
                } else {
                    $new_rule[$k]['area_type'] = "subject_two";
                }
                $new_rule[$k]['floor_img'] = $v['floor_img'];
                $new_rule[$k]['id'] = intval($v['id']);
                $new_rule[$k]['rule'] = $decode_subject;
            }
        }
        foreach ($new_rule as $k => $v) {
            $group_array['content'][$k + 1]['area_type'] = $new_rule[$k]['area_type'];
            $group_array['content'][$k + 1]['id'] = $new_rule[$k]['id'];
            $group_array['content'][$k + 1]['floor_img'] = $new_rule[$k]['floor_img'];
            $group_array['content'][$k + 1]['rule'] = $new_rule[$k]['rule'];
        }

        $floor_rule = $this->cmsContentTemplateSet->select('id', 'rule')->where(['tpl_id' => $temalates->id, 'area_type' => 2, 'status' => 1])->orderBy('id', 'asc')->get();
        $new_rule = [];
        foreach ($floor_rule->toArray() as $key => $val) {
            $rule = \GuzzleHttp\json_decode($val['rule'], true);
            if (count($rule) > 0) {
                $show_type = $this->cmsSubject->select('show_type')->where('id', intval($rule['link_url']))->first();
                $product = $this->cmsSubjectProduct->where('subject_id', intval($rule['link_url']))->orderBy('sort', 'asc')->get();
                $pro_array = $product->toArray();
                $res_id = implode(",", array_column($pro_array, 'product_id'));
                $get_product = $this->get_product($res_id);
                if ($get_product['products']){
                    $get_product['products'] = array_slice($get_product['products'],0,20);//楼层仅展示20个商品
                }
                $new_rule[$key]['id'] = $val['id'];
                $new_rule[$key]['show_type'] = intval($show_type->show_type) ?? '';
                $new_rule[$key]['url'] = $rule['url'];
                $new_rule[$key]['link_url'] = intval($rule['link_url']);
                $new_rule[$key]['link_type'] = $rule['link_type'];
                $new_rule[$key]['rule'] = $get_product['products'] ?? [];
            }
        }
        foreach ($new_rule as $key => $val) {
            $group_array['content'][$count + $key + 1]['area_type'] = "floor";
            $group_array['content'][$count + $key + 1]['id'] = $val['id'];
            $group_array['content'][$count + $key + 1]['show_type'] = $val['show_type'];
            $group_array['content'][$count + $key + 1]['floor_img'] = $val['url'];
            $group_array['content'][$count + $key + 1]['link_url'] = $val['link_url'];
            $group_array['content'][$count + $key + 1]['link_type'] = $val['link_type'];
            $group_array['content'][$count + $key + 1]['rule'] = $val['rule'];
        }

        if (!Cache::has($exchange_key)) {
            Cache::store('redis')->put($exchange_key, $group_array, 600);//10分钟过期
        }

        return $group_array;
    }

    function get_product($res_id)
    {
        try {
            $sign = generateSign(['ids' => $res_id], config('customer.app_secret'));
            $url = config("customer.app_service_url") . '/product/exchange/subject';
            $array = [
                'json' => ['sign' => $sign, 'ids' => $res_id], 'query' => [], 'http_errors' => false, 'headers' => ['Authorization' => "Bearer " . JWTAuth::getToken()]
            ];

            return http($url, $array, 'get');
        } catch (\Exception $e) {
            return [];
        }
    }

    public function getProducts($request)
    {
        $product = $this->cmsSubjectProduct->where('subject_id', $request['subject_id'])->orderBy('sort', 'asc')->get();
        $pro_array = $product->toArray();
        $res_id = implode(",", array_column($pro_array, 'product_id'));

        $product_key = config('constants.CMS_PRODUCTS');
        $product_key = sprintf($product_key,md5($res_id));
        if (Cache::has($product_key)) {
            return Cache::store('redis')->get($product_key);
        }

        try {
            if (isset($request['field_order'])) {
                $field_order = $request['field_order'];
                $sign = generateSign(['ids' => $res_id, 'field_order' => $field_order], config('customer.app_secret'));
                $array = [
                    'json' => ['sign' => $sign, 'ids' => $res_id, 'field_order' => $field_order], 'query' => [], 'http_errors' => false, 'headers' => ['Authorization' => "Bearer " . JWTAuth::getToken()]
                ];
            } else {
                $sign = generateSign(['ids' => $res_id], config('customer.app_secret'));
                $array = [
                    'json' => ['sign' => $sign, 'ids' => $res_id], 'query' => [], 'http_errors' => false, 'headers' => ['Authorization' => "Bearer " . JWTAuth::getToken()]
                ];
            }

            $url = config("customer.app_service_url") . '/product/exchange/subject';
            $http = http($url, $array, 'get');
            if (!Cache::has($product_key)) {
                Cache::store('redis')->put($product_key, $http, 600);//10分钟过期
            }
            return $http;

        } catch (\Exception $e) {
            return [];
        }
    }
}