<?php


namespace App\Ad\Services;

use App\Ad\Models\SysAdModel;
use App\Ad\Models\SysAdPositionModel;
use App\Exceptions\ApiException;
use App\Services\CommonUserBaseService;
use App\Web\Facades\WebFacade;
use Illuminate\Support\Facades\Cache;

class SysAdService extends CommonUserBaseService
{
    protected $cache = true;

    protected $cacheBucket = 'SysAd:';

    protected $sysAdPositionModel;


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

    /**
     * 广告设置保存
     * */
    public function saveAd($params){
        $data= $this->buildAdData($params);
        if(!empty($data['id'])){
            $id = $data['id'];
            $this->model->where('id','=',$id)->update($data);
        } else {
            $id = $this->save($data)->id;
        }
        $this->clearAdCache();
        WebFacade::clearPageCache('urla:');
        return $id;
    }

    /**
     * 构造广告数据
     * */
    private function buildAdData($params,$userId = null){
        $userId = $userId ?? $this->getAuthUserId();
        $add = [];
        $nowTime = nowTime();
        $add['update_time']=$nowTime;
        if(!empty($params['id'])){
            $add['id']=$params['id'];
            if(isset($params['position_id'])){
                $add['position_id'] = $params['position_id'];
                if(empty($params['position_id'])){
                    throw new ApiException(12101);
                }
                $positionUnique =$this->model->checkPosition($params['position_id'],$params['id']);
                if (!$positionUnique) {
                    throw new ApiException(12102);
                }
            }
            if(isset($params['ad_title'])){
                $add['ad_title'] = empty($params['ad_title'])?'':$params['ad_title'];
            }
            if(isset($params['ad_file'])){
                $add['ad_file'] = empty($params['ad_file'])?'':$params['ad_file'];
            }
            if(isset($params['ad_description'])){
                $add['ad_description'] = empty($params['ad_description'])?'':json_encode($params['ad_description']);
            }
            if(isset($params['start_time'])){
                if(!empty($params['start_time'])){
                    $add['start_time']= $params['start_time'];
                }
            }
            if(isset($params['end_time'])){
                if(!empty($params['end_time'])){
                    $add['end_time']= $params['end_time'];
                }
            }
            if(isset($params['ad_link'])){
                $add['ad_link'] = empty($params['ad_link'])?'':$params['ad_link'];
            }
            if(isset($params['ad_link_type'])){
                $add['ad_link_type'] = empty($params['ad_link_type'])?0:$params['ad_link_type'];
            }
            if(isset($params['ad_script'])){
                $add['ad_script'] = empty($params['ad_script'])?'':$params['ad_script'];
            }
            if(isset($params['form_id'])){
                $add['form_id'] = empty($params['form_id'])?0:$params['form_id'];
            }
            if(isset($params['type'])){
                $add['type'] = empty($params['type'])?0:$params['type'];
            }
            if(isset($params['status'])){
                $add['status'] = empty($params['status'])?0:$params['status'];
            }
            if(isset($params['remark'])){
                $add['remark'] = empty($params['remark'])?'':$params['remark'];
            }
            if(isset($params['hit_num'])){
                $add['hit_num'] = empty($params['hit_num'])?0:$params['hit_num'];
            }
            if(isset($params['hit_click_num'])){
                $add['hit_click_num'] = empty($params['hit_click_num'])?0:$params['hit_click_num'];
            }
            if(isset($params['push_num'])){
                $add['push_num'] = empty($params['push_num'])?0:$params['push_num'];
            }
        }else{
            $add['position_id'] = empty($params['position_id'])?0:$params['position_id'];
            if(empty($params['position_id'])){
                throw new ApiException(12101);
            }
            $positionUnique =$this->model->checkPosition($params['position_id']);
            if (!$positionUnique) {
                throw new ApiException(12102);
            }
            $add['ad_title'] = empty($params['ad_title'])?'':$params['ad_title'];
            $add['ad_file'] = empty($params['ad_file'])?'':$params['ad_file'];
            $add['ad_description'] = empty($params['ad_description'])?'':json_encode($params['ad_description']);
            $add['ad_link'] = empty($params['ad_link'])?'':$params['ad_link'];
            $add['ad_link_type'] = empty($params['ad_link_type'])?0:$params['ad_link_type'];
            $add['ad_script'] = empty($params['ad_script'])?'':$params['ad_script'];
            $add['form_id'] = empty($params['form_id'])?0:$params['form_id'];
            $add['type'] = empty($params['type'])?0:$params['type'];
            $add['hit_num'] = empty($params['hit_num'])?0:$params['hit_num'];
            $add['hit_click_num'] = empty($params['hit_click_num'])?0:$params['hit_click_num'];
            $add['push_num'] = empty($params['push_num'])?0:$params['push_num'];
            $add['create_time'] = $nowTime;
            if(!empty($params['start_time'])){
                $add['start_time']= $params['start_time'];
            }
            if(!empty($params['end_time'])){
                $add['end_time']= $params['end_time'];
            }
            $add['user_id']=$userId;
        }
        return $add;
    }


    /**
     * 获取广告列表
     */
    public function getAdList($params)
    {
        $list = $this->model->getAdList($params);
        return $list;
    }

    /**
     * 获取详情
     */
    public function getAdInfo($id)
    {
        $fields = "a.*";
        $info = $this->findOneById($id, $fields);
        if (!empty($info['id'])) {
            $info['ad_title'] = json_decode($info['ad_title'], true)[0];
            $info['ad_description'] = json_decode($info['ad_description'], true)[0];
            $info['ad_script'] = json_decode($info['ad_script'], true);
        }
        return $info;
    }

    /**
     * 广告点击
     */
    public function adClick($id)
    {
        return $this->incrementBy([
            "id" => $id
        ], "hit_click_num");
    }

    /**
     * 根据广告位编号
     */
    public function getAdPositionList($params)
    {
        $list = $this->sysAdPositionModel->getAdPositionList($params);
        $data=!empty($list['data'])?$list['data']:[];
        foreach ($data as $adPositionItem){
            $adPositionItem['route_path_key']=json_decode($adPositionItem['route_path_key']);
        }
        $list['data']=$data;
        return $list;
    }

    /**
     * 获取所有已发布的广告
     * */
    public function getPublishAdData(){
        $data=$this->getCacheAdData();
        if(empty($data)){
            $params=[];
            $params['status']=0;
            $params['page_size']=999;
            $list = $this->model->getAdList($params);
            if(!empty($list['data'])){
                $data= $list['data'];
                $this->setAdCache($data);
            }
        }
        return $data;
    }

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

    /**
     * 获取广告缓存key
     * @param $urla
     * @return string
     */
    private function getCacheAdKey()
    {
        $pageParamsStr = 'web-ad-list:' . md5('web-ad-list');
        return $this->cacheBucket . $pageParamsStr;
    }

    /**
     * 缓存广告数据
     * @param array $adData
     */
    private function setAdCache($adData)
    {
        Cache::put($this->getCacheAdKey(), $adData, config('cache.page_time'));
    }

    /**
     * 清除广告数据缓存
     * */
    public function clearAdCache()
    {
        $this->removeByKey('web-ad-list');
    }

    /**
     * 获取页面广告数据
     * */
    public function getPageAdData($routePathKey){
        $retData=[];
        $adData=$this->getPublishAdData();
        if (!empty($adData)) {
            foreach ($adData as $value){
                if(!empty($value['route_path_key'])){
                    $routePathKeyArray=json_decode($value['route_path_key'],true);
                    if(in_array($routePathKey,$routePathKeyArray)){
                        $retData[]= $value;
                    }
                }
            }
        }
        return $retData;
    }
}
