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

namespace App\Web\Services;

use App\Common\Facades\ComSmsFacade;
use App\Common\Facades\UserCenterFacade;
use App\Exceptions\ApiException;
use App\Services\CommonUserBaseService;
use App\User\Facades\UserFacade;
use App\User\Models\UserModel;
use App\Web\Facades\WebFacade;
use App\Web\Models\HelpModel;
use App\Web\Models\HelpTagModel;
use App\Web\Models\HelpTagRelationModel;
use App\Web\Models\HelpTypeModel;
use App\Web\Models\HelpTypeRelationModel;
use Illuminate\Support\Facades\Cache;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;

class HelpService extends CommonUserBaseService
{
    protected $cache = true;

    protected $cacheBucket = 'Help:';

    protected $helpTypeModel;
    protected $helpTypeRelationModel;
    protected $helpTagModel;
    protected $helpTagRelationModel;

    /**
     * HelpService construct
     * @param HelpModel $model
     * @param HelpTypeModel $helpTypeModel
     * @param HelpTagRelationModel $helpTagRelationModel
     * @param HelpTagModel $helpTagModel
     * @param HelpTypeRelationModel $helpTypeRelationModel
     * */
    public function __construct(HelpModel $model,
                                HelpTypeModel $helpTypeModel,
                                HelpTagRelationModel $helpTagRelationModel,
                                HelpTagModel $helpTagModel,
                                HelpTypeRelationModel $helpTypeRelationModel
    ){
        $this->model=$model;
        $this->helpTypeModel=$helpTypeModel;
        $this->helpTypeRelationModel=$helpTypeRelationModel;
        $this->helpTagModel=$helpTagModel;
        $this->helpTagRelationModel=$helpTagRelationModel;
    }

    /**
     * 获取帮助类型列表
     * */
    public function getHelpTypeList($params){
        $retData= $this->helpTypeModel->getHelpTypeList($params);
        if(!empty($retData['data'])){
            $typeIds=array_column($retData['data'],'id');
            $newsCounts=$this->helpTypeRelationModel->getHelpTypeCount($typeIds);
            foreach ($retData['data'] as &$newsItem){
                $newsItem['help_count'] = $newsCounts[$newsItem['id']] ?? 0;
                $newsItem['expand_content'] = empty($newsItem['expand_content'])?[]:json_decode($newsItem['expand_content'],true);
            }
        }
        return $retData;
    }

    /**
     * 根据类型id 获取帮助列表
     * */
    public function getHelpByTypeIds($params){
        $retData= $this->helpTypeRelationModel->getHelpByTypeIds($params);
        return $retData;
    }

    /**
     * 根据标签id 获取帮助列表
     * */
    public function getHelpByTagIds($params){
        $retData= $this->helpTagRelationModel->getHelpByTagIds($params);
        return $retData;
    }

    /**
     * 帮助类型保存
     * */
    public function saveHelpType($params){
        $saveData=[];
        $nowTime=nowTime();
        $saveData['update_time']=$nowTime;
        $userId=$this->getAuthUserId();

        if (!empty($params['seo_data'])) {
            $urlaUnique = WebFacade::checkUrlaUnique($params['seo_data']['urla'], $params['seo_id']);
            if (!$urlaUnique) {
                throw new ApiException(10019, ['name' => $params['seo_data']['urla']]);
            }
        }

        if(!empty($params['id'])){
            $saveData['id']=$params['id'];
            if(isset($params['type_name'])){
                $nameUnique =$this->helpTypeModel->checkTypeNameUnique($params['type_name'],$params['id']);
                if (!$nameUnique) {
                    throw new ApiException(10018, ['name' => $params['type_name']]);
                }
                $saveData['type_name']=$params['type_name'];
            }
            if(isset($params['type_img'])){
                $saveData['type_img']=empty($params['type_img'])?'':$params['type_img'];
            }
            if(isset($params['type_img_alt'])){
                $saveData['type_img_alt']=empty($params['type_img_alt'])?'':$params['type_img_alt'];
            }
            if(isset($params['status'])){
                $saveData['status']=$params['status'];
            }
            if(isset($params['sort'])){
                $saveData['sort']=$params['sort'];
            }
            if(isset($params['expand_content'])){
                $saveData['expand_content']=!empty($params['expand_content'])?json_encode($params['expand_content']):'';
            }
        }else{
            $nameUnique =$this->helpTypeModel->checkTypeNameUnique($params['type_name']);
            if (!$nameUnique) {
                throw new ApiException(10018, ['name' => $params['type_name']]);
            }
            $saveData['user_id']=$userId;
            $saveData['type_name']=$params['type_name'];
            $saveData['expand_content']=!empty($params['expand_content'])?json_encode($params['expand_content']):'';
            $saveData['type_img']=empty($params['type_img'])?'':$params['type_img'];
            $saveData['type_img_alt']=empty($params['type_img_alt'])?'':$params['type_img_alt'];
            $saveData['sort']=empty($params['sort'])?0:$params['sort'];
            $saveData['create_time']=$nowTime;
        }
        $id = $this->helpTypeModel->saveTypeData($saveData);
        if (!empty($id) && isset($params['seo_data'])) {
            $seoParams = [
                'relation_table' => WebService::RELATION_TABLE_HELP_TYPE,
                'relation_id' => $id,
                'urla' => $params['seo_data']['urla'],
                'seo_title' => $params['seo_data']['seo_title'],
                'seo_keyword' => $params['seo_data']['seo_keyword'],
                'seo_describe' => $params['seo_data']['seo_describe']
            ];

            if (empty($params['seo_id'])) {
                $seoParams['user_id'] = $userId;
                $urlaId = WebFacade::saveSeoData($seoParams);
                $this->helpTypeModel->newInstance()->where('id','=',$id)->update(['seo_id' => $urlaId]);
            } else {
                $seoParams['id'] = $params['seo_id'];
                $urlaId = WebFacade::saveSeoData($seoParams);
            }
            if(!empty($saveData['status'])&&$saveData['status']==2){
                //移除对应seo
                $delSeoParams=[];
                $delSeoParams['relation_table']=WebService::RELATION_TABLE_HELP_TYPE;
                $delSeoParams['relation_id']=$id;
                $ret = WebFacade::delSeoByRelation($delSeoParams);
            }
        }
        //更新所有页面缓存
        WebFacade::clearPageCache('urla:');
        return $id;
    }

    /**
     * 保存帮助类型关系
     * */
    public function typeRelationSave($params){
        $userId=$this->getAuthUserId();
        $ret = $this->helpTypeRelationModel->typeRelationSave($params,$userId);

        //更新所有页面缓存
        WebFacade::clearPageCache('urla:');
        return $ret;
    }

    /**
     * 根据帮助类型 保存帮助关系
     * */
    public function addRelationByTypeId($typeId,$helpIds){
        $userId=$this->getAuthUserId();
        $ret = $this->helpTypeRelationModel->addByTypeId($typeId,$helpIds,$userId);

        //更新所有页面缓存
        WebFacade::clearPageCache('urla:');
        return $ret;
    }

    /**
     * 根据类型id及帮助id 删除关联关系
     * */
    public function delTypeRelation($typeId, $helpId)
    {
        $ret = $this->helpTypeRelationModel->delTypeRelation($typeId, $helpId);

        //更新所有页面缓存
        WebFacade::clearPageCache('urla:');
        return $ret;
    }

    /**
     * 获取帮助标签列表
     * */
    public function getHelpTagList($params){
        $retData= $this->helpTagModel->getHelpTagList($params);
        if(!empty($retData['data'])){
            $tagIds=array_column($retData['data'],'id');
            $newsCounts=$this->helpTagRelationModel->getHelpTagCount($tagIds);
            foreach ($retData['data'] as &$newsItem){
                $newsItem['help_count'] = $newsCounts[$newsItem['id']] ?? 0;
            }
        }
        return $retData;
    }

    /**
     * 帮助标签保存
     * */
    public function saveHelpTag($params){
        $saveData=[];
        $nowTime=nowTime();
        $saveData['update_time']=$nowTime;
        $userId=$this->getAuthUserId();

        if (!empty($params['seo_data'])) {
            $urlaUnique = WebFacade::checkUrlaUnique($params['seo_data']['urla'], $params['seo_id']);
            if (!$urlaUnique) {
                throw new ApiException(10019, ['name' => $params['seo_data']['urla']]);
            }
        }

        if(!empty($params['id'])){
            $saveData['id']=$params['id'];
            if(isset($params['tag_name'])){
                $nameUnique =$this->helpTagModel->checkTagNameUnique($params['tag_name'],$params['id']);
                if (!$nameUnique) {
                    throw new ApiException(10018, ['name' => $params['tag_name']]);
                }
                $saveData['tag_name']=$params['tag_name'];
            }
            if(isset($params['status'])){
                $saveData['status']=$params['status'];
            }
            if(isset($params['sort'])){
                $saveData['sort']=$params['sort'];
            }
            if(isset($params['is_hot'])){
                $saveData['is_hot']=$params['is_hot'];
            }
        }else{
            $nameUnique =$this->helpTagModel->checkTagNameUnique($params['tag_name']);
            if (!$nameUnique) {
                throw new ApiException(10018, ['name' => $params['tag_name']]);
            }
            $saveData['user_id']=$userId;
            $saveData['tag_name']=$params['tag_name'];
            $saveData['sort']=empty($params['sort'])?0:$params['sort'];
            $saveData['create_time']=$nowTime;
        }
        $id = $this->helpTagModel->saveTagData($saveData);
        if (!empty($id) && isset($params['seo_data'])) {
            $seoParams = [
                'relation_table' => WebService::RELATION_TABLE_HELP_TAG,
                'relation_id' => $id,
                'urla' => $params['seo_data']['urla'],
                'seo_title' => $params['seo_data']['seo_title'],
                'seo_keyword' => $params['seo_data']['seo_keyword'],
                'seo_describe' => $params['seo_data']['seo_describe']
            ];

            if (empty($params['seo_id'])) {
                $seoParams['user_id'] = $userId;
                $urlaId = WebFacade::saveSeoData($seoParams);
                $this->helpTagModel->newInstance()->where('id','=',$id)->update(['seo_id' => $urlaId]);
            } else {
                $seoParams['id'] = $params['seo_id'];
                $urlaId = WebFacade::saveSeoData($seoParams);
            }
            if(!empty($saveData['status'])&&$saveData['status']==2){
                //移除对应seo
                $delSeoParams=[];
                $delSeoParams['relation_table']=WebService::RELATION_TABLE_HELP_TAG;
                $delSeoParams['relation_id']=$id;
                $ret = WebFacade::delSeoByRelation($delSeoParams);
            }
        }
        return $id;
    }

    /**
     * 保存帮助标签关系
     * */
    public function tagRelationSave($params){
        $userId=$this->getAuthUserId();
        $ret = $this->helpTagRelationModel->tagRelationSave($params,$userId);

        //更新所有页面缓存
        WebFacade::clearPageCache('urla:');
        return $ret;
    }

    /**
     * 根据帮助标签 保存帮助关系
     * */
    public function addRelationByTagId($tagId,$helpIds){
        $userId=$this->getAuthUserId();
        $ret = $this->helpTagRelationModel->addByTagId($tagId,$helpIds,$userId);

        //更新所有页面缓存
        WebFacade::clearPageCache('urla:');
        return $ret;
    }

    /**
     * 根据标签id及帮助id 删除关联关系
     * */
    public function delTagRelation($tagId, $helpId)
    {
        $ret = $this->helpTagRelationModel->delTagRelation($tagId, $helpId);
        //更新所有页面缓存
        WebFacade::clearPageCache('urla:');
        return $ret;
    }

    /**
     * 保存帮助数据
     * */
    public function saveHelp($params){
        $saveData=$this->buildHelpData($params);
        $userId=$this->getAuthUserId();
        $typeIds = empty($params['type_ids']) ? []: $params['type_ids'];
        $tagIds = empty($params['tag_ids']) ? []: $params['tag_ids'];
        $seoData=empty($params['seo_data'])?[]:$params['seo_data'];
        $urlaId=empty($saveData['seo_id'])?0:$saveData['seo_id'];
        if(!empty($seoData)){
            $urlaUnique = WebFacade::checkUrlaUnique($seoData['urla'],$urlaId);
            if (!$urlaUnique) {
                throw new ApiException(10019, ['name' => $seoData['urla']]);
            }
        }
        $id = $this->model->saveHelpData($saveData);
        if(!empty($id)){
            if(isset($params['seo_data'])){
                $seoParams=[];
                $seoParams['relation_table']=WebService::RELATION_TABLE_HELP;
                $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'];
                if(empty($urlaId)){
                    $seoParams['user_id']=$userId;
                    $urlaId = WebFacade::saveSeoData($seoParams);
                    $this->model->newInstance()->where('id','=',$id)->update(['seo_id'=>$urlaId]);
                }else{
                    $seoParams['id']=$urlaId;
                    $urlaId= WebFacade::saveSeoData($seoParams);
                }
            }
            if(isset($params['type_ids'])){
                $helpTypeParams=[];
                $helpTypeParams['help_id']=$id;
                $helpTypeParams['type_ids']=$typeIds;
                $this->helpTypeRelationModel->typeRelationSave($helpTypeParams,$userId);
            }
            if(isset($params['tag_ids'])){
                $helpTagParams=[];
                $helpTagParams['help_id']=$id;
                $helpTagParams['tag_ids']=$tagIds;
                $this->helpTagRelationModel->tagRelationSave($helpTagParams,$userId);
            }

            // 获取是否需要修改排序数据
            if (isset($saveData['sort'])) {
                $getData = $this->model->selectRaw('id')
                    ->where('sort', '=', $saveData['sort'])
                    ->where('id', '<>', $id)->first();
                if (!empty($getData['id'])) {
                    $this->model->where('sort','>=',$saveData['sort'])
                        ->where('id', '<>', $id)
                        ->update(['sort' => DB::raw('sort + 1')]);
                }
            }
            if(!empty($params['id'])&&!empty($params['virtual_view'])){
                $this->updatePv($params['id'],$params['virtual_view']);
            }
            if(!empty($saveData['status'])&&$saveData['status']==2){
                //移除对应seo
                $delSeoParams=[];
                $delSeoParams['relation_table']=WebService::RELATION_TABLE_HELP;
                $delSeoParams['relation_id']=$id;
                $ret = WebFacade::delSeoByRelation($delSeoParams);
            }
        }
        //更新所有页面缓存
        WebFacade::clearPageCache('urla:');
        return $id;
    }

    /**
     * 构造虚拟阅读量
     * */
    public function helpUvFactory(){
        $page=1;
        $total=0;
        do{
            $where=[];
            $where['page_size']=500;
            $where['page']=$page;
            $where['status']=0;
            $where['lt_total_view']=1000;
            $helpData= $this->model->getHelpList($where,'a.id,a.virtual_view,a.total_view');
            if(!empty($helpData)&&!empty($helpData['data'])){
                $total=$helpData['total'];
                $data=$helpData['data'];
                $updateUvStr='';
                // 规则：小于1千数随记增加 150以内位数
                foreach ($data as $item){
                    $value=0;
                    if($item['total_view']<1000){
                        $value=  mt_rand(0, 150);
                    }
                    /*   if($item['total_view']<1000){
                           $value=  mt_rand(0, 150);
                       }else if($item['total_view']<5000){
                           $value=  mt_rand(0, 99);
                       }else{
                           $value=  mt_rand(0, 9);
                       }*/
                    $this->upHelpPv($item['id'],$value);
                }
            }
            $page++;
        }while($total>($page*500));
        WebFacade::clearPageCache('urla:');
    }

    /**
     * 帮助推荐设置
     * */
    public function recommendSet($params){
        $id=empty($params['id'])?0:$params['id'];
        $isRecommend=empty($params['is_recommend'])?0:$params['is_recommend'];
        $ret= $this->model->where('id', '=', $id)
            ->update(['is_recommend' => $isRecommend,'update_time'=>nowTime()]);
        //更新所有页面缓存
        WebFacade::clearPageCache('urla:');
        return $id;
    }

    /**
     * 构建帮助保存数据
     * */
    private function buildHelpData($params){
        $saveData=[];
        $userId=$this->getAuthUserId();
        $nowTime=nowTime();
        $saveData['update_time']=$nowTime;
        if(!empty($params['id'])){
            $saveData['id']=$params['id'];
            if (isset($params['seo_id'])) {
                $saveData['seo_id'] = $params['seo_id'];
            }
            if(isset($params['pub_date'])){
                $saveData['pub_date']=empty($params['pub_date'])?null:$params['pub_date'];;
            }
            if(isset($params['title'])){
                $nameUnique =$this->model->checkNameUnique($params['title'],$params['id']);
                if (!$nameUnique) {
                    throw new ApiException(10018, ['name' => $params['title']]);
                }
                $saveData['title']=empty($params['title'])?'':$params['title'];
            }
            if(isset($params['content'])){
                $saveData['content']=empty($params['content'])?'':$params['content'];
            }
            if(isset($params['outline_bar'])){
                $saveData['outline_bar']=empty($params['outline_bar'])?'':json_encode($params['outline_bar']);
            }
            if(isset($params['description'])){
                $saveData['description']=empty($params['description'])?'':$params['description'];
            }
            if(isset($params['image_url'])){
                $saveData['image_url']=empty($params['image_url'])?'':$params['image_url'];
            }
            if(isset($params['image_alt'])){
                $saveData['image_alt']=empty($params['image_alt'])?'':$params['image_alt'];
            }
            if(isset($params['main_image'])){
                $saveData['main_image']=empty($params['main_image'])?'':$params['main_image'];
            }
            if(isset($params['main_image_alt'])){
                $saveData['main_image_alt']=empty($params['main_image_alt'])?'':$params['main_image_alt'];
            }
            if(isset($params['download_url'])){
                $saveData['download_url']=empty($params['download_url'])?'':$params['download_url'];
            }
            if(isset($params['sort'])){
                $saveData['sort']=empty($params['sort'])?0:$params['sort'];
            }
            if(isset($params['is_top'])){
                $saveData['is_top']=empty($params['is_top'])?0:$params['is_top'];
            }
            if(isset($params['status'])){
                $saveData['status']=$params['status'];
            }
        }else{
            $nameUnique =$this->model->checkNameUnique($params['title']);
            if (!$nameUnique) {
                throw new ApiException(10018, ['name' => $params['title']]);
            }

            if(empty($params['title'])){
                throw new ApiException(11002);
            }
            if(isset($params['status'])){
                $saveData['status']=$params['status'];
            }
            $saveData['user_id']=$userId;
            $saveData['pub_date']=empty($params['pub_date'])?null:$params['pub_date'];
            $saveData['title']=empty($params['title'])?'':$params['title'];
            $saveData['content']=empty($params['content'])?'':$params['content'];
            $saveData['outline_bar']=empty($params['outline_bar'])?'':json_encode($params['outline_bar']);
            $saveData['description']=empty($params['description'])?'':$params['description'];
            $saveData['image_url']=empty($params['image_url'])?'':$params['image_url'];
            $saveData['image_alt']=empty($params['image_alt'])?'':$params['image_alt'];
            $saveData['main_image']=empty($params['main_image'])?'':$params['main_image'];
            $saveData['main_image_alt']=empty($params['main_image_alt'])?'':$params['main_image_alt'];
            $saveData['virtual_view']=empty($params['virtual_view'])?0:$params['virtual_view'];
            $saveData['total_view']=$saveData['virtual_view'];
            $saveData['download_url']=empty($params['download_url'])?'':$params['download_url'];
            $saveData['sort']=empty($params['sort'])?0:$params['sort'];
            $saveData['create_time']=$nowTime;

        }
        return $saveData;
    }

    public function updatePv($id,$newVirtualView){

        $virtualView = $this->getFieldById('virtual_view', $id);
        $value=$newVirtualView-$virtualView;
        $ret= $this->model->where('id','=',$id)->increment('total_view',$value);
        $ret= $this->model->where('id','=',$id)->increment('virtual_view',$value);
        WebFacade::clearPageCache('urla:');
        return $ret;
    }

    /**
     * 更新帮助浏览量
     * */
    public function upHelpPv($helpId, $value=1) {
        if($value>1){
            $ret= $this->model->where('id','=',$helpId)->increment('total_view',$value);
            $ret= $this->model->where('id','=',$helpId)->increment('virtual_view',$value);
        }else{
            $totalView = $this->getFieldById('total_view', $helpId);
            $value = (($value * -1) > $totalView) ? ($totalView * -1) : $value;
            $ret= $this->model->where('id','=',$helpId)->increment('total_view',$value);
        }
        return $ret;
    }

    /**
     * 帮助列表
     * */
    public function getHelpList($params){
        $ret=$this->model->getHelpList($params);
        $pageListData=empty($ret['data'])?[]:$ret['data'];
        if(!empty($pageListData)){
            $ids=array_column($pageListData,'seo_id');
            $seoList=[];
            if(!empty($ids)){
                $seoList=WebFacade:: getSeoListByIds($ids);
                if(!empty($seoList)){
                    $seoList=mapByKey($seoList,'id');
                }
            }
            foreach ($pageListData as &$pageItem){
                $pageItem['seo_data']=empty($seoList[$pageItem['seo_id']])?[]:$seoList[$pageItem['seo_id']];
            }
        }
        $ret['data']=$pageListData;
        return $ret;
    }

    /**
     * 获取帮助详情
     * */
    public function getHelpInfo($params){
        $helpInfo= $this->model->getHelpInfo($params);
        if(!empty($helpInfo)){
            if(!empty($helpInfo['seo_id'])){
                $helpInfo['seo_data']=WebFacade::getSeoInfo(['id'=>$helpInfo['seo_id']]);
            }else{
                $helpInfo['seo_data'] = [
                    'seo_describe' => '',
                    'seo_keyword' => '',
                    'seo_title' => '',
                    'urla' => ''
                ];
            }
            $helpInfo['type_ids']=$this->helpTypeRelationModel->getTypeIds($helpInfo['id']);
            $helpInfo['tag_ids']=$this->helpTagRelationModel->getTagIds($helpInfo['id']);
        }

        return $helpInfo;
    }

    /**
     * 获取帮助分类未关联的帮助
     * */
    public function getUnrelatedHelpByTypeIds($params){
        $ret=$this->model->getUnrelatedHelpByTypeIds($params);
        return $ret;
    }

    /**
     * 获取帮助标签未关联的帮助
     * */
    public function getUnrelatedHelpByTagIds($params){
        $ret=$this->model->getUnrelatedHelpByTagIds($params);
        return $ret;
    }

    /**
     * 获取已发布的连接
     * */
    public function getPublishHelpList($params,$fields=''){
        if(empty($fields)){
            $fields="a.id,a.pub_date,a.title,a.description,a.image_url,a.image_alt,'' is_top,".
                "'' is_recommend,a.download_url,a.total_view,b.urla";
        }
        $helpList=$this->model->getPublishHelpList($params,$fields);
        $helpIds=array_column($helpList,'id');
        if($helpIds){
            $newestTypeAndTagData=$this->getTypeAndTagDataByHelpId($helpIds);
            foreach ($helpList as &$newestItem){
                if(!empty($newestTypeAndTagData[$newestItem['id']]['type_items'])){
                    $newestItem['type_items']=$newestTypeAndTagData[$newestItem['id']]['type_items'];
                }else{
                    $newestItem['type_items']=[];
                }
                if(!empty($newestTypeAndTagData[$newestItem['id']]['tag_items'])){
                    $newestItem['tag_items']=$newestTypeAndTagData[$newestItem['id']]['tag_items'];
                }else{
                    $newestItem['tag_items']=[];
                }
            }
        }
        return $helpList;
    }

    /**
     * 获取帮助详情渲染数据
     * */
    public function getHelpRenderData($params){
        $helpInfo= $this->model->getHelpInfo($params);
        if(!empty($helpInfo)){
            if(!empty($helpInfo['outline_bar'])){
                $helpInfo['outline_bar']=json_decode($helpInfo['outline_bar'],true);
            }
            $newestTypeAndTagData=$this->getTypeAndTagDataByHelpId([$helpInfo['id']]);
            if(!empty($newestTypeAndTagData[$helpInfo['id']]['type_items'])){
                $helpInfo['type_items']=$newestTypeAndTagData[$helpInfo['id']]['type_items'];
            }else{
                $helpInfo['type_items']=[];
            }
            if(!empty($newestTypeAndTagData[$helpInfo['id']]['tag_items'])){
                $helpInfo['tag_items']=$newestTypeAndTagData[$helpInfo['id']]['tag_items'];
            }else{
                $helpInfo['tag_items']=[];
            }
        }
        return $helpInfo;
    }


    public function getHelpTypeRenderInfo($params){
        $typeWhere=[];
        $typeWhere['status']=0;
        $typeWhere['id']=empty($params['id'])?0:$params['id'];
        $typeInfo=$this->helpTypeModel->getHelpTypeInfo($typeWhere);
        return $typeInfo;
    }

    /**
     * 获取类型帮助列表页渲染数据
     * */
    public function getHelpTypeRenderData($params=[]){
        $data=[
            'type_info'=>[],//最新板块帮助列表
           'type_help_list'=>[],//帮助板块列表
            'hot_news_list'=>[],//热门帮助列表
            'recommend_news_list'=>[],//推荐帮助列表
            'hot_news_tag'=>[],//热门标签
        ];
        $typeWhere=[];
        $typeWhere['status']=0;
        $typeWhere['id']=empty($params['type_id'])?0:$params['type_id'];
        $typeInfo=$this->helpTypeModel->getHelpTypeInfo($typeWhere);
        $helpTypeListParams=[];
        $helpTypeListParams['page_size']=empty($params['page_size'])?10:$params['page_size'];
        $helpTypeListParams['page']=empty($params['page'])?1:$params['page'];
        $fields="a.id,a.pub_date,a.title,a.description,a.image_url,a.image_alt,".
            " '' is_top,'' is_recommend,a.download_url,a.total_view,b.type_id,c.urla";
        $helpList=$this->model->getRenderListByTypeIds([$typeInfo['id']],$helpTypeListParams,$fields);
        $helpIds=array_column($helpList,'id');
        $typeInfo['help_list']=[];
        if($helpIds){
            $helpTypeAndTagData=$this->getTypeAndTagDataByHelpId($helpIds);
            foreach ($helpList as $helpItem){
                if(!empty($helpTypeAndTagData[$helpItem['id']]['type_items'])){
                    $helpItem['type_items']=$helpTypeAndTagData[$helpItem['id']]['type_items'];
                }else{
                    $helpItem['type_items']=[];
                }
                if(!empty($helpTypeAndTagData[$helpItem['id']]['tag_items'])){
                    $helpItem['tag_items']=$helpTypeAndTagData[$helpItem['id']]['tag_items'];
                }else{
                    $helpItem['tag_items']=[];
                }
                $typeInfo['help_list'][]=$helpItem;
            }
        }
        $data['type_info']=$typeInfo;
        //热门帮助列表
        $data['hot_news_list']=$this->getHotList($params);
        //推荐帮助列表
        $data['recommend_news_list']=$this->getRecommendList($params);
        //热门标签
        $data['hot_news_tag']=$this->helpTagModel->getBaseTagList(['is_hot'=>1]);
        return $data;
    }

    /**
     * 获取标签帮助列表页渲染数据
     * */
    public function getHelpTagRenderData($params=[]){
        $data=[
            'tag_info'=>[],//最新板块帮助列表
            'tag_help_list'=>[],//帮助板块列表
            'hot_news_list'=>[],//热门帮助列表
            'recommend_news_list'=>[],//推荐帮助列表
            'hot_news_tag'=>[],//热门标签
        ];
        $tagWhere=[];
        $tagWhere['status']=0;
        $tagWhere['id']=empty($params['tag_id'])?0:$params['tag_id'];
        $tagInfo=$this->helpTagModel->getHelpTagInfo($tagWhere);

        $helpTagListParams=[];
        $helpTagListParams['page_size']=empty($params['page_size'])?10:$params['page_size'];
        $helpTagListParams['page']=empty($params['page'])?1:$params['page'];
        $fields="a.id,a.pub_date,a.title,a.description,a.image_url,a.image_alt,".
            " '' is_top,'' is_recommend,a.download_url,a.total_view,b.type_id,c.urla";
        $helpList=$this->model->getRenderListByTagIds([$tagInfo['id']],$helpTagListParams,$fields);
        $helpIds=array_column($helpList,'id');
        $tagInfo['help_list']=[];
        if($helpIds){
            $helpTypeAndTagData=$this->getTypeAndTagDataByHelpId($helpIds);
            foreach ($helpList as $helpItem){
                if(!empty($helpTypeAndTagData[$helpItem['id']]['type_items'])){
                    $helpItem['type_items']=$helpTypeAndTagData[$helpItem['id']]['type_items'];
                }else{
                    $helpItem['type_items']=[];
                }
                if(!empty($helpTypeAndTagData[$helpItem['id']]['tag_items'])){
                    $helpItem['tag_items']=$helpTypeAndTagData[$helpItem['id']]['tag_items'];
                }else{
                    $helpItem['tag_items']=[];
                }
                $tagInfo['help_list'][]=$helpItem;
            }
        }
        $data['tag_info']=$tagInfo;
        //热门帮助列表
        $data['hot_news_list']=$this->getHotList($params);
        //推荐帮助列表
        $data['recommend_news_list']=$this->getRecommendList($params);
        //热门标签
        $data['hot_news_tag']=$this->helpTagModel->getBaseTagList(['is_hot'=>1]);
        return $data;
    }

    /**
     * 最新帮助列表
     * */
    public function getNewestHelpList($params){
        $newestListParams=[];
        $newestListParams['page_size']=empty($params['page_size'])?10:$params['page_size'];
        $newestListParams['page']=empty($params['page'])?1:$params['page'];
        $newestListParams['sort']['pub_date']=1;
        $newestListParams['only_List']=1;
        $newestList=$this->getPublishHelpList($newestListParams);
        return $newestList;
    }

    /**
     * 热门帮助列表
     * */
    public function getHotList($params){
        $hotListParams=[];
        $hotListParams['page_size']=empty($params['hot_news_size'])?4:$params['hot_news_size'];
        $hotListParams['sort']['is_hot']=1;
        $hotListParams['sort']['pub_date']=1;
        $hotList=$this->getPublishHelpList($hotListParams);
        return $hotList;
    }

    /**
     * 推荐帮助列表
     * */
    public function getRecommendList($params){
        $recommendListParams=[];
        $recommendListParams['page_size']=empty($params['recommend_news_size'])?4:$params['recommend_news_size'];
        $recommendListParams['sort']['is_recommend']=1;
        $recommendListParams['sort']['pub_date']=1;
        $recommendList=$this->getPublishHelpList($recommendListParams);
        return $recommendList;
    }


    /**
     * 根据帮助id获取帮助类型及帮助标签数据
     * */
    public function getTypeAndTagDataByHelpId($newestHelpIds){
        $resultData=[];
        $newestTypeData=$this->helpTypeRelationModel->getTypeListByHelpIds($newestHelpIds);
        foreach ($newestTypeData as $typeItem){
            $resultData[$typeItem['help_id']]['type_items'][]=$typeItem;
        }
        $newestTagData=$this->helpTagRelationModel->getTagListByHelpIds($newestHelpIds);
        foreach ($newestTagData as $tagItem){
            $resultData[$tagItem['help_id']]['tag_items'][]=$tagItem;
        }
        return $resultData;
    }

    /**
     * 根据类型id获取帮助
     * */
    public function getPublishHelpListByTypeId($params){
        $fields="a.id,a.pub_date,a.title,a.description,a.image_url,a.image_alt,'' is_top,'' is_recommend,a.download_url,a.total_view,b.type_id,c.urla";
        $ret=$this->model->getPublishHelpListByTypeId($params,$fields);
        $helpData=empty($ret['data'])?[]:$ret['data'];
        if(!empty($helpData)){
            $newestHelpIds=array_column($helpData,'id');
            $newestTypeAndTagData=$this->getTypeAndTagDataByHelpId($newestHelpIds);
            foreach ($helpData as &$newestItem){
                if(!empty($newestTypeAndTagData[$newestItem['id']]['type_items'])){
                    $newestItem['type_items']=$newestTypeAndTagData[$newestItem['id']]['type_items'];
                }else{
                    $newestItem['type_items']=[];
                }
                if(!empty($newestTypeAndTagData[$newestItem['id']]['tag_items'])){
                    $newestItem['tag_items']=$newestTypeAndTagData[$newestItem['id']]['tag_items'];
                }else{
                    $newestItem['tag_items']=[];
                }
            }
            $ret['data']=$helpData;
        }

        return $ret;
    }

    /**
     * 根据标签id获取帮助
     * */
    public function getPublishHelpListByTagId($params){
        $fields="a.id,a.pub_date,a.title,a.description,a.image_url,a.image_alt,'' is_top,'' is_recommend,a.download_url,a.total_view,b.tag_id,c.urla";
        $ret=$this->model->getPublishHelpListByTagId($params,$fields);
        $helpData=empty($ret['data'])?[]:$ret['data'];
        if(!empty($helpData)){
            $newestHelpIds=array_column($helpData,'id');
            $newestTypeAndTagData=$this->getTypeAndTagDataByHelpId($newestHelpIds);
            foreach ($helpData as &$newestItem){
                if(!empty($newestTypeAndTagData[$newestItem['id']]['type_items'])){
                    $newestItem['type_items']=$newestTypeAndTagData[$newestItem['id']]['type_items'];
                }else{
                    $newestItem['type_items']=[];
                }
                if(!empty($newestTypeAndTagData[$newestItem['id']]['tag_items'])){
                    $newestItem['tag_items']=$newestTypeAndTagData[$newestItem['id']]['tag_items'];
                }else{
                    $newestItem['tag_items']=[];
                }
            }
            $ret['data']=$helpData;
        }
        return $ret;
    }

    /**
     * 搜索获取已发布的帮助
     * */
    public function getSearchHelpList($params){
        if(empty($fields)){
            $fields='a.id,a.title,b.urla';
        }
        $helpList=$this->model->getPublishHelpList($params,$fields);
        return $helpList;
    }

    /**
     * 新闻排序
     */
    public function changeHelpSort($helpId, $sort)
    {
        $data = [];
        $getData = $this->findOneById($helpId, 'id,sort');
        if ($sort == 0) { // 置顶
            $sortData = $this->findOneBy([
                'sort' => $sort,
                'id' => ['<>', $helpId]
            ], 'id');
            if (empty($sortData['id'])) {
                throw new ApiException(1004, ['msg' => '当前已经是最高一行']);
            }
            if ($getData['sort'] == 0) {
                $this->incrementBy([
                    'id' => ['<>', $helpId],
                ], 'sort');
            } else {
                $this->incrementBy([
                    'id' => ['<', $helpId],
                ], 'sort');
            }
            $upData['sort']= $sort;
        } elseif ($sort == '-1') { // 上移
            $upSortData = $this->model->where('sort', '<', $getData['sort'])
                ->orderBy('sort', 'desc')->first();
            if (empty($upSortData)) {
                throw new ApiException(1004, ['msg' => '当前已经是最高一行']);
            } else {
                $upData = $upSortData->toArray();
            }
        } elseif ($sort == '+1') { // 下移
            $downSortData = $this->model->where('sort', '>', $getData['sort'])
                ->orderBy('sort', 'asc')->first();
            if (empty($downSortData)) {
                throw new ApiException(1004, ['msg' => '当前已经是最后一行']);
            } else {
                $upData = $downSortData->toArray();
            }
        }
        $data['sort'] = $upData['sort'];
        $this->updateBy([
            'sort' => $data['sort'],
        ], [
            'sort' => $getData['sort']
        ]);
        $is_top=0;
        if($data['sort']==0){
            $is_top=1;
        }
        $rst = $this->update($helpId, [
            'sort' => $data['sort'],
            'is_top'=>$is_top
        ]);
        //更新所有页面缓存
        WebFacade::clearPageCache('urla:');
        return $rst;

    }
}
