<?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\Exceptions\ApiException;
use App\Services\CommonUserBaseService;
use App\Web\Facades\SuccessCaseFacade;
use App\Web\Facades\HelpFacade;
use App\Web\Facades\WebFacade;
use App\Web\Models\DictFunctionModel;
use App\Web\Models\DictIndustryModel;
use App\Web\Models\SuccessCaseModel;
use App\Web\Models\WebSeoModel;
use App\Web\Models\WebStaticPageModel;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;


class SuccessCaseService extends CommonUserBaseService
{
    protected $cache = true;

    protected $cacheBucket = 'SuccessCase:';




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

    /**
     * 保存成功案例数据
     * */
    public function saveSuccessCase($params){
        $saveData=$this->buildSuccessCaseData($params);
        $userId=$this->getAuthUserId();
        $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->saveSuccessCaseData($saveData);
        if(!empty($id)){
            if(isset($params['seo_data'])){
                $seoParams=[];
                $seoParams['relation_table']=WebService::RELATION_TABLE_SUCCESS_CASE;
                $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($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($saveData['status'])&&$saveData['status']==2){
                //移除对应seo
                $delSeoParams=[];
                $delSeoParams['relation_table']=WebService::RELATION_TABLE_SUCCESS_CASE;
                $delSeoParams['relation_id']=$id;
                $ret = WebFacade::delSeoByRelation($delSeoParams);
            }
        }
        //更新所有页面缓存
        WebFacade::clearPageCache('urla:');
        return $id;
    }

    /**
     * 构建成功案例保存数据
     * */
    private function buildSuccessCaseData($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['title'])){
                $titleUnique =$this->model->checkTitleUnique($params['title'],$params['id']);
                if (!$titleUnique) {
                    throw new ApiException(10018, ['name' => $params['title']]);
                }
                $saveData['title']=empty($params['title'])?'':$params['title'];
            }
            if(isset($params['pub_date'])){
                $saveData['pub_date']=empty($params['pub_date'])?null:$params['pub_date'];;
            }
            if(isset($params['description'])){
                $saveData['description']=empty($params['description'])?'':$params['description'];
            }
            if(isset($params['content'])){
                $saveData['content']=empty($params['content'])?'':$params['content'];
            }
            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['up_data'])){
                $saveData['up_data']=empty($params['up_data'])?'':json_encode($params['up_data']);
            }
            if(isset($params['function_id'])){
                $saveData['function_id']=empty($params['function_id'])?0:$params['function_id'];
            }
            if(isset($params['industry_id'])){
                $saveData['industry_id']=empty($params['industry_id'])?0:$params['industry_id'];
            }
            if(isset($params['company_name'])){
                $saveData['company_name']=empty($params['company_name'])?'':$params['company_name'];
            }
            if(isset($params['company_desc'])){
                $saveData['company_desc']=empty($params['company_desc'])?'':$params['company_desc'];
            }
            if(isset($params['company_logo'])){
                $saveData['company_logo']=empty($params['company_logo'])?'':$params['company_logo'];
            }
            if(isset($params['virtual_view'])){
                $saveData['virtual_view']=empty($params['virtual_view'])?0:$params['virtual_view'];
            }
            if(isset($params['sort'])){
                $saveData['sort']=empty($params['sort'])?0:$params['sort'];
            }
            if(isset($params['status'])){
                $saveData['status']=$params['status'];
            }
        }else{
            $titleUnique =$this->model->checkTitleUnique($params['title']);
            if (!$titleUnique) {
                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['title']=empty($params['title'])?'':$params['title'];
            $saveData['pub_date']=empty($params['pub_date'])?null:$params['pub_date'];
            $saveData['description']=empty($params['description'])?'':$params['description'];
            $saveData['content']=empty($params['content'])?'':$params['content'];
            $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['up_data']=empty($params['up_data'])?'':json_encode($params['up_data']);
            $saveData['function_id']=empty($params['function_id'])?0:$params['function_id'];
            $saveData['industry_id']=empty($params['industry_id'])?0:$params['industry_id'];
            $saveData['company_name']=empty($params['company_name'])?'':$params['company_name'];
            $saveData['company_desc']=empty($params['company_desc'])?'':$params['company_desc'];
            $saveData['company_logo']=empty($params['company_logo'])?'':$params['company_logo'];
            $saveData['virtual_view']=empty($params['virtual_view'])?0:$params['virtual_view'];
            $saveData['sort']=empty($params['sort'])?0:$params['sort'];
            $saveData['create_time']=$nowTime;

        }
        return $saveData;
    }

    /**
     * 成功案例列表
     * */
    public function getSuccessCaseList($params){
        $ret=$this->model->getSuccessCaseList($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']];
                $pageItem['urla']=empty($seoList[$pageItem['seo_id']]['urla'])?'':$seoList[$pageItem['seo_id']]['urla'];
            }
        }
        $ret['data']=$pageListData;
        return $ret;
    }

    /**
     * 获取成功案例详情
     * */
    public function getSuccessCaseInfo($params){
        $caseInfo= $this->model->getSuccessCaseInfo($params);
        if(!empty($caseInfo)){
            if(!empty($caseInfo['seo_id'])){
                $caseInfo['seo_data']=WebFacade::getSeoInfo(['id'=>$caseInfo['seo_id']]);
            }else{
                $caseInfo['seo_data'] = [
                    'seo_describe' => '',
                    'seo_keyword' => '',
                    'seo_title' => '',
                    'urla' => ''
                ];
            }
            $caseInfo['up_data']=empty($caseInfo['up_data'])?[]:json_decode($caseInfo['up_data'],true);
        }

        return $caseInfo;
    }

    /**
     * 新闻排序
     */
    public function changeSuccessCaseSort($caseId, $sort)
    {
        $data = [];
        $getData = $this->findOneById($caseId, 'id,sort');
        if ($sort == 0) { // 置顶
            $sortData = $this->findOneBy([
                'sort' => $sort,
                'id' => ['<>', $caseId]
            ], 'id');
            if (empty($sortData['id'])) {
                throw new ApiException(1004, ['msg' => '当前已经是最高一行']);
            }
            if ($getData['sort'] == 0) {
                $this->incrementBy([
                    'id' => ['<>', $caseId]
                ], 'sort');
            } else {
                $this->incrementBy([
                    'id' => ['<', $caseId]
                ], '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']
        ]);
        $rst = $this->update($caseId, [
            'sort' => $data['sort']
        ]);
        //更新所有页面缓存
        WebFacade::clearPageCache('urla:');
        return $rst;

    }

    /**
     * 更新成功案例浏览量
     * */
    public function upSuccessCasePv($caseId, $value=1) {
        if($value>1){
            $ret= $this->model->where('id','=',$caseId)->increment('total_view',$value);
            $ret= $this->model->where('id','=',$caseId)->increment('virtual_view',$value);
        }else{
            $totalView = $this->getFieldById('total_view', $caseId);
            $value = (($value * -1) > $totalView) ? ($totalView * -1) : $value;
            $ret= $this->model->where('id','=',$caseId)->increment('total_view',$value);
        }
        return $ret;
    }

    /**
     * 获取成功案例详情渲染数据
     * */
    public function getSuccessCaseRenderData($params){
        $caseInfo= $this->model->getSuccessCaseInfo($params);
        if(!empty($caseInfo)){
            if(!empty($caseInfo['up_data'])){
                $caseInfo['up_data']=json_decode($caseInfo['up_data'],true);
            }
        }
        return $caseInfo;
    }

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