<?php
namespace app\common\controller;
use think\facade\View;
use think\facade\Cache;
use think\facade\Db;
use app\common\variable\MsgCode;
use app\common\model\Article as ArticleModel;
use app\common\model\ArticleCate as ArticleCateModel;
use app\common\model\StatusAlias as StatusAliasModel;
use think\helper\Str;
use helper\Wechat;
/**
 * 
 */
class Article extends Base
{
    public static function getSelect($alias,$length)
    {
        $whereSubSiteSql='';
        $whereSubSite=[];
        if (isset(request()->sub_province)){
            if (config('xy_sub_website.data_is_all'))
                $whereSubSite[]='article.province IS NULL';
            $whereSubSite[]='article.province = '.request()->sub_province;
        }
        if (isset(request()->sub_city)){
            if (config('xy_sub_website.data_is_all'))
                $whereSubSite[]='article.city IS NULL';
            $whereSubSite[]='article.city = '.request()->sub_city;
        }
        if (isset(request()->sub_area)){
            if (config('xy_sub_website.data_is_all'))
                $whereSubSite[]='article.area IS NULL';
            $whereSubSite[]='article.area = '.request()->sub_area;
        }
        if (isset(request()->sub_industry)){
            if (config('xy_sub_website.data_is_all'))
                $whereSubSite[]='article.industry IS NULL';
            $whereSubSite[]='article.industry = '.request()->sub_industry;
        }
        if(!empty($whereSubSite))
            $whereSubSiteSql=implode(' OR ', $whereSubSite);
        $now=time();
        $whreTime='(`article`.`start_time` IS NULL AND `article`.`end_time` IS NULL)  OR (`article`.`start_time` < '.$now.' AND `article`.`end_time` IS NULL)  OR (`article`.`start_time` IS NULL AND `article`.`end_time` > '.$now.')  OR (`article`.`start_time` < '.$now.' AND `article`.`end_time` > '.$now.')';
        if($alias&&$alias=='all'){
            $ArticleModelObj=ArticleModel::alias('article')->where(['article.status'=>1])
                ->whereRaw($whreTime);
            if ($whereSubSiteSql)
                $ArticleModelObj->whereRaw($whereSubSiteSql);
            $ArticleModel=$ArticleModelObj->limit($length)->order('article.sort asc,article.start_time desc,article.id desc')->field('article.id,article.title,article.view,article.thumb,article.source,article.start_time,article.create_time,article.desc,article.status_alias,article.force_alert,article.cla')->withAttr('start_time',function($v,$data){
                    return $v?$v:$data['create_time'];
                })->withAttr('thumb',function($v,$data){
                    return $v?explode(',',$v):[];
                })->withAttr('source',function($v,$data){
                    return $v?$v:config('web.name');
                })->withAttr('status_alias',function($v,$data){
                    return $v?StatusAliasModel::where(['alias'=>'article/status_alias','value'=>$v])->field('type,title')->find():'';
                })->select();
            return $ArticleModel;
        }else{
            $ArticleCateModel=ArticleCateModel::where(['alias'=>$alias])->find();
            if ($ArticleCateModel) {
                $ArticleModelObj=ArticleModel::alias('article')->where(['article.cid'=>$ArticleCateModel->id,'article.status'=>1]);
                if ($whereSubSiteSql)
                    $ArticleModelObj->whereRaw($whereSubSiteSql);
                $ArticleModel=$ArticleModelObj->whereRaw($whreTime)->limit($length)->order('article.start_time desc,article.id desc')->field('article.id,article.title,article.view,article.thumb,article.source,article.start_time,article.create_time,article.desc,article.status_alias,article.force_alert,article.cla')->withAttr('start_time',function($v,$data){
                        return $v?$v:$data['create_time'];
                    })->withAttr('thumb',function($v,$data){
                        return $v?explode(',',$v):[];
                    })->withAttr('source',function($v,$data){
                        return $v?$v:config('web.name');
                    })->withAttr('status_alias',function($v,$data){
                        return $v?StatusAliasModel::where(['alias'=>'article/status_alias','value'=>$v])->field('type,title')->find():'';
                    })->select();
                return $ArticleModel;
            }
        }
        return [];
    }
    public static function getPage($alias,$length)
    {
        $whereSubSiteSql='';
        $whereSubSite=[];
        if (isset(request()->sub_province)){
            if (config('xy_sub_website.data_is_all'))
                $whereSubSite[]='article.province IS NULL';
            $whereSubSite[]='article.province = '.request()->sub_province;
        }
        if (isset(request()->sub_city)){
            if (config('xy_sub_website.data_is_all'))
                $whereSubSite[]='article.city IS NULL';
            $whereSubSite[]='article.city = '.request()->sub_city;
        }
        if (isset(request()->sub_area)){
            if (config('xy_sub_website.data_is_all'))
                $whereSubSite[]='article.area IS NULL';
            $whereSubSite[]='article.area = '.request()->sub_area;
        }
        if (isset(request()->sub_industry)){
            if (config('xy_sub_website.data_is_all'))
                $whereSubSite[]='article.industry IS NULL';
            $whereSubSite[]='article.industry = '.request()->sub_industry;
        }
        if(!empty($whereSubSite))
            $whereSubSiteSql=implode(' OR ', $whereSubSite);
        $G=request()->get();
        $now=time();
        $whreTime='(`article`.`start_time` IS NULL AND `article`.`end_time` IS NULL)  OR (`article`.`start_time` < '.$now.' AND `article`.`end_time` IS NULL)  OR (`article`.`start_time` IS NULL AND `article`.`end_time` > '.$now.')  OR (`article`.`start_time` < '.$now.' AND `article`.`end_time` > '.$now.')';
        $where=[];
        if(!empty($G['key']))
            $where[]=['article.title','like','%'.$G['key'].'%'];
        if($alias&&$alias=='all'){
            $ArticleModelObj=ArticleModel::alias('article')->where(['article.status'=>1])->where($where);
            if ($whereSubSiteSql)
                $ArticleModelObj->whereRaw($whereSubSiteSql);
            $ArticleModel=$ArticleModelObj->whereRaw($whreTime)->order('article.sort asc,article.start_time desc,article.id desc')->field('article.id,article.title,article.view,article.thumb,article.source,article.start_time,article.create_time,article.desc,article.status_alias,article.force_alert,article.cla')->paginate($length)->each(function($item, $key){
                    $item->start_time = $item->start_time?$item->start_time:$item->create_time;
                    $item->source = $item->source?$item->source:config('web.name');
                    $item->imgurl=config('web.imgurl');
                    if ($item->thumb)
                        $item->thumb=explode(',',$item->thumb);
                    if($item->status_alias)
                    $item->status_alias=StatusAliasModel::where(['alias'=>'article/status_alias','value'=>$item->status_alias])->field('type,title')->find();
                });
            return $ArticleModel;
        }else{
            $ArticleCateModel=ArticleCateModel::where(['alias'=>$alias])->find();
            if ($ArticleCateModel) {
                $ArticleModelObj=ArticleModel::alias('article')->where(['article.cid'=>$ArticleCateModel->id,'article.status'=>1])->where($where);
                if ($whereSubSiteSql)
                    $ArticleModelObj->whereRaw($whereSubSiteSql);
                $ArticleModel=$ArticleModelObj->whereRaw($whreTime)->order('article.start_time desc,article.id desc')->field('article.id,article.title,article.view,article.thumb,article.source,article.start_time,article.create_time,article.desc,article.status_alias,article.force_alert,article.cla')->paginate($length)->each(function($item, $key){
                        $item->start_time = $item->start_time?$item->start_time:$item->create_time;
                        $item->source = $item->source?$item->source:config('web.name');
                        $item->imgurl=config('web.imgurl');
                        if ($item->thumb)
                            $item->thumb=explode(',',$item->thumb);
                        if($item->status_alias)
                        $item->status_alias=StatusAliasModel::where(['alias'=>'article/status_alias','value'=>$item->status_alias])->field('type,title')->find();
                    });
                return $ArticleModel;
            }
        }
        return [];
    }
    public static function getIdContent($id)
    {
        $Find=Cache::get('article.id_'.$id);
        if (!$Find || Cache::pull('article_update_cache.id_'.$id)) {
            $now=time();
            $whreTime='(`article`.`start_time` IS NULL AND `article`.`end_time` IS NULL)  OR (`article`.`start_time` < '.$now.' AND `article`.`end_time` IS NULL)  OR (`article`.`start_time` IS NULL AND `article`.`end_time` > '.$now.')  OR (`article`.`start_time` < '.$now.' AND `article`.`end_time` > '.$now.')';
            $Find=ArticleModel::alias('article')->where(['article.id'=>$id,'article.status'=>1])
                    ->join('article_content content','content.tid=article.id')
                    ->whereRaw($whreTime)->field('article.id,article.create_time,article.start_time,article.end_time,article.title,article.view,article.alias,article.source,article.desc,content.content,article.status_alias,article.qrcode,article.thumb,article.cla')
                    ->withAttr('qrcode',function($v,$data){
                        return $v?config('web.imgurl').$v:'';
                    })
                    ->withAttr('start_time',function($v,$data){
                        return $v?$v:$data['create_time'];
                    })
                    ->withAttr('source',function($v,$data){
                        return $v?$v:config('web.name');
                    })
                    ->withAttr('thumb',function($v,$data){
                        return $v?explode(',',$v):[];
                    })->find();
            if ($Find) {
                if($Find->status_alias)
                $Find->status_alias=StatusAliasModel::where(['alias'=>'article/status_alias','value'=>$Find->status_alias])->field('type,title')->find();
                $Find->cate=ArticleModel::alias('article')->where(['article.id'=>$Find->id])
                    ->join('article_cate cate','cate.id=article.cid')->order('cate.sort asc')->field('article.id,article.cid,cate.title,cate.alias')->find();
                if ($Find->cate) {
                    $Find->prev=ArticleModel::alias('article')->where(['cid'=>$Find->cate->cid])
                        ->where('article.id','<',$Find->cate->id)
                        ->order('article.id desc')->field('article.id,article.title')->find();
                    $Find->next=ArticleModel::alias('article')->where(['cid'=>$Find->cate->cid])
                        ->where('article.id','>',$Find->cate->id)
                        ->order('article.id asc')->field('article.id,article.title')->find();
                    if ($Find->prev || $Find->next)
                        $Find->extension=1;
                }
                $end_time=0;
                if ($Find->end_time) {
                    $end_time=$Find->end_time-time();
                }
                $Find->end_time=$end_time;
                if ($end_time>=0) {
                    if ($Find->alias) {
                        Cache::set('article.'.$Find->alias,$Find->toArray(),$end_time);
                    }
                    Cache::set('article.id_'.$Find->id,$Find->toArray(),$end_time);
                }
                $Find=$Find->toArray();
            }else{
                $Find=[];
                Cache::delete('article.id_'.$id);
            }
        }
        if ($Find) {
            $view_rand=intval(config('basic.view_rand'));
            $view=1;
            if ($view_rand)
            $view=rand(1,$view_rand);
            ArticleModel::where(['id'=>$Find['id']])->inc('view',$view)->update();
            $Find['view']=$Find['view']+$view;
            if ($Find['end_time']>=0) {
                if ($Find['alias']) {
                    Cache::set('article.'.$Find['alias'],$Find,$Find['end_time']);
                }
                Cache::set('article.id_'.$Find['id'],$Find,$Find['end_time']);
            }
            $Find['web_logo']=config('web.imgurl').config('web.logo');
            $Find['shareData']=[
                'type'  =>1,
                'id'    =>$Find['id'],
                'title' =>$Find['title'],
                'desc'  =>$Find['desc'],
                'url'   =>config('web.h5').'/#/pageA/pages/common/article/content?id='.$Find['id']
            ];
            if (request()->AppInfo['app_modul']=='mobile'&&request()->is_wx) {
                try {
                    $tinket=Wechat::getTicket();
                    if ($tinket) {
                        $wxShareData=[
                            'noncestr'=>Str::random(16),
                            'jsapi_ticket'=>$tinket,
                            'timestamp'=>time(),
                            'url'=>config('web.h5').'/#/pageA/pages/common/article/content?id='.$Find['id']
                        ];
                        ksort($wxShareData);
                        $wxShareData['signature']=sha1(urldecode(http_build_query($wxShareData)));
                        $wxShareData['appid']=config('xy_wechat_mp.appid').'';
                        unset($wxShareData['jsapi_ticket']);
                        $Find['wxShareData']=$wxShareData;
                    }
                } catch (\think\Exception $e) {
                    
                }
            }
        }
        return $Find;
    }
    public static function getAliasContent($alias)
    {
        $Find=Cache::get('article.alias_'.$alias);
        if (!$Find || Cache::pull('article_update_cache.alias_'.$alias)) {
            $now=time();
            $whreTime='(`article`.`start_time` IS NULL AND `article`.`end_time` IS NULL)  OR (`article`.`start_time` < '.$now.' AND `article`.`end_time` IS NULL)  OR (`article`.`start_time` IS NULL AND `article`.`end_time` > '.$now.')  OR (`article`.`start_time` < '.$now.' AND `article`.`end_time` > '.$now.')';
            $Find=ArticleModel::alias('article')->where(['article.alias'=>$alias,'article.status'=>1])
                    ->join('article_content content','content.tid=article.id')
                    ->whereRaw($whreTime)->field('article.id,article.create_time,article.start_time,article.end_time,article.title,article.view,article.alias,article.source,article.desc,content.content,article.status_alias,article.qrcode,article.thumb,article.cla')
                    ->withAttr('qrcode',function($v,$data){
                        return $v?config('web.imgurl').$v:'';
                    })
                    ->withAttr('start_time',function($v,$data){
                        return $v?$v:$data['create_time'];
                    })
                    ->withAttr('source',function($v,$data){
                        return $v?$v:config('web.name');
                    })
                    ->withAttr('thumb',function($v,$data){
                        return $v?explode(',',$v):[];
                    })->find();
            if ($Find) {
                if($Find->status_alias)
                $Find->status_alias=StatusAliasModel::where(['alias'=>'article/status_alias','value'=>$Find->status_alias])->field('type,title')->find();
                $Find->cate=ArticleModel::alias('article')->where(['article.id'=>$Find->id])
                    ->join('article_cate cate','cate.id=article.cid')->order('cate.sort asc')->field('article.id,article.cid,cate.title,cate.alias')->find();
                if ($Find->cate) {
                    $Find->prev=ArticleModel::alias('article')->where(['cid'=>$Find->cate->cid])
                        ->where('article.id','<',$Find->cate->id)
                        ->order('article.id desc')->field('article.id,article.title')->find();
                    $Find->next=ArticleModel::alias('article')->where(['cid'=>$Find->cate->cid])
                        ->where('article.id','>',$Find->cate->id)
                        ->order('article.id asc')->field('article.id,article.title')->find();
                    if ($Find->prev || $Find->next)
                        $Find->extension=1;
                }
                $end_time=0;
                if ($Find->end_time) {
                    $end_time=$Find->end_time-time();
                }
                $Find->end_time=$end_time;
                if ($end_time>=0) {
                    if ($Find->alias) {
                        Cache::set('article.'.$Find->alias,$Find->toArray(),$end_time);
                    }
                    Cache::set('article.id_'.$Find->id,$Find->toArray(),$end_time);
                }
                $Find=$Find->toArray();
            }else{
                $Find=[];
                Cache::delete('article.'.$alias);
            }
        }
        if ($Find) {
            $view_rand=intval(config('basic.view_rand'));
            $view=1;
            if ($view_rand)
            $view=rand(1,$view_rand);
            ArticleModel::where(['id'=>$Find['id']])->inc('view',$view)->update();
            $Find['view']=$Find['view']+$view;
            if ($Find['end_time']>=0) {
                if ($Find['alias']) {
                    Cache::set('article.'.$Find['alias'],$Find,$Find['end_time']);
                }
                Cache::set('article.id_'.$Find['id'],$Find,$Find['end_time']);
            }
            $Find['web_logo']=config('web.imgurl').config('web.logo');
            $Find['shareData']=[
                'type'  =>1,
                'id'    =>$Find['id'],
                'title' =>$Find['title'],
                'desc'  =>$Find['desc'],
                'url'   =>config('web.h5').'/#/pageA/pages/common/article/content?id='.$Find['id']
            ];
            if (request()->AppInfo['app_modul']=='mobile'&&request()->is_wx) {
                try {
                    $tinket=Wechat::getTicket();
                    if ($tinket) {
                        $wxShareData=[
                            'noncestr'=>Str::random(16),
                            'jsapi_ticket'=>$tinket,
                            'timestamp'=>time(),
                            'url'=>config('web.h5').'/#/pageA/pages/common/article/content?alias='.$alias
                        ];
                        ksort($wxShareData);
                        $wxShareData['signature']=sha1(urldecode(http_build_query($wxShareData)));
                        $wxShareData['appid']=config('xy_wechat_mp.appid').'';
                        unset($wxShareData['jsapi_ticket']);
                        $Find['wxShareData']=$wxShareData;
                    }
                } catch (\think\Exception $e) {
                    
                }
            }
        }
        return $Find;
    }
}