<?php
namespace App\JsonRpc;                 

use App\Model\Ad;
use App\Model\AdPlace;
use App\Model\Article;
use App\Model\Department;
use App\Model\District;
use App\Model\Link;
use App\Model\TemplateClass;
use App\Model\Template;
use App\Model\WebsiteRole;
use App\Model\WebsiteRoleUser;
use App\Model\Website;
use App\Model\WebsiteColumn;
use Hyperf\RpcServer\Annotation\RpcService;
use App\Tools\Result;
use App\Model\WebsiteCategory;
use Carbon\Carbon;
use Directory;
use MathPHP\Exception\FunctionFailedToConvergeException;

use function PHPUnit\Framework\isNull;

#[RpcService(name: "WebsiteService", protocol: "jsonrpc-http", server: "jsonrpc-http")]
class WebsiteService implements WebsiteServiceInterface
{
    /**
     * @param string $keyword
     * @param int $page
     * @param int $pageSize
     * @return array
     */
    public function getWebsitetList(array $data): array
    {
        $where = [];
        if(isset($data['keyword']) && !empty($data['keyword'])){
            array_push($where,['website.website_name','like','%'.$data['keyword'].'%']);
        }
        if(isset($data['website_column_id']) && !empty($data['website_column_id'])){
            array_push($where,['website.website_column_id','=',$data['website_column_id']]);
        }
        if(isset($data['city_id']) && !empty($data['city_id'])){
            array_push($where,['website.city_id','=',$data['city_id']]);
        }

        $result = Website::where($where)
            ->leftJoin("website_column","website.website_column_id","website_column.id")
            ->leftJoin("district","district.id","website.city_id")
            ->select("website.*","website_column.column_name","district.name as city_name")
            ->limit($data['pageSize'])->offset(($data['page']-1)*$data['pageSize'])->get();

        $count = Website::where($where)->count();
        if (empty($result)) {
            return Result::error("没有数据",0);
        }
        $data = [
            'rows'=>$result->toArray(),
            'count'=>$count
        ];
        return Result::success($data);
    }

    /**
     * @param array $data
     * @return array
     */
    public function createWebsite(array $data): array
    {
        var_dump("网站数据:",$data);
        $insertData = [
            'website_name'=>$data['website_name'],
            'logo'=>$data['logo']??'',
            'website_url'=>$data['website_url']??'',
            'city_id'=>$data['city_id']??0,
            'website_column_id'=>$data['website_column_id'],
            'title'=>$data['title']??'',
            'keywords'=>$data['keywords']??'',
            'description'=>$data['description']??'',
            'status'=>$data['status']??0,
            'website_column_arr_id'=>$data['website_column_arr_id'],
            'city_arr_id'=>$data['city_arr_id']??[0],
            'template_id' =>$data['template_id']??0,
        ];
        $result = Website::insertGetId($insertData);
        if(empty($result)){
            return Result::error("创建失败",0);
        }else{
            return Result::success(["id"=>$result]);
        }
    }

    /**
     * @param int $id
     * @param array $data
     * @return array
     */
    public function updateWebsite(int $id,array $data): array
    {
        $insertData = [
            'website_name'=>$data['website_name'],
            'logo'=>$data['logo']??'',
            'website_url'=>$data['website_url']??'',
            'city_id'=>$data['city_id']??0,
            'website_column_id'=>$data['website_column_id'],
            'title'=>$data['title']??'',
            'keywords'=>$data['keywords']??'',
            'description'=>$data['description']??'',
            'status'=>$data['status']??0,
            'website_column_arr_id'=>$data['website_column_arr_id'],
            'city_arr_id'=>$data['city_arr_id']??[0],
            'template_id' =>$data['template_id']??0,
        ];
        $result = Website::where('id',$id)->update($insertData);
        var_dump("更新站点",$result);
        if(empty($result)){
            return Result::error("更新失败",0);
        }else{
            return Result::success();
        }
    }

    /**
     * @param int $id
     * @return array
     */
    public function delWebsite(int $id): array
    {
        $result = Website::where('id',$id )->delete();
        var_dump("删除站点",$result);
        if(empty($result)){
            return Result::error("删除失败",0);
        }else{
            return Result::success();
        }
    }

    /**
     * @param int $id
     * @return array
     */
    public function getWebsiteInfo(int $id): array
    {

        $where = [
            ['website.id','=',$id]
        ];
        $result = Website::where($where )
        ->leftJoin("template","template.id","website.template_id")
        ->select("website.*","template.template_name","template.template_img")
        ->first();
        if(empty($result)){
            return Result::error("数据不存在",0);
        }else{
            return Result::success($result->toArray());
        }

    }

    /**
     * 查询所有的站点栏目
     * @return array
     */
    public function getWebsiteColumn(array $data): array
    {
        $result = WebsiteColumn::where($data)->get();
        if(empty($result)){
            return Result::error("数据不存在",0);
        }else{
            return Result::success($result->toArray());
        }

    }


    /**
     * @param string $keyword
     * @param int $page
     * @param int $pageSize
     * @return array
     */
    public function getWebsiteColumnList(string $keyword,int $page,int $pageSize):array
    {
        $where = [
            ['website_column.column_name','like','%'.$keyword.'%']
        ];
        $result = WebsiteColumn::where($where)
            ->leftJoin("website_column as wc","website_column.pid","wc.id")
            ->select("website_column.*","wc.column_name as parent_column_name")
            ->limit($pageSize)->offset(($page-1)*$pageSize)->get();
        $count = WebsiteColumn::where($where)->count();
        if (empty($result)) {
            return Result::error("没有数据",0);
        }
        $data = [
            'rows'=>$result->toArray(),
            'count'=>$count
        ];
        return Result::success($data);
    }

    /**
     * @param array $data
     * @return array
     */
    public function createWebsiteColumn(array $data): array
    {
        $insertData = [
            'column_name'=>$data['column_name'],
            'pid'=>$data['pid']??'',
            'column_arr_id'=>$data['column_arr_id']??[0],
            'sort'=>$data['sort']??0,
            'remark'=>$data['remark']??'',
        ];
        $result = WebsiteColumn::insertGetId($insertData);
        if(empty($result)){
            return Result::error("创建失败",0);
        }else{
            return Result::success(["id"=>$result]);
        }
    }

    /**
     * @param int $id
     * @param array $data
     * @return array
     */
    public function updateWebsiteColumn(int $id,array $data): array
    {
        $insertData = [
            'column_name'=>$data['column_name'],
            'pid'=>$data['pid']??'',
            'column_arr_id'=>$data['column_arr_id']??[0],
            'sort'=>$data['sort']??0,
            'remark'=>$data['remark']??'',
        ];
        $result = WebsiteColumn::where('id',$id)->update($insertData);
        if(empty($result)){
            return Result::error("更新失败",0);
        }else{
            return Result::success();
        }
    }

    /**
     * @param int $id
     * @return array
     */
    public function delWebsiteColumn(int $id): array
    {
        $result = WebsiteColumn::where('id',$id )->delete();
        if(empty($result)){
            return Result::error("删除失败",0);
        }else{
            return Result::success();
        }
    }

    /**
     * @param string $keyword
     * @param int $page
     * @param int $pageSize
     * @return array
     */
    public function getWebsiteRoleList(string $keyword,int $page,int $pageSize,int $websiteId):array
    {
        $where = [
            ['role.role_name','like','%'.$keyword.'%'],
            ['website_role.website_id','=',$websiteId],
        ];
        $result = WebsiteRole::where($where)
            ->leftJoin("role","role.id","website_role.role_id")
            ->select("role.*","website_role.type","website_role.role_id","website_role.id as website_role_id","website_role.website_id")
            ->limit($pageSize)->offset(($page-1)*$pageSize)->get();
        $count = WebsiteRole::where($where) ->leftJoin("role","role.id","website_role.role_id")->count();
        if (empty($result)) {
            return Result::error("没有数据",0);
        }
        $data = [
            'rows'=>$result->toArray(),
            'count'=>$count
        ];
        return Result::success($data);
    }


    /**
     * @param array $data
     * @return array
     */
    public function createWebsiteRole(array $data): array
    {

        $insertData = [
            'website_id'=>$data['website_id'],
            'role_id'=>$data['role_id']??''
        ];
        $info = WebsiteRole::where($insertData)->first();
        if($info){
            return Result::error("不能重复添加角色",0);
        }
        $insertData['admin_user_id'] = $data['admin_user_id']??'';
        $insertData['type'] = $data['type']??'';
        $result = WebsiteRole::insertGetId($insertData);
        if(empty($result)){
            return Result::error("创建失败",0);
        }else{
            return Result::success(["id"=>$result]);
        }
    }

    /**
     * 暂时用不上
     * @param int $id
     * @param array $data
     * @return array
     */
    public function updateWebsiteRole(int $id,array $data): array
    {
        $insertData = [
            'website_id'=>$data['website_id'],
            'type'=>$data['type']??'',
        ];
        $result = WebsiteRole::where('id',$id)->update($insertData);
        if(empty($result)){
            return Result::error("更新失败",0);
        }else{
            return Result::success();
        }
    }

    /**
     * @param int $id
     * @return array
     */
    public function delWebsiteRole(int $id): array
    {
        $result = WebsiteRole::where('id',$id )->delete();
        if(empty($result)){
            return Result::error("删除失败",0);
        }else{
            return Result::success();
        }
    }


    /**
     * @param string $keyword
     * @param int $page
     * @param int $pageSize
     * @return array
     */
    public function getWebsiteRoleUserList(string $keyword,int $page,int $pageSize,int $websiteId,int $roleId):array
    {
        $where = [
            ['website_role_user.website_id','=',$websiteId],
            ['website_role_user.role_id','=',$roleId],
        ];
        $count = WebsiteRoleUser::where($where)->count();
       $where[] =   ['u.user_name','like','%'.$keyword.'%'];
        $result = WebsiteRoleUser::where($where)
            ->leftJoin("user as u","website_role_user.user_id","u.id")
            ->leftJoin("website as w","website_role_user.website_id","u.id")
            ->leftJoin("role as r","website_role_user.role_id","r.id")
            ->select("u.*","u.user_name",'w.website_name','r.role_name','website_role_user.id as website_role_user_id','website_role_user.updated_at as user_update_at')
            ->limit($pageSize)->offset(($page-1)*$pageSize)->get();

        if (empty($result)) {
            return Result::error("没有数据",0);
        }
        $data = [
            'rows'=>$result->toArray(),
            'count'=>$count
        ];
        return Result::success($data);
    }

    /**
     * @param array $data
     * @return array
     */
    public function createWebsiteRoleUser(array $data): array
    {
        $insertData = [
            'website_id'=>$data['website_id'],
            'user_id'=>$data['user_id']??'',
        ];
        $info = WebsiteRoleUser::where($insertData)->first();
        if($info){
            return Result::error("不能重复添加角色用户",0);
        }
        $insertData['role_id'] = $data['role_id']??'';
        $insertData['admin_user_id'] = $data['admin_user_id']??'';
        $insertData['type'] = $data['type']??'';
        $result = WebsiteRoleUser::insertGetId($insertData);
        if(empty($result)){
            return Result::error("创建失败",0);
        }else{
            return Result::success(["id"=>$result]);
        }
    }

    /**
     * @param int $id
     * @param array $data
     * @return array
     */
    public function updateWebsiteRoleUser(int $id,array $data): array
    {
        $insertData = [
            'website_id'=>$data['website_id'],
            'type'=>$data['type']??'',
            'type_id'=>$data['type_id']??'',
            'role_id'=>$data['role_id']??'',
        ];
        $result = WebsiteRoleUser::where('id',$id)->update($insertData);
        if(empty($result)){
            return Result::error("更新失败",0);
        }else{
            return Result::success();
        }
    }

    /**
     * @param int $id
     * @return array
     */
    public function delWebsiteRoleUser(int $id): array
    {
        $result = WebsiteRoleUser::where('id',$id )->delete();
        if(empty($result)){
            return Result::error("删除失败",0);
        }else{
            return Result::success();
        }
    }

    /**
     * 根据域名获取网站 站点id
     * @param array $data
     * @return array
     */
    public function getWebsiteId(array $data): array
    {
        $where = [
            'website_url'=>$data['website_url']
        ];
        $result = Website::where($where)->first();
        if(empty($result)){
            return Result::error("查询站点失败",0);
        }else{
            return Result::success($result);
        }
    }

    /**
     * 查询网站下面的导航
     * @param array $data
     * @return array
     */
    public function getWebsiteCategory(array $data): array
    {
       
        $where = [
            'website_id'=>$data['website_id'],
            'pid'=>0
        ];
        $result = WebsiteCategory::where($where)->limit($data['pageSize'])->orderBy('sort','asc')->get();
        if(empty($result)){
            return Result::error("查询站点栏目失败",0);
        }else{
            return Result::success($result);
        }
    }
     /**
     * 查询网站的广告
     * @param array $data
     * @return array
     */
    public function getWebsiteAdvertisement(array $data): array
    {
        $where = [
            'website_id' => $data['website_id'],
            'id' => $data['ad_placeid']
        ];
        $ad_place = AdPlace::where($where)->orderBy('id','asc')->limit(1)->get();
        
            
        $today = Carbon::now();
       
        if(empty($ad_place)){
            return Result::error("error",0);
        }else{
            foreach($ad_place as $val){
                $adplaceid = $val;
            }
            $ad=Ad::where('pid',$adplaceid['id'])->where('status',1)->orderBy('id','asc')->get();
            if(empty($ad)){
                $result=$adplaceid;
                return Result::success($result); 
            }else{                   
                foreach($ad as $i)
                {
                    $starttime=Carbon::parse($i['fromtime']);
                    $endtime=Carbon::parse($i['totime']);
                    $time=$today->between($starttime,$endtime);
                    if($time)
                    {
                        $result=$i;
                    }
                }
                if(empty($result)){
                    $result=$ad;
                    return Result::success($result); 
                }else{
                    return Result::success($result); 
                }
            }
                
        } 
    }
     /**
     * 
     * @param array $data
     * @return array
     */
    /**网站行政职能搜索 */
    public function selectWebsiteDepartment(array $data): array
    {

        $depart = Department::where('pid',0)->orderBy('id','asc')->limit(10)->get();
        if(isset($data['keyword']) && !empty($data['keyword'])){
            $departments= Department::where('name', 'like', '%' . $data['keyword'] . '%')->get();
            if(empty($departments)){
                $result['message']="未查询到与此相关职能部门";
            }else{
                $count = Department::where('name','like',"%{$data['keyword']}%")->count();
                $m = [
                    'department'=>$depart,
                    'type'=>$departments,
                    'count'=>$count
                ]; 
            }
            
            $result['sele'] = $m;
            return Result::success($result['sele']); 
            
        }
        $result=$depart;
        return Result::success($result['data']); 
    }
    /**
     * 
     * @param array $data
     * @return array
     */
    /**
     * 搜索地区
     */
    public function selectWebsiteArea(array $data): array
    {
       
        $provinces=District::where('pid',0)->where('status',1)->get();
       
        if(isset($data['province'])){
            $province=District::where('pid',0)->where('status',1)->where('id',$data['province'])->orderBy('id')->get();
            $province=$province->toArray();
            if(!empty($province)){
                $citys=District::where('pid',$data['province'])->where('status',1)->orderBy('id')->get();
                if(!empty($citys) && isset($data['city']) && !empty($data['city'])){
                    // $province = $province->toArray();
                    $province_id=[];
                    foreach($province as $val){
                        array_push($province_id,$val['id']);
                    }
                    // var_dump($province_id);
                    $city=District::whereIn('pid',$province_id)->where('status',1)->where('id',$data['city'])->orderBy('id')->get();
                    if(!empty($city)){
                        $city_id=[];
                        foreach($city as $val){
                            array_push($city_id,$val['id']);
                        }
                        $regions=District::whereIn('pid',$city_id)->where('status',1)->orderBy('id')->get();
                       
                            $result=[
                                'province' => $province,
                                'city' => $city,
                                'region' => $regions
                            ];
                    }else{
                        return Result::error("未查询到此城市",0); 
                    }
                }else{
                    $result=[
                        'province' => $province,
                        'city' => $citys,
                        'region' => null
                    ];
                }
            }else{
                return Result::error("未查询到此省份",0);
            }
        }else{
            // $keys = array('data');
           $result =  $provinces;
        }
        return Result::success($result);  
    }
    /**
     * @param array $data
     * @return array
     */
    //获取栏目
    public function getWebsiteModelCategory(array $data): array
    {
        $website_id=[
            'website_id' => $data['website_id']
        ];
        $placeid=$data['placeid']-1;
        $pid=[
            'pid' => $data['pid'],
        ];
        $num = $data['num'];
        
        $result=WebsiteCategory::where($website_id)->where($pid)->orderBy('sort')->offset($placeid)->limit($num)->get();
        $result = $result->toArray();
        if(!empty($result)){
            return Result::success($result); 
        }else{
            return Result::error("本网站暂无栏目",0);
        }

    }
    /**
     * @param array $data
     * @return array
     */
    //获取友情链接
    public function selectWebsiteLinks(array $data): array
    {
        $where = [
            'website_id' => $data['website_id'],
            'status' => 1,
            'type' => $data['type']
        ];
        $num=$data['num'];
        $result=Link::where($where)->orderBy('id')->limit($num)->get();
        if(!empty($result)){
            return Result::success($result); 
        }else{
            return Result::error("本网站暂无此类型友情链接",0);
        }

    }


    /**
     * 网站首页数据统计， 管理员
     * @return void
     */
    public function getAdminIndex(array $data): array
    {
         return [];
    }

    /**
     * 获取模板类型
     * @return void
     */
    public function getTemplateClass(array $data): array
    {
        $result = TemplateClass::orderBy('sort','asc')->get();
        if(empty($result)){
            return Result::error("没有模板类型",0);
        }else{
            return Result::success($result);
        }
    }

    /**
     * 添加模板类型
     * @param
     * @return void
     */
    public function addTemplateClass(array $data): array
    {
        $insertData = [
            'name'=>$data['name']
        ];
        $result = TemplateClass::insertGetId($insertData);
        if(empty($result)){
            return Result::error("创建失败",0);
        }else{
            return Result::success(["id"=>$result]);
        }
    }

    /**
     * 更新模板
     * @param array $data
     * @return array
     */
    public function upTemplateClass(array $data): array
    {
        $where = [
            'id'=>$data['id']
        ];
        $insertData = [
            'name'=>$data['name']
        ];
        $result = TemplateClass::where($where)->update($insertData);
        if(empty($result)){
            return Result::error("更新失败",0);
        }else{
            return Result::success();
        }
    }

    /**
     * 删除模板
     * @param array $data
     * @return array
     */
    public function delTemplateClass(array $data): array
    {
        $where = [
            'id'=>$data['id']
        ];

        $result = TemplateClass::where($where)->delete();
        if(empty($result)){
            return Result::error("删除失败",0);
        }else{
            return Result::success();
        }
    }

    /**
     * 获取分类下的模板
     * @param array $data
     * @return array
     */
    public function getTemplate(array $data): array
    {
        $page = $data['page'];
        $pageSize = $data['pageSize'];
        $where = [
           'template_class_id'=> $data['template_class_id']
        ];
        $result = Template::where($where)
            ->limit($pageSize)->offset(($page-1)*$pageSize)->get();
        $count = Template::where($where)->count();
        if (empty($result)) {
            return Result::error("没有数据",0);
        }
        $data = [
            'rows'=>$result->toArray(),
            'count'=>$count
        ];
        return Result::success($data);
    }

    /**
     * 创建模板
     * @param
     * @return void
     */
    public function addTemplate(array $data): array
    {
        $insertData = [
            'template_name'=>$data['template_name'],
            'template_img'=>json_encode($data['template_img']),
            'template_class_id'=>$data['template_class_id'],
        ];
        $result = Template::insertGetId($insertData);
        if(empty($result)){
            return Result::error("创建模板失败",0);
        }else{
            return Result::success(["id"=>$result]);
        }
    }

    /**
     * 更新模板
     * @param array $data
     * @return array
     */
    public function upTemplate(array $data): array
    {
        $where = [
            'id'=>$data['id']
        ];
        $insertData = [
            'template_name'=>$data['template_name'],
            'template_img'=>json_encode($data['template_img']),
            'template_class_id'=>$data['template_class_id'],
        ];
        $result = Template::where($where)->update($insertData);
        if(empty($result)){
            return Result::error("更新模板失败",0);
        }else{
            return Result::success();
        }
    }

    /**
     * 删除模板
     * @param array $data
     * @return array
     */
    public function delTemplate(array $data): array
    {
        $where = [
            'id'=>$data['id']
        ];
        $result = Template::where($where)->delete();
        if(empty($result)){
            return Result::error("删除模板失败",0);
        }else{
            return Result::success();
        }
    }

}