<?php
namespace App\JsonRpc;
use App\Model\Ad;
use App\Model\AdPlace;
use App\Model\AdSize;
use Hyperf\RpcServer\Annotation\RpcService;
use App\Tools\Result;
use Hyperf\DbConnection\Db;
use App\Model\WebsiteTemplate;

#[RpcService(name: "AdService", protocol: "jsonrpc-http", server: "jsonrpc-http")]
class AdService implements AdServiceInterface
{
    /**
     * @param array $data
     * @return string
     */
    public function createAd(array $data): array
    {
        $insertData = [
            'name'=>$data['name']??'',
            'pid'=>$data['pid']??0,
            'areaid'=>$data['areaid']??0,
            'amount'=>$data['amount']??0,//浏览数量
            'introduce'=>$data['introduce']??'',
            'hits'=>$data['hits']??0, //点击数量
            'fromtime'=>$data['f_t_date'][0]??0,
            'totime'=>$data['f_t_date'][1]??0,
            'text_name'=>$data['text_name']??'',
            'text_url'=>$data['text_url']??'',
            'text_title'=>$data['text_title']??'',
            'image_src'=>$data['image_src']??'',
            'image_url'=>$data['image_url']??'',
            'image_alt'=>$data['image_alt']??'',
            'video_src'=>$data['video_src']??'',//视频
            'video_url'=>$data['video_url']??'',
            'video_auto'=>$data['video_auto'] ??0,
            'video_loop'=>$data['video_loop'] ??0,
            'status'=>$data['status']??2,
            'remark'=>$data['remark']??'',
        ];
        $result = Ad::query()->insertGetId($insertData);
        if($result){
            return Result::success();
        }else{
            return Result::error("创建广告失败",500);
        }
    }
    /**
     * @param int $id
     * @return array
     */
    public function getAdInfo(int $id): array
    {
        $adInfo = Ad::query()->find($id);
        if (empty($adInfo)) {
            return Result::error("没有数据",0);
        }
        return Result::success($adInfo->toArray());
    }

    /**
     * @param array $data
     * @return array
     */
    public function getAdList(array $data): array
    {
        if(isset($data['pid'])){
            $where[] =   ['ad.pid','=',$data['pid']];
        }
        $rep = Ad::where($where)
            ->leftJoin("ad_place","ad.pid","ad_place.id")
            ->leftJoin("website","website.id","ad_place.website_id")
            ->select("ad.*","ad_place.name as place_name","ad_place.typeid","website.website_name")
            ->limit($data['pageSize'])->orderBy("ad.id","desc")->offset(($data['page']-1)*$data['pageSize'])->get();
        $count =  Ad::where($where)
            ->leftJoin("ad_place","ad.pid","ad_place.id")
            ->leftJoin("website","website.id","ad_place.website_id")
            ->count();
        $data = [
            'rows'=>$rep->toArray(),
            'count'=>$count
        ];
        if(empty($rep->toArray())){
            return Result::error("没有数据");
        }
        return Result::success($data);
    }

    public function updateAd(array $data): array
    {
        $where = [
            'id'=>$data['id']
        ];
        $insertData = [
            'name'=>$data['name']??'',
            'pid'=>$data['pid']??0,
            'areaid'=>$data['areaid']??0,
            'amount'=>$data['amount']??0,//浏览数量
            'introduce'=>$data['introduce']??'',
            'hits'=>$data['hits']??0, //点击数量
            'fromtime'=>$data['f_t_date'][0]??0,
            'totime'=>$data['f_t_date'][1]??0,
            'text_name'=>$data['text_name']??'',
            'text_url'=>$data['text_url']??'',
            'text_title'=>$data['text_title']??'',
            'image_src'=>$data['image_src']??'',
            'image_url'=>$data['image_url']??'',
            'image_alt'=>$data['image_alt']??'',
            'video_src'=>$data['video_src']??'',//视频
            'video_url'=>$data['video_url']??'',
            'video_auto'=>isset($data['video_auto']) && empty($data['video_auto'])?0:$data['video_auto'],
            'video_loop'=>isset($data['video_loop']) && empty($data['video_loop'])?0:$data['video_loop'],
            'status'=>$data['status']??2,
            'remark'=>$data['remark']??'',
        ];
        $result = Ad::where($where)->update($insertData);
        if($result){
            return Result::success($result);
        }else{
            return Result::error("更新失败");
        }
    }

    public function delAd(array $data): array
    {
        $result = Ad::where($data)->delete();
        if(!$result){
            return Result::error("删除失败");
        }
        return Result::success($result);
    }

    /**
     * 广告位列表
     * @param array $data
     * @return array
     */
    public function getAdPlaceList(array $data): array
    {

        $where = [];
        if(isset($data['name'])  && $data['name']){
            array_push($where,['ad_place.name','like','%'.$data['name'].'%']);
        }
        if(isset($data['website_id'])  && $data['website_id']){
            array_push($where,['ad_place.website_id','=',$data['website_id']]);
        }
        $rep = AdPlace::where($where)
            ->leftJoin("ad_size","ad_place.ad_size_id","ad_size.id")
            ->leftJoin("website","website.id","ad_place.website_id")
            ->limit($data['pageSize'])
            ->orderBy("ad_place.updated_at","desc")
            ->offset(($data['page']-1)*$data['pageSize'])
            ->select("ad_place.*","ad_size.width","ad_size.height","website.website_name","website.website_column_id","website.website_column_arr_id")
            ->get();
        if($rep){
            foreach ($rep as $key=>$val){
                $rep[$key]['website_column_arr_id'] = json_decode($val['website_column_arr_id'],true);
            }
        }
        $count =  AdPlace::where($where)->count();
        $reponse = [
            'rows'=>$rep->toArray(),
            'count'=>$count
        ];
        if(empty($rep->toArray())){
            return Result::error("没有数据");
        }
        return Result::success($reponse);
    }

    public function createAdPlace(array $data): array
    {
        unset($data['size']);
        $result = AdPlace::query()->insertGetId($data);
        if($result){
            return Result::success();
        }else{
            return Result::error("创建广告位失败",500);
        }
    }
    /**
     * @param array $data 
     * @return array 
     */ 
    public function updateAdPlace(array $data): array   
    {
        // 11
        $where = [ 
            'ad_place.id'=>$data['id'] 
        ]; 
        // $website_id = intval($data['website_id']);

        // 原代码 leftJoin 条件使用错误，第三个参数应该是关联字段，这里修正为 "website.id" 关联 "ad_place.website_id"
        $web = AdPlace::where($where)
        ->leftJoin("website","website.id","ad_place.website_id")
        ->select("website.*","ad_place.name",'ad_place.ad_tag')

        ->first();
        if(empty($web)){
            return Result::error("广告位不存在");
        }
        // 自助建站广告位-广告位编辑同步模板数据-------fr----start
        //  return Result::success($web);
        $website_column_arr_id = json_decode($web['website_column_arr_id'],true);
        Db::beginTransaction();
        try{
            // 判断网站的广告位是否通过自助建站创建的广告位（通过网系包含2来判断）
            if(!in_array(3,$website_column_arr_id)){
                $template_data = ['ad_tag'=>$web['ad_tag']];
                $template_data = array_merge($data,$template_data);
                $template_module = WebsiteTemplate::where('website_id',$template_data['website_id'])->first();
                $page_type = explode('_', $template_data['ad_tag']);
                // 页面类型
                $page = $page_type[1];
                $ad_places = [];
                // 模板数据及画布数据
                $oldtemplate_data = json_decode($template_module['template_data'],true);
                $oldcanvas_data = json_decode($template_module['canvas_data'],true);
                if(array_key_exists( $page,$oldtemplate_data['ad'])){
                    $ad_places = $oldtemplate_data['ad'][$page];
                }
                // return Result::success($ad_places);
                if($page == 'top'){
                    $ad_place = [
                        'width' => $oldtemplate_data['ad'][$page]['width'],
                        'height' => $oldtemplate_data['ad'][$page]['height'],
                        'name'=>$template_data['name'],   //广告位名称可更改
                        'price'=>$template_data['price'],   //广告位价格可更改
                        'introduce'=>$template_data['introduce'],   //广告位介绍可更改
                        'website_id'=>$oldtemplate_data['ad'][$page]['website_id'],
                        'thumb'=>$template_data['thumb'],   //广告位默认图可更改
                        'typeid'=>$oldtemplate_data['ad'][$page]['typeid'],
                        'ad_tag'=>$oldtemplate_data['ad'][$page]['ad_tag'],
                        'ad_url'=>$template_data['ad_url'],   //广告位默认链接可更改
                    ];
                }else{
                    foreach($ad_places as $key=>$val){
                        if($template_data['ad_tag'] == $val['ad_tag']){
                            $ad_place[$key] = [
                                'width' => $val['width'],
                                'height' => $val['height'],
                                'name'=>$template_data['name'],   //广告位名称可更改
                                'price'=>$template_data['price'],   //广告位价格可更改
                                'introduce'=>$template_data['introduce'],   //广告位介绍可更改
                                'website_id'=>$val['website_id'],
                                'thumb'=>$template_data['thumb'],   //广告位默认图可更改
                                'typeid'=>$val['typeid'],
                                'ad_tag'=>$val['ad_tag'],
                                'ad_url'=>$template_data['ad_url'],   //广告位默认链接可更改

                            ];
                            $template_ad = $ad_place[$key];
                        }else{
                            $ad_place[$key] = $val;
                        }


                    }
                    if(array_key_exists( $page,$oldtemplate_data['template'])){
                        $ad_places_info = $oldtemplate_data['template'][$page];
                    }
                    foreach($ad_places_info as $key=>$val){
                        $ad_info[$key] = $val;
                        if(array_key_exists('ad',$val) && $val['ad']['ad_tag'] == $template_data['ad_tag']){
                            $ad_info[$key]['ad'] = $template_ad;
                            $num = $key;
                        }
                    }
                    $canvas_data = $oldcanvas_data;
                    foreach($oldcanvas_data['template'][$page] as $key=>$val){
                        // $canvas_info_ad[$key] = $val;
                        if(array_key_exists('ad',$val['content']) && $val['content']['ad']['ad_tag'] == $template_data['ad_tag']){
                            // $canvas_info_ad[$key]['ad'] = $template_ad;
                            $canvas_ad['content']['ad'] = [
                                'width' => $val['content']['ad']['width'],
                                'height' => $val['content']['ad']['height'],
                                'name'=>$template_data['name'],   //广告位名称可更改
                                'price'=>$template_data['price'],   //广告位价格可更改
                                'introduce'=>$template_data['introduce'],   //广告位介绍可更改
                                'website_id'=>$val['content']['ad']['website_id'],
                                'thumb'=>$val['content']['ad']['thumb'],   //广告位默认图可更改
                                'typeid'=>$val['content']['ad']['typeid'],
                                'ad_tag'=>$val['content']['ad']['ad_tag'],
                            ];
                            $canvas_data['template'][$page][$key]['content']['ad'] = $canvas_ad['content']['ad'];
                        }
                    }
                    $oldtemplate_data['template'][$page] = $ad_info;    //模板广告位相关信息已修改
                }
                // return Result::success($ad_place);

                //  保存的模板中的广告位相关信息
                $oldtemplate_data['ad'][$page] = $ad_place;

                    
                    // Db::rollBack();
                // }
                
                
                if($page == 'top'){
                    $canvas_data['topAd'] = $ad_place;
                }
                // return Result::success($canvas_data);
                $template_module['canvas_data'] = json_encode($canvas_data,JSON_UNESCAPED_UNICODE);
                $template_module['template_data'] = json_encode($oldtemplate_data,JSON_UNESCAPED_UNICODE);
                $template_result = WebsiteTemplate::where('website_id',$template_data['website_id'])->update([
                    'canvas_data'=>$template_module['canvas_data'],
                    'template_data'=>$template_module['template_data'], 
                ]);
                if(!$template_result){
                    Db::rollBack();
                    return Result::error('同步模板失败！');
                }
            }
            // return Result::success($website_column_arr_id);
            $Insdata = [
                'website_id'=>$data['website_id']??'',
                'typeid'=>$data['typeid']??1,
                'status'=>$data['status']??2,
                'name'=>$data['name']??'',
                'thumb'=>$data['thumb']??'',
                'introduce'=>$data['introduce']??'',
                'code'=>$data['code']??'',
                'price'=>$data['price']??0,
                'ad_size_id'=>$data['ad_size_id']??0,
                'ad_url'=>$data['ad_url']??'',
                'ad_tag'=>$data['ad_tag']??'',

            ];
            $result = AdPlace::where($where)->update($Insdata);
            if(!$result){
                Db::rollBack();
                return Result::error("更新失败");
            }
            Db::commit();
            return Result::success($result);
        }catch (\Exception $e) {
            Db::rollBack();
            return Result::error($e->getMessage());
        }
        // 自助建站广告位-广告位编辑同步模板数据-------fr----end
        // 11--end
    }  
    /**
     * 删除广告位
     * @param array $data
     * @return array
     */
    public function delAdPlace(array $data): array
    {
        $adList = Ad::where(['pid'=>$data['id']])->get();
        if($adList->toArray()){
            return Result::error("广告位里面还有广告,不能删除广告位");
        }
        $result = AdPlace::where($data)->delete();
        if(!$result){
            return Result::error("删除失败");
        }
        return Result::success($result);
    }
    /**
     * @param int $id
     * @return array
     */
    public function getAdPlaceInfo(int $id): array
    {
        $adInfo = AdPlace::query()->find($id);
        if (empty($adInfo)) {
            return Result::error("没有数据",0);
        }
        return Result::success($adInfo->toArray());
    }

    /**
     * @param array $data
     * @return array
     */
    public function addTwinAdPlace(array $data): array
    {
        Db::beginTransaction();
        try {
            //根据传过来的website_id查询网站下的广告位 ad_tag字段组合成一个数组
            $adTagList = AdPlace::where(['website_id'=>$data['adPlaceList'][0]['website_id']])->pluck('ad_tag')->toArray();
            //循环传过来的adPlaceList数组取参数的ad_tag字段
            $adTagNewList = array_column($data['adPlaceList'],'ad_tag');
            //假设$adTagNewList=[1,2,3],$adTagList=[1,2,4,5] 我要取到$adTagList 里面的4,5
            $adTagDiffList = array_diff($adTagList,$adTagNewList);
            //删除AdPlace模型里面的$adTagDiffList 里面的广告位
            if($adTagDiffList){
                AdPlace::whereIn('ad_tag',$adTagDiffList)->delete();
            }
            if(isset($data['adPlaceList']) && $data['adPlaceList']){
                foreach ($data['adPlaceList'] as $key=>$val){
                    $adSizeInfo = AdSize::firstOrCreate(['width'=>$val['width'],'height'=>$val['height']]);
                    $adPlaceInfo = AdPlace::updateOrCreate(
                        [ 'ad_tag'=>$val['ad_tag'],'website_id'=>$val['website_id']],
                        [
                            'website_id'=>$val['website_id'],
                            'typeid'=>$val['typeid'],
                            'status'=>1,
                            'name'=>$val['name']??'',
                            'thumb'=>$val['thumb']??'',
                            'code'=>$val['code']??'',
                            'ad_size_id'=>$adSizeInfo->id,
                            'ad_tag'=>$val['ad_tag']??'',
                            'introduce'=>$val['introduce']??'',
                            'price'=>$val['price']??0,
                        ]
                    );
                }
            }
            Db::commit();
            return Result::success([]);
        }catch (\Exception $e){
            Db::rollBack();
            return Result::error("创建广告位失败".$e->getMessage(),0);
        }

    }

}