<?php
/**
 *  ╔═══════════════════════════════════════════════════╗
 *  ║                                                   ║
 *  ║     ██╗  ██╗   █████╗    ██████╗                  ║
 *  ║     ██║  ██║  ██╔══██╗  ██╔═══██╗                 ║
 *  ║     ███████║  ███████║  ██║   ██║                 ║
 *  ║     ██╔══██║  ██╔══██║  ██║   ██║                 ║
 *  ║     ██║  ██║  ██║  ██║  ╚██████╔╝   SNS           ║
 *  ║                                                   ║    
 *  ║                                                   ║    
 *  ║     © 2023 HaoSNS™ All Rights Reserved            ║
 *  ║     官方网站: https://www.haosns.com                *
 *  ║     本代码由赣州乐易网络科技有限公司®提供             *
 *  ║                                                    *
 *  ║   未经授权禁止复制、传播或用于其他商业目的            *
 *  ║                                                   ║
 *  ╚═══════════════════════════════════════════════════╝
 */


namespace app\api\lists;

use app\common\enum\PayEnum;
use app\common\model\Article;
use app\common\model\ArticleOrder;
use app\common\model\UserCollect;
use app\common\model\UserFollow;
use app\common\service\ConfigService;
use app\api\logic\ArticleLogic;
use app\common\enum\ArticleEnum;
use app\common\service\FileService;

class ArticleVideoLists extends BaseShopDataLists 
{

    protected $video;
    /**
     * @notes 设置搜索
     */
    public function setSearch()
    {
        $this->searchWhere[] = [
            'status' ,'=' , ArticleEnum::STATUS_SUCCESS
        ];

        $this->searchWhere[] = [
            'type' ,'=' , ArticleEnum::TYPE_VIDEO
        ];


        if (isset($this->params['video_id'])  && $this->params['video_id'] ) {
            
            if( $this->pageNo == 1 ){
                $this->video = Article::alias('a')->with(['user' => function($query){
                    $query->with('user_level');
                }])->where([
                    'id'     => $this->params['video_id'] , 
                    'status' => ArticleEnum::STATUS_SUCCESS , 
                    'type'   => ArticleEnum::TYPE_VIDEO
                ])->append(['comment_num' ,'collect_num' ,'zan_num'])
                ->field('a.*')
                ->select()->toArray();
            }        
            // dd($this->video);die;
            $this->searchWhere[] = [
                'id' ,'<>' , $this->params['video_id']
            ];
            
        }
    }

    /**
     * 设置排序
     */
    public function setOrder()
    {

        $article_index_sort = ConfigService::get('article', 'article_index_sort',1);

        // 设置默认排序方式， 按时间 还是 按照热度
        if( $article_index_sort == 1){
            $this->orderBy = 'a.create_time desc , a.sort desc'  ;
        } else {
            $this->orderBy = 'a.visit desc , a.sort desc'  ;
        }
        

        if (isset($this->params['type'])  && $this->params['type'] =='is_news' ) {
            $this->orderBy ='a.create_time desc , a.sort desc';
        }
        
        return $this->orderBy;
    }


    /**
     * @notes 文章视频列表
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function lists(): array
    {
        
        $this->setSearch();

        $lists = Article::alias('a')->with(['user' => function($query){
            $query->with('user_level');
        }])
            ->limit($this->limitOffset, $this->limitLength)
            ->where($this->searchWhere)
            ->append(['comment_num' ,'collect_num' ,'zan_num'])
            ->field('a.*')
            ->order($this->setOrder());
        
        $lists = $lists->select()->toArray();

        if( $this->pageNo == 1 ){
            $lists = array_merge($this->video,$lists);
        }  
        foreach($lists as  &$item){
            $item['video_cover'] = $item['video_cover'] ? FileService::getFileUrl($item['video_cover']) : '';
            $item['video']       = $item['video'] ? FileService::getFileUrl($item['video']) : '';
            $item['create_time'] = formatTime($item['create_time']);

            if($this->userId) {
                
                //是否点赞过
                $isAan = UserCollect::where([ 'type' => 2, 'aid' => $item['id'], 'user_id' => $this->userId])->value('id');
                $item['is_zan'] = $isAan ? 1 : 0;
                
                //是否收藏过
                $isCollect = UserCollect::where([ 'type' => 1, 'aid' => $item['id'], 'user_id' => $this->userId])->value('id');
                $item['is_collect'] = $isCollect ? 1 : 0;

                //是否关注过改帖子用户
                $isFollow = UserFollow::where([ 'follow_user_id' => $item['user_id'], 'user_id' => $this->userId])->value('id');
                $item['is_follow'] = $isFollow ? 1 : 0;

                $item['btn']['follow_btn'] = $this->userId ==$item['user_id'] ? 0 :1;
                // 判断帖子发帖人时，可管理帖子
                $item['btn']['manage'] = $this->userId ==$item['user_id'] ? 1 :0;


                // 判断是否付费内容
                if( $item['pay_money'] > 0 ){
                    // 判断该用户是否已经付费 
                    $order = ArticleOrder::where([ 'pay_status' => PayEnum::ISPAID, 'article_id' => $item['id'], 'user_id' => $this->userId])->count();
                    if( !$order){
                        // 截取部分内容
                        $item['content']= ArticleLogic::cuttingPayContent($item['content']);
                        $item['title'] = $item['content'];
                        $item['image'] = [];
                        $item['video'] = '';
                        $item['is_pay'] = 0;
                    } else {
                        $item['is_pay'] = 1;
                    }

                    
                }  

            } else {
                $item['btn']['follow_btn'] = 1;

                // 判断是否付费内容
                if( $item['pay_money'] > 0 ){
                    // 截取部分内容
                    $item['content']= ArticleLogic::cuttingPayContent($item['content']);
                    $item['title'] = $item['content'];
                    $item['image'] = [];
                    $item['video'] = '';
                    $item['is_pay'] = 0;
                }   
            }
        }

        return $lists;
    }

    /**
     * @notes 文章/帮助总记录数
     * @return int
     */
    public function count(): int
    {
        $this->setSearch();
        
        $count = Article::alias('a')->where($this->searchWhere);

        return $count->count();
    }
}