<?php
/**
 * Created by PhpStorm.
 * User: ywl
 * Date: 2017/4/14
 * Time: 11:38
 */

namespace App\Web\Services;


use App\Ad\Facades\SysAdFacade;
use App\Common\Facades\UserCenterFacade;
use App\Common\Library\DES;
use App\Common\Models\ExportExcel;
use App\ExcelData\Services\ImportHeadingExcel;
use App\Exceptions\ApiException;
use App\Services\CommonUserBaseService;
use App\Web\Facades\BlogFacade;
use App\Web\Facades\BlogRenderFacade;
use App\Web\Facades\DictFacade;
use App\Web\Facades\HelpFacade;
use App\Web\Facades\MeetingFacade;
use App\Web\Facades\ProductFacade;
use App\Web\Facades\SuccessCaseFacade;
use App\Web\Facades\SysGlobalConfigFacade;
use App\Web\Facades\WebFacade;
use App\Web\Models\BlogModel;
use App\Web\Models\BlogPlateModel;
use App\Web\Models\HelpModel;
use App\Web\Models\ProductModel;
use App\Web\Models\SuccessCaseModel;
use App\Web\Models\WebSeoModel;
use App\Web\Models\WebStaticPageModel;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\View;
use Maatwebsite\Excel\Events\AfterSheet;
use Maatwebsite\Excel\Facades\Excel;
use PhpOffice\PhpSpreadsheet\Style\Fill;


class WebService extends CommonUserBaseService
{
    const RELATION_TABLE_BLOG = 'blog';
    const RELATION_TABLE_SUCCESS_CASE = 'success_case';
    const RELATION_TABLE_HELP = 'help';
    const RELATION_TABLE_WEB_PAGE = 'web_static_page';
    const RELATION_TABLE_BLOG_PLATE = 'blog_plate';
    const RELATION_TABLE_BLOG_TYPE = 'blog_type';
    const RELATION_TABLE_BLOG_TAG = 'blog_tag';
    const RELATION_TABLE_HELP_TYPE = 'help_type';
    const RELATION_TABLE_HELP_TAG = 'help_tag';
    const RELATION_TABLE_PRODUCT = 'product';
    const RELATION_TABLE_PRODUCT_TYPE = 'product_type';
    const RELATION_TABLE_PRODUCT_TAG = 'product_tag';
    const RELATION_TABLE_MEETING = 'meeting';
    const RELATION_TABLE_MEETING_TYPE = 'meeting_type';
    const RELATION_TABLE_MEETING_TAG = 'meeting_tag';
    const BLOG_ROUTE_PATH = 'blog-details.index';
    const BLOG_JOB_ROUTE_PATH = 'join-us-details.index';
    const BLOG_TYPE_LIST_ROUTE_PATH = 'blog-list.index';
    const BLOG_TYPE_SOLUTIONS_ROUTE_PATH = 'solution-list.index';
    const BLOG_TYPE_VIDEO_ROUTE_PATH = 'video-list.index';
    const CASE_List_ROUTE_PATH = 'case-list.index'; // 成功案例列表页
    const CASE_ROUTE_PATH = 'case-details.index';  // 成功案例详情页
    const HELP_ROUTE_PATH = 'help-details.index';
    const SOLUTION_DETAILS_ROUTE_PATH = 'solution-details.index';
    const MEDIA_ROUTE_PATH = 'media-details.index';
    const HELP_TYPE_LIST_ROUTE_PATH = 'support-details.index';

    const TOURISM_DETAILS_ROUTE_PATH = 'tourism-details.index';
    const KNOWLEDGE_DETAILS_PATH = 'knowledge-details.index';
    const PRODUCT_LIST_ROUTE_PATH = 'product-list.index';
    const PRODUCT_ROUTE_PATH = 'product-details.index';
    const MEETING_LIST_ROUTE_PATH = 'events.index';
    const MEETING_ROUTE_PATH = 'event-details.index';
    const MEETING_SPEAKER_ROUTE_PATH = 'guest-speaker.index'; //会议嘉宾页
    const LAYOUTS_ROUTE = 'layouts.index';
    const LAYOUT_HEADER_MENU_ROUTE = 'layout_menu.index';
    const HOME_ROUTE = 'home.index';
    protected $cache = true;
    protected $cacheBucket = 'Web:';
    protected $webSeoModel;

    /**
     * WebService construct
     * @param WebStaticPageModel $model
     * @param WebSeoModel $webSeoModel
     * */
    public function __construct(WebStaticPageModel $model, WebSeoModel $webSeoModel)
    {
        $this->model = $model;
        $this->webSeoModel = $webSeoModel;
    }

    /**
     * 保存静态页面数据
     * */
    public function saveStaticPageData($params)
    {
        $saveData = [];
        $userId = $this->getAuthUserId();
        $nowTime = nowTime();
        $seoData = empty($params['seo_data']) ? [] : $params['seo_data'];
        $urlaId = empty($params['seo_id']) ? 0 : $params['seo_id'];
        if (!empty($seoData)) {
            if (empty($seoData['urla']) && !empty($params['route_path'])) {
                $seoData['urla'] = $params['route_path'];
            }
            $urlaUnique = $this->checkUrlaUnique($seoData['urla'], $urlaId);
            if (!$urlaUnique) {
                throw new ApiException(10019, ['name' => $seoData['urla']]);
            }
        }
        $saveData['update_time'] = $nowTime;
        if (!empty($params['id'])) {
            $saveData['id'] = $params['id'];
            if (isset($params['page_name'])) {
                $pageNameUnique = $this->model->checkPageNameUnique($params['page_name'], $params['id']);
                if (!$pageNameUnique) {
                    throw new ApiException(10018, ['name' => $params['page_name']]);
                }
                $saveData['page_name'] = $params['page_name'];
            }
            /*if (isset($params['route_path'])) {
                $routePathUnique = $this->model->checkPageNameUnique($params['route_path'], $params['id']);
                if (!$routePathUnique) {
                    throw new ApiException(10018, ['name' => $params['route_path']]);
                }
                $saveData['route_path'] = $params['route_path'];
            }*/
            if (isset($params['sort'])) {
                $saveData['sort'] = empty($params['sort']) ? 0 : $params['sort'];
            }
            if (isset($params['status'])) {
                $saveData['status'] = $params['status'];
            }
            if (isset($params['type'])) {
                $saveData['type'] = empty($params['type']) ? 0 : $params['type'];
            }
            if (isset($params['page_content'])) {
                $saveData['page_content'] = empty($params['page_content']) ? '' : json_encode($params['page_content']);
            }
        } else {
            $pageNameUnique = $this->model->checkPageNameUnique($params['page_name']);
            if (!$pageNameUnique) {
                throw new ApiException(10018, ['name' => $params['page_name']]);
            }
            /*$routePathUnique = $this->model->checkRoutePathUnique($params['route_path']);
            if (!$routePathUnique) {
                throw new ApiException(10018, ['name' => $params['route_path']]);
            }*/
            $saveData['type'] = empty($params['type']) ? 0 : $params['type'];
            $saveData['user_id'] = $userId;
            $saveData['page_name'] = $params['page_name'];
            $saveData['route_path'] = $params['route_path'];
            $saveData['sort'] = empty($params['sort']) ? 0 : $params['sort'];
            $saveData['page_content'] = empty($params['page_content']) ? '' : json_encode($params['page_content']);
            $saveData['create_time'] = $nowTime;
        }
        $id = $this->model->saveStaticPageData($saveData);
        if (!empty($id)) {
            if (!empty($params['seo_data'])) {
                if (empty($seoData['urla']) && !empty($params['route_path'])) {
                    $seoData['urla'] = $params['route_path'];
                }
                $seoParams = [];
                $seoParams['relation_table'] = self::RELATION_TABLE_WEB_PAGE;
                $seoParams['relation_id'] = $id;
                $seoParams['urla'] = $seoData['urla'];
                $seoParams['seo_title'] = $seoData['seo_title'];
                $seoParams['seo_keyword'] = $seoData['seo_keyword'];
                $seoParams['seo_describe'] = $seoData['seo_describe'];
                $seoParams['track_code_head'] = empty($seoData['track_code_head']) ? '' : $seoData['track_code_head'];
                $seoParams['track_code_body'] = empty($seoData['track_code_body']) ? '' : $seoData['track_code_body'];
                if (empty($urlaId)) {
                    $seoParams['user_id'] = $userId;
                    $urlaId = $this->saveSeoData($seoParams);
                    $this->model->newInstance()->where('id', '=', $id)->update(['seo_id' => $urlaId]);
                } else {
                    $seoParams['id'] = $urlaId;
                    $urlaId = $this->saveSeoData($seoParams);
                }
            }
            if (!empty($saveData['status']) && $saveData['status'] == 2) {
                //移除对应seo
                $delSeoParams = [];
                $delSeoParams['relation_table'] = WebService::RELATION_TABLE_WEB_PAGE;
                $delSeoParams['relation_id'] = $id;
                $ret = $this->delSeoByRelation($delSeoParams);
            }
        }
        //编辑静态页面后清除静态页面缓存
        $this->clearPageCache('urla');
        return $id;
    }

    /**
     * 检查优化连接时候唯一
     * */
    public function checkUrlaUnique($urla, $id = 0)
    {
        return $this->webSeoModel->checkUrlaUnique($urla, $id);
    }

    /**
     * 保存seo数据
     * */
    public function saveSeoData($params)
    {
        $saveData = [];
        $nowTime = nowTime();
        $saveData['update_time'] = $nowTime;
        if (!empty($params['id'])) {
            $info = $this->webSeoModel->selectRaw('urla')->where('id', '=', $params['id'])->first();

            $saveData['id'] = $params['id'];
            if (isset($params['seo_title'])) {
                $saveData['seo_title'] = empty($params['seo_title']) ? '' : $params['seo_title'];
            }
            if (isset($params['seo_keyword'])) {
                $saveData['seo_keyword'] = empty($params['seo_keyword']) ? '' : $params['seo_keyword'];
            }
            if (isset($params['seo_describe'])) {
                $saveData['seo_describe'] = empty($params['seo_describe']) ? '' : $params['seo_describe'];
            }
            if (isset($params['track_code_head'])) {
                $saveData['track_code_head'] = empty($params['track_code_head']) ? '' : $params['track_code_head'];
            }
            if (isset($params['track_code_body'])) {
                $saveData['track_code_body'] = empty($params['track_code_body']) ? '' : $params['track_code_body'];
            }
            if (isset($params['relation_table'])) {
                $saveData['relation_table'] = empty($params['relation_table']) ? '' : $params['relation_table'];
            }
            if (isset($params['urla'])) {
                $saveData['urla'] = empty($params['urla']) ? '' : $params['urla'];
            }
        } else {
            $saveData['urla'] = $params['urla'];
            $saveData['user_id'] = empty($params['user_id']) ? 0 : $params['user_id'];
            $saveData['relation_table'] = empty($params['relation_table']) ? '' : $params['relation_table'];
            $saveData['relation_id'] = empty($params['relation_id']) ? 0 : $params['relation_id'];
            $saveData['seo_title'] = empty($params['seo_title']) ? '' : $params['seo_title'];
            $saveData['seo_keyword'] = empty($params['seo_keyword']) ? '' : $params['seo_keyword'];
            $saveData['seo_describe'] = empty($params['seo_describe']) ? '' : $params['seo_describe'];
            $saveData['track_code_head'] = empty($params['track_code_head']) ? '' : $params['track_code_head'];
            $saveData['track_code_body'] = empty($params['track_code_body']) ? '' : $params['track_code_body'];
            $saveData['create_time'] = $nowTime;
        }
        $ret = $this->webSeoModel->saveSeoData($saveData);
        return $ret;
    }

    /**
     * 根据关联关系删除Seo
     * */
    public function delSeoByRelation($params)
    {
        $ret = $this->webSeoModel->delSeoByRelation($params);
        return $ret;
    }

    /**
     * 清除详情详情页面缓存
     * */
    public function clearPageCache($clearKey = '')
    {
        if (!empty($clearKey)) {
            $this->removeByKey($clearKey);
        }
    }

    /**
     * 获取静态页面列表
     * */
    public function getStaticPageList($params)
    {
        $pageList = $this->model->getStaticPageList($params);
        $pageListData = empty($pageList['data']) ? [] : $pageList['data'];
        $pageList['data'] = $pageListData;
        return $pageList;
    }

    /**
     * 根据seoids 获取seo列表
     * */
    public function getSeoListByIds($ids)
    {
        if (!empty($ids)) {
            $seoList = $this->webSeoModel->getSeoListByIds($ids);
        } else {
            $seoList = [];
        }
        return $seoList;
    }

    /**
     * 获取静态页面详情
     * */
    public function getStaticPageInfo($params)
    {
        $pageInfo = $this->model->getStaticPageInfo($params);
        if (!empty($pageInfo['seo_id'])) {
            $pageInfo['seo_data'] = $this->getSeoInfo(['id' => $pageInfo['seo_id']]);
        } else {
            $pageInfo['seo_data'] = [];
        }
        /*if (!empty($pageInfo['page_content']) && is_array($pageInfo['page_content'])) {
            $pageInfo['page_content'] = array_values($pageInfo['page_content']);
        } else {
            $pageInfo['page_content'] = [];
        }*/
        return $pageInfo;
    }

    /**
     * 获取seo详情
     * */
    public function getSeoInfo($params)
    {
        return $this->webSeoModel->getSeoInfo($params);
    }

    /**
     * 获取网页菜单
     * */
    public function getPageMenuInfo($params)
    {
        /*if (!empty($pageInfo['page_content']) && is_array($pageInfo['page_content'])) {
            $pageInfo['page_content'] = array_values($pageInfo['page_content']);
        } else {
            $pageInfo['page_content'] = [];
        }*/
        return $this->model->getPageMenuInfo($params);
    }

    /**
     * 获取获取页面渲染数据
     * */
    public function getWebPageRenderData($urla = '')
    {
        //$pageRenderData = $this->getCachePageData($urla);
        if (config('app.app_debug')) {
            $pageRenderData = [];
        }
        $pageRenderData = [];
        if (empty($pageRenderData)) {
            if (empty($urla) || $urla == 'home') {
                //首页
                $pageRenderData = $this->model->getStaticPageInfo(['route_path' => self::HOME_ROUTE]);
                $layoutContent = $this->model->getStaticPageInfo(['route_path' => self::LAYOUTS_ROUTE]);
                if (!empty($layoutContent['page_content'])) {
                    foreach ($layoutContent['page_content'] as $key => $content_item) {
                        if (empty($pageRenderData['page_content'][$key])) {
                            $pageRenderData['page_content'][$key] = $content_item;
                        }
                    }
                }
            } else {
                $seoParams = [];
                $seoParams['urla'] = $urla;
                $seoInfo = $this->webSeoModel->getSeoInfo($seoParams);
                if (!empty($seoInfo)) {
                    $pageRenderData = [];
                    $pageRenderData['urla'] = $seoInfo['urla'];
                    $pageRenderData['seo_title'] = $seoInfo['seo_title'];
                    $pageRenderData['seo_keyword'] = $seoInfo['seo_keyword'];
                    $pageRenderData['seo_describe'] = $seoInfo['seo_describe'];
                    $pageRenderData['track_code_head'] = $seoInfo['track_code_head'];
                    $pageRenderData['track_code_body'] = $seoInfo['track_code_body'];
                    $pageRenderData['relation_table'] = $seoInfo['relation_table'] ?? '';
                    $pageRenderData['relation_id'] = $seoInfo['relation_id'] ?? 0;
//                    dd($urla);
/*                    if ($urla === 'gahumi-custom-advertising-flag70d-6') {
                        dd($pageRenderData);
                    }*/
                    if ($pageRenderData['relation_table']) {
                        switch ($pageRenderData['relation_table']) {
                            case self::RELATION_TABLE_BLOG_TYPE:
                                //新闻分类列表
                                $pageRenderData['blog_type_info'] = BlogRenderFacade::getBlogTypeInfo($seoInfo['relation_id']);
                                if (!empty($pageRenderData['blog_type_info']['plate_id'])) {
                                    if ($pageRenderData['blog_type_info']['plate_id'] === BlogPlateModel::SOLUTION) {
                                        $pageRenderData['route_path'] = self::BLOG_TYPE_SOLUTIONS_ROUTE_PATH;
                                        $pageRenderData['solution_tag_list'] = BlogRenderFacade::getPublishedTagList(BlogPlateModel::SOLUTION);
                                    }if ($pageRenderData['blog_type_info']['plate_id'] === BlogPlateModel::SUCCESSCASES) {
                                        $pageRenderData['route_path'] = self::CASE_List_ROUTE_PATH;
                                        $pageRenderData['tag_list'] = BlogRenderFacade::getPublishedTagList(BlogPlateModel::SUCCESSCASES);
                                    } else {
                                        $pageRenderData['route_path'] = self::BLOG_TYPE_LIST_ROUTE_PATH;
                                    }
                                } else {
                                    $pageRenderData['route_path'] = self::BLOG_TYPE_LIST_ROUTE_PATH;
                                }
                                break;
                            case self::RELATION_TABLE_BLOG_TAG:
                                //新闻标签列表
                                $pageRenderData['blog_tag_info'] = BlogRenderFacade::getBlogTagInfo($seoInfo['relation_id']);
                                $pageRenderData['route_path'] = self::BLOG_TYPE_LIST_ROUTE_PATH;
                                break;
                            case self::RELATION_TABLE_BLOG:
                                //博客详情
                                $blogData = BlogFacade::getBlogRenderData(['id' => $seoInfo['relation_id']]);
                                $blogData['plate_info'] = BlogRenderFacade::getPlateInfo($blogData['plate_id']);
                                $blogData['expand_content'] = mapByKey($blogData['expand_content'], 'key');
                                if ($blogData['plate_id'] === BlogPlateModel::JOB) {
                                    $pageRenderData['route_path'] = self::BLOG_JOB_ROUTE_PATH;
                                } else if ($blogData['plate_id'] === BlogPlateModel::KNOWLEDGECENTRE) {
                                    $pageRenderData['route_path'] = self::KNOWLEDGE_DETAILS_PATH;
                                } else if ($blogData['plate_id'] === BlogPlateModel::SOLUTION) {
                                    $pageRenderData['route_path'] = self::SOLUTION_DETAILS_ROUTE_PATH;
                                    $pageRenderData['solution_tag_list'] = BlogRenderFacade::getPublishedTagList(BlogPlateModel::SOLUTION);
                                } else if ($blogData['plate_id'] === BlogPlateModel::Media) {
                                    $pageRenderData['route_path'] = self::MEDIA_ROUTE_PATH;
                                } else if ($blogData['plate_id'] === BlogPlateModel::SUCCESSCASES) {
                                    $pageRenderData['route_path'] = self::CASE_ROUTE_PATH;
                                }  else if ($blogData['plate_id'] === BlogPlateModel::Q_AND_A) {
                                    $pageRenderData['route_path'] = self::HELP_ROUTE_PATH;
                                }   else if ($blogData['plate_id'] === BlogPlateModel::TOURISM) {
                                    $pageRenderData['route_path'] = self::TOURISM_DETAILS_ROUTE_PATH;
                                }  else {
                                    $pageRenderData['route_path'] = self::BLOG_ROUTE_PATH;
                                }

                                $blogData['pre_news_info'] = BlogRenderFacade::getPreBlog($blogData['plate_id'], $blogData['id']);
                                $blogData['next_news_info'] = BlogRenderFacade::getNextBlog($blogData['plate_id'], $blogData['id']);
                                $pageRenderData['blog_details'] = $blogData;
                                break;
                            case self::RELATION_TABLE_PRODUCT_TYPE:
                                //产品分类列表
                                $pageRenderData['product_type_info'] = ProductFacade::getProductTypeRenderInfo(['id' => $seoInfo['relation_id']]);
                                $pageRenderData['product_type_info']['id'] = $seoInfo['relation_id'];
                                if (!empty($pageRenderData['product_type_info']['expand_content'])) {
                                    $pageRenderData['product_type_info']['expand_content'] = mapByKey(json_decode($pageRenderData['product_type_info']['expand_content'], true), 'key');
                                }
                                $pageRenderData['route_path'] = self::PRODUCT_LIST_ROUTE_PATH;
                                break;
                            case self::RELATION_TABLE_PRODUCT_TAG:
                                //产品标签列表
                                $pageRenderData['product_tag_info'] = ProductFacade::getProductTagRenderInfo(['tag_id' => $seoInfo['relation_id']]);
                                $pageRenderData['product_tag_info']['id'] = $seoInfo['relation_id'];
                                if (!empty($pageRenderData['product_tag_info']['expand_content'])) {
                                    $pageRenderData['product_tag_info']['expand_content'] = mapByKey(json_decode($pageRenderData['product_tag_info']['expand_content'], true), 'key');
                                }
                                if (!empty($pageRenderData['product_tag_info']['route_path'])) {
                                    $pageRenderData['route_path'] = $pageRenderData['product_tag_info']['route_path'];
                                } else {
                                    $pageRenderData['route_path'] = self::PRODUCT_LIST_ROUTE_PATH;
                                }
                                break;
                            case self::RELATION_TABLE_PRODUCT:
                                //产品详情
                                $pageRenderData['route_path'] = self::PRODUCT_ROUTE_PATH;
                                $productData = ProductFacade::getProductRenderData(['id' => $seoInfo['relation_id']]);
                                $pageRenderData['product_detail'] = $productData;
                                $typeIds = [];
                                if (!empty($productData['type_items'])) {
                                    foreach ($productData['type_items'] as $typeItem) {
                                        $typeIds[] = $typeItem['type_id'];
                                    }
                                }
                                $relevanceList = ProductFacade::getRelevanceList(['relevance_page_size' => 4, 'type_ids' => $typeIds]);
                                $pageRenderData['relevance_product_list'] = $relevanceList;
                                break;
                            case self::RELATION_TABLE_MEETING:
                                //会议详情
                                $meetingInfo = MeetingFacade::getMeetingRenderData(['id' => $seoInfo['relation_id']]);
                                $meetingInfo['relation_table'] = self::RELATION_TABLE_MEETING;
                                $routePath = self::MEETING_ROUTE_PATH;
                                if(!empty($meetingInfo['tag_items'])) {
                                    $tagIds = array_column($meetingInfo['tag_items'], 'tag_id');
                                    if(View::exists('exhibition-detail.index') && in_array(1, $tagIds)) {
                                        //todo 临时定义tag，标签为1的为全球展会
                                        $routePath = 'exhibition-detail.index';
                                    }
                                }
                                if (!empty($meetingInfo['expand_content'])) {
                                    $meetingInfo['expand_content'] = mapByKey($meetingInfo['expand_content'], 'key');
                                }
                                if (!empty($meetingInfo['page_route'])) {
                                    $pageRenderData['route_path'] = $meetingInfo['page_route'];
                                } else {
                                    $pageRenderData['route_path'] = $routePath;
                                }
                                $meetingInfo['pre_meeting_info'] = MeetingFacade::getPrevMeetingItem($meetingInfo['id']);
                                $meetingInfo['next_meeting_info'] = MeetingFacade::getNextMeetingItem($meetingInfo['id']);
                                $pageRenderData['event_detail'] = $meetingInfo;
                                break;
                            case self::RELATION_TABLE_MEETING_TYPE:
                                //会议分类
                                $pageRenderData['route_path'] = self::MEETING_LIST_ROUTE_PATH;
                                $pageRenderData['event_type_info'] = MeetingFacade::getMeetingTypeRenderInfo(['id' => $seoInfo['relation_id']]);
                                $productRecentlyData = MeetingFacade::getMeetingRecentlyData();
                                if (!empty($productRecentlyData['country'])) {
                                    $pageRenderData['country_list'] = $productRecentlyData['country'];
                                }
                                break;
                        }
                    }
                    $layoutContent = $this->model->getStaticPageInfo(['route_path' => self::LAYOUTS_ROUTE]);
                    //动态页面获取page_content
                    if (!empty($pageRenderData['route_path'])) {
                        $pageData = $this->model->getStaticPageInfo(['route_path' => $pageRenderData['route_path']]);
                        if (empty($pageData['page_content'])) {
                            $pageData['page_content'] = [];
                        }
                        //合并公共数据进页面数据
                        if (!empty($layoutContent['page_content'])) {
                            foreach ($layoutContent['page_content'] as $key => $content_item) {
                                if (empty($pageData['page_content'][$key])) {
                                    $pageData['page_content'][$key] = $content_item;
                                }
                            }
                        }
                        if (!empty($pageData['page_content'])) {
                            $pageRenderData['page_content'] = $pageData['page_content'];
                        }
                    } else {
                        $pageData = $this->model->getStaticPageInfo(['id' => $pageRenderData['relation_id']]);
                        if ($pageData['route_path'] === self::MEETING_SPEAKER_ROUTE_PATH && isset($_GET['id'])) {
                            //嘉宾页获取会议详情
                            $meetingInfo = MeetingFacade::getMeetingRenderData(['id' => $_GET['id']]);
                            if (!empty($meetingInfo['expand_content'])) {
                                $meetingInfo['expand_content'] = mapByKey($meetingInfo['expand_content'], 'key');
                            }
                            if (!empty($meetingInfo['speech_schedule'])) {
                                foreach ($meetingInfo['speech_schedule'] as $speech_schedule_key => $speech_schedule_item) {
                                    if (!empty($speech_schedule_item['expand_content'])) {
                                        $meetingInfo['speech_schedule'][$speech_schedule_key]['expand_content'] = mapByKey($speech_schedule_item['expand_content'], 'key');
                                    } else {
                                        $meetingInfo['speech_schedule'][$speech_schedule_key]['expand_content'] = [];
                                    }
                                }
                            }
                            $pageRenderData['event_detail'] = $meetingInfo;
                        }
                        if (!empty($layoutContent['page_content'])) {
                            foreach ($layoutContent['page_content'] as $key => $content_item) {
                                if (empty($pageData['page_content'][$key])) {
                                    $pageData['page_content'][$key] = $content_item;
                                }
                            }
                        }
                        $pageRenderData['route_path'] = $pageData['route_path'];
                        $pageRenderData['page_content'] = $pageData['page_content'];
                        if ($pageData['route_path'] === self::MEETING_LIST_ROUTE_PATH) {
                            $productRecentlyData = MeetingFacade::getMeetingRecentlyData();
                            if (!empty($productRecentlyData['country'])) {
                                $pageRenderData['country_list'] = $productRecentlyData['country'];
                            }
                        }
                    }
                } else {
                    $pageRenderData = $this->model->getStaticPageInfo(['route_path' => '404.index']);
                    $layoutContent = $this->model->getStaticPageInfo(['route_path' => self::LAYOUTS_ROUTE]);
                    if (!empty($layoutContent['page_content'])) {
                        foreach ($layoutContent['page_content'] as $key => $content_item) {
                            if (empty($pageRenderData['page_content'][$key])) {
                                $pageRenderData['page_content'][$key] = $content_item;
                            }
                        }
                    }
                }
                //dd($pageRenderData);
            }
            /*if (!empty($pageRenderData)) {
                if (!empty($pageRenderData['route_path'])) {
                    switch ($pageRenderData['route_path']) {
                        case 'blog-recently.index':
                            $blogRecently = BlogFacade::getBlogRecentlyData();
                            $pageRenderData = array_merge($pageRenderData, $blogRecently);
                            break;
                        case 'help.index':
                            $helpListRet = HelpFacade::getHelpList(['page_size' => 999, 'status' => 0]);
                            if (!empty($helpListRet['data'])) {
                                $pageRenderData['help_items'] = $helpListRet['data'];
                            }
                            break;
                        case 'support.index':
                            $helpTypeRet = HelpFacade::getHelpTypeList(['page_size' => 999, 'status' => 0]);
                            if (!empty($helpTypeRet['data'])) {
                                $pageRenderData['help_type_items'] = $helpTypeRet['data'];
                            }
                            break;
                        case 'case-list.index':
                            $isHandpickRet = SuccessCaseFacade::getSuccessCaseList(['page_size' => 4, 'status' => 0, 'is_handpick' => 1]);
                            $funcRet = DictFacade::getDictFunctionList(['page_size' => 999, 'status' => 0]);
                            $industryRet = DictFacade::getDictIndustryList(['page_size' => 999, 'status' => 0]);
                            if (!empty($isHandpickRet)) {
                                $pageRenderData['handpick_data'] = $isHandpickRet;
                            }
                            $caseRet = SuccessCaseFacade::getSuccessCaseList(['page_size' => 12, 'status' => 0]);
                            if (!empty($caseRet)) {
                                $pageRenderData['case_data'] = $caseRet;
                            }
                            if (!empty($funcRet['data'])) {
                                $pageRenderData['func_items'] = $funcRet['data'];
                            }
                            if (!empty($industryRet['data'])) {
                                $pageRenderData['industry_items'] = $industryRet['data'];
                            }
                            break;
                        case 'product.index':
                            $staticPageData = $this->model->getStaticPageInfo(['route_path' => 'product.index', 'type' => 1]);
                            $productRecentlyData = ProductFacade::getProductRecentlyData();
                            $pageRenderData = array_merge($pageRenderData, $staticPageData);
                            $pageRenderData = array_merge($pageRenderData, $productRecentlyData);
                            //print_r($pageRenderData);die;
                            break;
                        case 'expo.index':
                            $staticPageData = $this->model->getStaticPageInfo(['route_path' => 'expo.index', 'type' => 1]);
                            $productRecentlyData = MeetingFacade::getMeetingRecentlyData();
                            $pageRenderData = array_merge($pageRenderData, $staticPageData);
                            $pageRenderData = array_merge($pageRenderData, $productRecentlyData);
                            //print_r($pageRenderData);die;
                            break;
                        default:
                            break;
                    }
                    $adData = SysAdFacade::getPageAdData($pageRenderData['route_path']);
                    if (!empty($adData)) {
                        $adData = mapByKey($adData, 'number');
                        $pageRenderData['ad_items'] = $adData;
                    }
                }
                $this->setCachePageCache($urla, $pageRenderData);
            }*/
        }
        //dd($pageRenderData);
        if (!empty($pageRenderData['route_path'])) {
            $adData = SysAdFacade::getPageAdData($pageRenderData['route_path']);
            $adRes = [];
            foreach ($adData as $adItem) {
                if (empty($adRes[$adItem['number']])) {
                    $adRes[$adItem['number']] = [];
                }
                array_push($adRes[$adItem['number']], $adItem);
            }
            $pageRenderData['ad_items'] = [];
            foreach ($adRes as $key => $adItem) {
                $pageRenderData['ad_items'][$key] = mapByKey($adItem, 'ad_key');
            }
        }
        $menuData = $this->model->getPageMenuInfo(['route_path' => self::LAYOUT_HEADER_MENU_ROUTE]);
        if ($menuData && $menuData['page_content']) {
            $pageRenderData['head_menu'] = json_decode($menuData['page_content'], true);
        } else {
            $pageRenderData['head_menu'] = [];
        }
//        dd($pageRenderData);
        return $pageRenderData;
    }

    /**
     * 获取页面详情
     * @return array
     */
    public function getCachePageData($urla = '')
    {
        $key = $this->getCachePageKey($urla);
        return Cache::get($key);
    }

    /**
     * 获取page缓存key
     * @param $urla
     * @return string
     */
    private function getCachePageKey($urla = '')
    {
        $pageParamsStr = 'urla:' . md5('urla-' . $urla);
        return $this->cacheBucket . $pageParamsStr;
    }

    /**
     * 获取手机的验证码
     * */
    public function getPhoneCode($phone, $countryCode)
    {
        UserCenterFacade::getSmsCode($phone, $countryCode);
        return true;
    }

    /**
     * 清除页面缓存
     */
    public function clearPageCacheByUrla($urla)
    {
        if (empty($urla)) {
            return;
        }
        $this->clearPageCache($this->getCachePageKey($urla));
        return true;
    }

    public function getWebMenu()
    {
        $webMenuData = $this->model->getWebMenu();
        $menu = [];
        $domain = config('app.web_url') . '/';
        foreach ($webMenuData as $item) {
            $menu[$item['route_path']] = $item['urla'];
        }
        return $menu;
    }

    public function getSiteMap()
    {
        $domain = config('app.web_url') . '/';
        $request_scheme = 'https';
        $rootUrl = $domain;
        $xmlns = $request_scheme . '://www.sitemaps.org/schemas/sitemap/0.9';
        $xmlnsXsi = $request_scheme . '://www.w3.org/2001/XMLSchema-instance';
        $xmlnsImage = $request_scheme . '//www.google.com/schemas/sitemap-image/1.1';
        $schemaLocation = $request_scheme . '://www.sitemaps.org/schemas/sitemap/0.9 '
            . $request_scheme . '://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd '
            . $request_scheme . '://www.google.com/schemas/sitemap-image/1.1 '
            . $request_scheme . '://www.google.com/schemas/sitemap-image/1.1/sitemap-image.xsd';
        $xmlStr = '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n";
        $xmlStr .= '<urlset   xmlns="' . $xmlns . '"   xmlns:xsi="' . $xmlnsXsi . '"   xmlns:image="' . $xmlnsImage . '"  xsi:schemaLocation="' . $schemaLocation . '">' . "\r\n";
        $xmlStr .= '<url>' . "\r\n";
        $xmlStr .= '<loc>' . $rootUrl . '</loc>' . "\r\n";
        $xmlStr .= '<lastmod>' . gmdate('c') . '</lastmod>' . "\r\n";
        //$xmlStr .= '<changefreq>daily</changefreq>';
        $xmlStr .= '</url>' . "\r\n";
        $xmlUrl = '';
        $resultData = $this->webSeoModel->getSeoList(['status' => 0, 'page_size' => 9999], 'a.urla');
        if (!empty($resultData['data'])) {
            $list = $resultData['data'];
            foreach ($list as $val) {
                $urla = empty($val['urla']) ? '' : $val['urla'];
                if (!empty($urla)) {
                    $href = $urla;
                    $xmlUrl .= '<url>' . "\r\n";
                    $xmlUrl .= '<loc>' . $rootUrl . $href . '</loc>' . "\r\n";
                    $xmlUrl .= '<lastmod>' . gmdate('c') . '</lastmod>' . "\r\n";
                    $xmlUrl .= '</url>' . "\r\n";
                }
            }
        }
        $xmlStr .= $xmlUrl;
        $xmlStr .= '</urlset>' . "\r\n";
        $xmlStr .= '<!-- XML Sitemap generated by Matchpages SEO -->';
        return $xmlStr;

    }

    /**
     * 全站搜索
     * */
    public function queryAllWebsite($params)
    {
        $keyWord = !empty($params['keyword']) ? $params['keyword'] : '';
        $pageSize = !empty($params['page_size']) ? $params['page_size'] : 10; //页面大小，不传默认一页10条记录
        $pageNo = !empty($params['page']) ? $params['page'] : 1; //页码，不传默认第1页
        $skip = ($pageNo - 1) * $pageSize; //页面记录的开始位置，即偏移量
        //产品
        $productModel = new ProductModel();
        $productQuery = $productModel->newInstance()->alias('a')
            ->leftJoin('web_seo as b', 'a.seo_id', '=', 'b.id')
            ->where('a.status', '=', 0)
            ->where('b.status', '=', 0)
            ->where('b.urla', '!=', '')
            ->where(function ($query) use ($keyWord) {
                if (!empty($keyWord)) {
                    $query->where('a.title', 'like', '%' . $keyWord . '%')
                        ->orWhere('a.description', 'like', '%' . $keyWord . '%')
                        ->orWhere('b.seo_title', 'like', '%' . $keyWord . '%')
                        ->orWhere('b.seo_keyword', 'like', '%' . $keyWord . '%')
                        ->orWhere('b.seo_describe', 'like', '%' . $keyWord . '%');
                }
            })->selectRaw("a.id,a.image_url,a.image_alt,b.urla,b.seo_describe,b.seo_title as title");
        //文章
        $blogModel = new BlogModel();
        $blogQuery = $blogModel->newInstance()->alias('a')
            ->leftJoin('web_seo as b', 'a.seo_id', '=', 'b.id')
            ->where('a.status', '=', 0)
            ->where('b.status', '=', 0)
            ->where('b.urla', '!=', '')
            ->where(function ($query) use ($keyWord) {
                if (!empty($keyWord)) {
                    $query->where('a.title', 'like', '%' . $keyWord . '%')
                        ->orWhere('a.description', 'like', '%' . $keyWord . '%')
                        ->orWhere('b.seo_title', 'like', '%' . $keyWord . '%')
                        ->orWhere('b.seo_keyword', 'like', '%' . $keyWord . '%')
                        ->orWhere('b.seo_describe', 'like', '%' . $keyWord . '%');
                }
            })
            ->selectRaw("a.id,a.image_url,a.image_alt,b.urla,b.seo_describe,b.seo_title as title");
        //帮助
        $helpModel = new HelpModel();
        $helpQuery = $helpModel->newInstance()->alias('a')
            ->leftJoin('web_seo as b', 'a.seo_id', '=', 'b.id')
            ->where('a.status', '=', 0)
            ->where('b.status', '=', 0)
            ->where('b.urla', '!=', '')
            ->where(function ($query) use ($keyWord) {
                if (!empty($keyWord)) {
                    $query->where('a.title', 'like', '%' . $keyWord . '%')
                        ->orWhere('a.description', 'like', '%' . $keyWord . '%')
                        ->orWhere('b.seo_title', 'like', '%' . $keyWord . '%')
                        ->orWhere('b.seo_keyword', 'like', '%' . $keyWord . '%')
                        ->orWhere('b.seo_describe', 'like', '%' . $keyWord . '%');
                }
            })
            ->selectRaw("a.id,a.image_url,a.image_alt,b.urla,b.seo_describe,b.seo_title as title");
        //成功案例
        $successCaseModel = new SuccessCaseModel();
        $successCaseQuery = $successCaseModel->newInstance()->alias('a')
            ->leftJoin('web_seo as b', 'a.seo_id', '=', 'b.id')
            ->where('a.status', '=', 0)
            ->where('b.status', '=', 0)
            ->where('b.urla', '!=', '')
            ->where(function ($query) use ($keyWord) {
                if (!empty($keyWord)) {
                    $query->where('a.title', 'like', '%' . $keyWord . '%')
                        ->orWhere('a.description', 'like', '%' . $keyWord . '%')
                        ->orWhere('b.seo_title', 'like', '%' . $keyWord . '%')
                        ->orWhere('b.seo_keyword', 'like', '%' . $keyWord . '%')
                        ->orWhere('b.seo_describe', 'like', '%' . $keyWord . '%');
                }
            })
            ->selectRaw("a.id,a.image_url,a.image_alt,b.urla,b.seo_describe,b.seo_title as title");
        $staticPageQuery = $this->model->newInstance()->alias('a')
            ->leftJoin('web_seo as b', 'a.seo_id', '=', 'b.id')
            ->where('a.status', '=', 0)
            ->where('b.status', '=', 0)
            ->where('b.urla', '!=', '')
            ->where(function ($query) use ($keyWord) {
                if (!empty($keyWord)) {
                    $query->where('a.page_name', 'like', '%' . $keyWord . '%')
                        ->orWhere('b.seo_title', 'like', '%' . $keyWord . '%')
                        ->orWhere('b.seo_keyword', 'like', '%' . $keyWord . '%')
                        ->orWhere('b.seo_describe', 'like', '%' . $keyWord . '%');
                }
            })
            ->selectRaw("a.id,Null AS image_url,Null AS image_alt,b.urla,b.seo_describe,b.seo_title as title");
        $allData = array();
        $totalCount = 0;
        $queryStr = null;
        $productCount = $productQuery->count();
        $totalCount = $totalCount + $productCount;
        $queryStr = $productQuery;
        $blogCount = $blogQuery->count();
        $totalCount = $totalCount + $blogCount;
        $queryStr = $queryStr->unionAll($blogQuery);;
        $helpCount = $helpQuery->count();
        $totalCount = $totalCount + $helpCount;
        $queryStr = $queryStr->unionAll($helpQuery);
        $successCaseCount = $successCaseQuery->count();
        $totalCount = $totalCount + $successCaseCount;
        $queryStr = $queryStr->unionAll($successCaseQuery);
        $staticPageCount = $staticPageQuery->count();
        $totalCount = $totalCount + $staticPageCount;
        $queryStr = $queryStr->unionAll($staticPageQuery);
        $allData = $queryStr
            ->skip($skip)
            ->limit($pageSize)
            ->get();
        if (!empty($allData)) {
            $resultData = $allData->toArray();
        }
        $result = buildPage($resultData, $skip, $pageNo, $pageSize, $totalCount);
        return $result;
    }

    /**
     * 获取产品类型菜单
     * */
    public function getProductTypeMenu()
    {
        $typeParams = [];
        $typeParams['status'] = 0;
        $typeParams['page_size'] = 9999;
        $productTypeMenuData = ProductFacade::getTreeProductList($typeParams);
        return $productTypeMenuData;
    }

    public function getProductTagRenderData()
    {
        $data = ProductFacade::getProductTagData();
        return $data;
    }

    /**
     * @return array
     */
    public function getPlateTypeMenu()
    {
        $plateNewsType = BlogRenderFacade::getPublishedTypeList(BlogPlateModel::NEWS, 0, 9999);
        foreach ($plateNewsType as &$plateNewsTypeItem) {
            $plateNewsTypeItem['expand_content'] = empty($plateNewsTypeItem['expand_content']) ? [] : json_decode($plateNewsTypeItem['expand_content'], true);
            $plateNewsTypeItem['expand_array'] = $this->transformArrayToKeyValue($plateNewsTypeItem['expand_content']);
        }
        $plateSolutionType = BlogRenderFacade::getPublishedTypeList(BlogPlateModel::SOLUTION, 0, 9999);
        foreach ($plateSolutionType as &$plateSolutionTypeItem) {
            $plateSolutionTypeItem['expand_content'] = empty($plateSolutionTypeItem['expand_content']) ? [] : json_decode($plateSolutionTypeItem['expand_content'], true);
            $plateSolutionTypeItem['expand_array'] = $this->transformArrayToKeyValue($plateSolutionTypeItem['expand_content']);
        }
        $plateVideoType = BlogRenderFacade::getPublishedTypeList(BlogPlateModel::VIDEO, 0, 9999);
        foreach ($plateVideoType as &$plateVideoTypeItem) {
            $plateVideoTypeItem['expand_content'] = empty($plateVideoTypeItem['expand_content']) ? [] : json_decode($plateVideoTypeItem['expand_content'], true);
            $plateVideoTypeItem['expand_array'] = $this->transformArrayToKeyValue($plateVideoTypeItem['expand_content']);
        }
        $event_tag_list = MeetingFacade::getMeetingTagList([]);
        if (!empty($event_tag_list['data'])) {
            $event_tag_list = $event_tag_list['data'];
        }
        $plateNewsTag = BlogRenderFacade::getPublishedTagList(BlogPlateModel::NEWS);
        $platCommentsType = BlogRenderFacade::getPublishedTypeList(BlogPlateModel::FUNGI_COMMENT, 0, 9999);
        return ['event_tag_list'=> $event_tag_list ,'news_type' => $plateNewsType, 'solution_type' => $plateSolutionType, 'video_type' => $plateVideoType, 'news_tags' => $plateNewsTag, 'comment_type' => $platCommentsType];
    }

    public function transformArrayToKeyValue($array)
    {
        $result = [];
        foreach ($array as $item) {
            if (isset($item['key']) && isset($item['value'])) {
                $result[$item['key']] = $item['value'];
            }
        }
        return $result;
    }

    /**
     * 获取会议类型菜单
     * */
    public function getMeetingTypeMenu()
    {
        $typeParams = [];
        $typeParams['status'] = 0;
        $typeParams['page_size'] = 9999;
        $meetingTypeMenuData = MeetingFacade::getMeetingTypeList($typeParams);
        return $meetingTypeMenuData;
    }

    public function getGlobalSeo()
    {
        $globalParams = [];
        $globalData = SysGlobalConfigFacade::getGlobalConfig($globalParams);
        if (!empty($globalData)) {
            $globalData = mapByKey($globalData, 'global_key');
        }
        $globalSeoData = [
            "seo_title" => "",
            "seo_keyword" => "",
            "seo_describe" => "",
            "track_code_head" => "",
            "track_code_body" => ""
        ];
        if (!empty($globalData['WEB_GLOBAL_SEO']['value'])) {
            $globalSeoData['seo_title'] = empty($globalData['WEB_GLOBAL_SEO']['value']['seo_title']) ? '' : $globalData['WEB_GLOBAL_SEO']['value']['seo_title'];
            $globalSeoData['seo_keyword'] = empty($globalData['WEB_GLOBAL_SEO']['value']['seo_keyword']) ? '' : $globalData['WEB_GLOBAL_SEO']['value']['seo_keyword'];
            $globalSeoData['seo_describe'] = empty($globalData['WEB_GLOBAL_SEO']['value']['seo_describe']) ? '' : $globalData['WEB_GLOBAL_SEO']['value']['seo_describe'];
            $globalSeoData['track_code_head'] = empty($globalData['WEB_GLOBAL_SEO']['value']['track_code_head']) ? '' : $globalData['WEB_GLOBAL_SEO']['value']['track_code_head'];
            $globalSeoData['track_code_body'] = empty($globalData['WEB_GLOBAL_SEO']['value']['track_code_body']) ? '' : $globalData['WEB_GLOBAL_SEO']['value']['track_code_body'];
        }
        return $globalSeoData;
    }

    /**
     * 缓存页面数据
     * @param string $urla
     * @param array $PageData
     */
    private function setCachePageCache($urla = '', $PageData)
    {
        Cache::put($this->getCachePageKey($urla), $PageData, config('cache.page_time'));
    }

    public function downloadPageSEOExcel($pageSize = 10000)
    {
        $params = [
            'page_size' => $pageSize
        ];
        // $pageData = $this->getStaticPageList($params);
        $pageData = $this->model->downloadPageSEOQuery();
        $mapData = [];
        if (!empty($pageData)) {
            $index = 1;
            $langPath = '';
            if(config('app.is_utm') && config('app.language_path') === 'en') {
                $langPath = 'en/';
            }
            foreach ($pageData as $pd) {
                $pd = (array)$pd;
                if ($pd['page_name'] != 'layout_menu') {
                    $tmp = [];
                    $tmp['index'] = $index++;
                    $tmp['relation_table'] = $pd['relation_table'];
                    $tmp['page_name'] = $pd['page_name'];
                    $tmp['page_url'] = config('app.web_url').'/'.$langPath.$pd['urla'] ?? '';
                    $tmp['urla'] = $pd['urla'] ?? '';
                    $tmp['seo_title'] = $pd['seo_title'] ?? '';
                    $tmp['seo_keyword'] = $pd['seo_keyword'] ?? '';
                    $tmp['seo_describe'] = $pd['seo_describe'] ?? '';
                    $tmp['new_seo_title'] = '';
                    $tmp['new_seo_keyword'] = '';
                    $tmp['new_describe'] = '';
                    $mapData[] = $tmp;
                }
            }
        }
        $headerMap = [
            'index' => '序号',
            'relation_table' => '页面类型',
            'page_name' => '页面名称',
            'page_url' => '原页面地址',
            'new_page_url' => '优化页面地址',
            'urla' => '原路径',
            'urla_update' => '优化路径',
            'seo_title' => '原SEO标题',
            'new_seo_title' => '优化SEO标题',
            'seo_keyword' => '原SEO关键词',
            'new_seo_keyword' => '优化SEO关键词',
            'seo_describe' => '原SEO描述',
            'new_describe' => '优化SEO描述',
        ];
        $afterSheetStyle = [
            AfterSheet::class => function (AfterSheet $event) use (&$mapData) {
                //表头字体
                $event->sheet->getDelegate()->getColumnDimension('A')->setWidth(10);
                $event->sheet->getDelegate()->getColumnDimension('B')->setWidth(30);
                $event->sheet->getDelegate()->getColumnDimension('C')->setWidth(30);
                $event->sheet->getDelegate()->getColumnDimension('D')->setWidth(40);
                $event->sheet->getDelegate()->getColumnDimension('E')->setWidth(40);
                $event->sheet->getDelegate()->getColumnDimension('F')->setWidth(40);
                $event->sheet->getDelegate()->getColumnDimension('G')->setWidth(40);
                $event->sheet->getDelegate()->getColumnDimension('H')->setWidth(40);
                $event->sheet->getDelegate()->getColumnDimension('I')->setWidth(40);
                $event->sheet->getDelegate()->getColumnDimension('J')->setWidth(40);
                $event->sheet->getDelegate()->getColumnDimension('K')->setWidth(40);
                $event->sheet->getDelegate()->getColumnDimension('L')->setWidth(40);
                $event->sheet->getDelegate()->getColumnDimension('M')->setWidth(40);
                // 获取最高列字母
                $highestColumn = $event->sheet->getHighestColumn();
                // 设置表头背景色
                $styleArray = [
                    'fill' => [
                        'fillType' => Fill::FILL_SOLID,
                        'startColor' => [
                            'rgb' => '1890ff', // 蓝色背景
                        ],
                    ],
                    'font' => [
                        'color' => [
                            'rgb' => 'ffffff', // 白色字体
                        ],
                    ]
                ];
                $event->sheet->getStyle('E1')->applyFromArray($styleArray);
                $event->sheet->getStyle('G1')->applyFromArray($styleArray);
                $event->sheet->getStyle('I1')->applyFromArray($styleArray);
                $event->sheet->getStyle('K1')->applyFromArray($styleArray);
                $event->sheet->getStyle('M1')->applyFromArray($styleArray);
                $worksheet = $event->sheet->getDelegate();
                // 获取最大列和最大行
                $lastColumn = $worksheet->getHighestColumn();
                $lastRow    = $worksheet->getHighestRow();
                // 设置动态范围的样式
                $worksheet->getStyle("A1:{$lastColumn}{$lastRow}")
                    ->getAlignment()
                    ->setWrapText(true);
            }
        ];
        $columnFormats = [];
        return Excel::download(
            new ExportExcel(
                $headerMap,
                $mapData,
                $afterSheetStyle,
                $columnFormats
            ),
            '页面seo_list_'.date('YmdHis') . ".xlsx"
        );
    }

    public function uploadPageSEOExcel($filePath, $isRecover = true)
    {
        $loadCount = 0;
        try {
            $headRow = [
                '序号' => 'index',
                '页面类型' => 'relation_table',
                '页面名称' => 'page_name',
                '原页面地址' => 'page_url',
                '原路径' => 'urla',
                'SEO标题' => 'seo_title',
                'SEO关键词' => 'seo_keyword',
                'SEO描述' => 'seo_describe',
                '优化页面地址' => 'new_page_url',
                '优化路径' => 'urla_update',
                '优化SEO标题' => 'new_seo_title',
                '优化SEO关键词' => 'new_seo_keyword',
                '优化SEO描述' => 'new_describe'
            ];
            $columns = [
                'index',
                'relation_table',
                'page_name',
                'page_url',
                'urla',
                'seo_title',
                'seo_keyword',
                'seo_describe',
                'new_page_url',
                'urla_update',
                'new_seo_title',
                'new_seo_keyword',
                'new_describe',
            ];
            $data = [];
            $duplicateUrla = [];
            //更新的条数，重复的条数
            $updateNumber = 0;
            $duplicateNumber = 0;
            Excel::import(new ImportHeadingExcel(function ($rows) use (&$data, &$duplicateUrla, &$loadCount, $isRecover, $headRow, $columns) {
                // 解析字段在excel中对应的索引
                $header = $rows[0];
                $headKey = [];
                foreach ($header as $hk => $val) {
                    $val = trim($val);
                    if (!isset($headRow[$val])) {
                        continue;
                    }
                    $headKey[$headRow[$val]] = $hk;
                }
                $urla = [];
                foreach ($rows as $key => &$row) {
                    if ($key === 0) {
                        continue;
                    }
                    if ($loadCount++ >= 10000) {
                        break;
                    }
                    if (empty($row) || empty($headKey['urla'])) {
                        continue;
                    }
                    $tmp = [];
                    // 整理字段
                    if (empty($row[$headKey['urla']])
                        && empty($row[$headKey['page_url']])
                        && empty(pathinfo($row[$headKey['page_url']], PATHINFO_BASENAME))
                    ) {
                        continue;
                    }
                    if (empty($row[$headKey['urla']])) {
                        $row[$headKey['urla']] = pathinfo($row[$headKey['page_url']], PATHINFO_BASENAME);
                    }
                    if (empty($row[$headKey['urla_update']])
                        && !empty($row[$headKey['new_page_url']])
                        && !empty(pathinfo($row[$headKey['new_page_url']], PATHINFO_BASENAME))) {
                        $row[$headKey['urla_update']] = pathinfo($row[$headKey['new_page_url']], PATHINFO_BASENAME);
                    }
                    foreach ($columns as $column) {
                        if (isset($headKey[$column])) {
                            $tmp[$column] = $row[$headKey[$column]] ?? '';
                        }
                        //导入的urla_update有重复项
                        if ($column === 'urla_update' && !empty($tmp[$column])) {
                            if (!empty($urla) && in_array($tmp[$column], $urla)) {
                                $oldUrla = $tmp[$column];
                                $tmp[$column] .= '-' . strtolower(uniqid());
                                //page_name
                                $tmpDuplicate = [];
                                $tmpDuplicate['urla'] = $row[$headKey['urla']] ?? '';
                                $tmpDuplicate['page_name'] = $row[$headKey['page_name']] ?? '';
                                $tmpDuplicate['seo_title'] = $row[$headKey['new_seo_title']] ?? '';
                                $tmpDuplicate['seo_keyword'] =$row[$headKey['new_seo_keyword']] ?? '';
                                $tmpDuplicate['seo_describe'] = $row[$headKey['new_describe']] ?? '';
                                $tmpDuplicate['old_urla_update'] = $oldUrla;
                                $tmpDuplicate['new_urla_update'] = $tmp[$column];
                                $duplicateUrla[] = $tmpDuplicate;
                            }
                            $urla[] = $tmp[$column];
                        }
                    }
                    $tmp['seo_title'] = $tmp['new_seo_title'];
                    $tmp['seo_keyword'] = $tmp['new_seo_keyword'];
                    $tmp['seo_describe'] = $tmp['new_describe'];
                    $data[] = $tmp;
                }
            }), $filePath);
            if (!empty($data)) {
                $checkUrla = array_column($data, 'urla_update');
                $mapUrlaUpdate = mapByKey($data, 'urla_update');
                //在数据库中查到重复项
                $check = $this->webSeoModel->checkUrlaIsExits($checkUrla);
                if (!empty($check)) {
                    foreach ($check as $ck) {
                        $tmpDuplicate = [];
                        $tmpDuplicate['urla'] = $mapUrlaUpdate[$ck['urla']]['urla'] ?? '';
                        $tmpDuplicate['seo_title'] = $mapUrlaUpdate[$ck['urla']]['seo_title'] ?? '';
                        $tmpDuplicate['seo_keyword'] = $mapUrlaUpdate[$ck['urla']]['seo_keyword'] ?? '';
                        $tmpDuplicate['seo_describe'] = $mapUrlaUpdate[$ck['urla']]['seo_describe'] ?? '';
                        $tmpDuplicate['page_name'] = $mapUrlaUpdate[$ck['urla']]['page_name'] ?? '';
                        $tmpDuplicate['old_urla_update'] = $ck['urla'];
                        $tmpDuplicate['new_urla_update'] = $ck['urla'] . '-' . strtolower(uniqid());
                        $duplicateUrla[] = $tmpDuplicate;
                        foreach ($data as &$da) {
                            if($da['urla'] === $tmpDuplicate['urla']
                                && $da['urla_update'] === $tmpDuplicate['old_urla_update']) {
                                $da['urla_update'] = $tmpDuplicate['new_urla_update'];
                                break;
                            }
                        }
                    }
                }
                foreach ($data as $d) {
                    if (!empty($d['urla'])) {
                        $dup = false;
                        $urlaUpdate = '';
                        if(!empty($d['urla_update'])) {
                            $urlaUpdate =  $d['urla_update'];
                            if(!empty($duplicateUrla)) {
                                foreach ($duplicateUrla as $dp) {
                                    if($dp['urla'] === $d['urla']
                                        && $dp['new_urla_update'] === $d['urla_update']) {
                                        $duplicateNumber++;
                                        $dup = true;
                                        break;
                                    }
                                }
                            }
                        }
                        if($dup) {
                            //如果url重复，不能更新
                            $urlaUpdate = '';
                        }
                        if($urlaUpdate || $d['seo_title'] || $d['seo_keyword'] || $d['seo_describe']) {
                            $updateNumber++;
                            $this->webSeoModel->updateSeoInfo($d['urla'], $urlaUpdate, $d['seo_title'], $d['seo_keyword'], $d['seo_describe']);
                        }
                    }
                }
            }
            return [
                'update_number' => $updateNumber,
                'duplicate_number' => $duplicateNumber,
                'duplicate_data' => $duplicateUrla
            ];
        } finally {
            //fclose($f);
        }
    }

    public function uploadPageSEOByData($duplicateUrla)
    {
        if(!empty($duplicateUrla)) {
            foreach ($duplicateUrla as $dp) {
                $check = $this->webSeoModel->checkUrlaUnique($dp['new_urla_update']);
                if($check) {
                    $this->webSeoModel->updateSeoInfo($dp['urla'], $dp['new_urla_update'], $dp['seo_title'], $dp['seo_keyword'], $dp['seo_describe']);
                }
            }
        }
        return 1;
    }

    public function updateTransStatus($id,$transStatus) {
        return $this->webSeoModel->updateTransStatus($id,$transStatus);
    }
}
