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


namespace app\api\controller;

use app\api\lists\ArticleCommentsLists;
use app\api\lists\ArticleDraftLists;
use app\api\lists\ArticleVideoLists;
use app\api\logic\ArticleLogic;
use app\api\logic\UserLogic;
use app\common\model\ArticleDun;

class Article extends BaseShopController
{
    /**
     * 无需登录即可访问的方法
     * @var array|string[]
     */
    public array $notNeedLogin = ['lists', 'video_lists',  'detail','comments_lists','related'];

    /**
     * 相关推荐
     * 根据标签
     * 圈子
     * 标题关键字推荐相关内容
     */
    public function related($id)
    {

        $article_info = \app\common\model\Article::find($id)->toArray();
        $where = [];
        if($article_info['circle_id'] && $article_info['circle_id']>0){
            $where[] = ['circle_id','=',$article_info['circle_id']];
        }

        $list = \app\common\model\Article::where($where)
        ->order('create_time','desc')
        ->paginate(10);

        return show(config('status.success'),'ok',$list);

    }

    /**
     * 猜你喜欢
     */
    public function like()
    {
        echo 1;die;
    }

    /**
     * @notes 帖子列表
     * @return \think\response\Json
     */
    public function lists()
    {
        try{
            return $this->dataLists();
        }catch(\Exception $e){
            return show(config('status.error'),$e->getMessage());
        }
    }

    /**
     * @notes 帖子视频列表
     * @return \think\response\Json
     */
    public function video_lists()
    {
        return $this->dataLists( new ArticleVideoLists());
    }
    

    /**
     * @notes 获取详情
     * @return \think\response\Json
     */
    public function detail()
    {    

        try{
            $params = $this->request->get();
            // 记录分享日志
            if(isset($params['from_user_id']) && !empty($params['user_id'])){
                $share_log = \app\common\model\ArticleShareLog::where([
                    'user_id'=>$params['user_id'],
                    'article_id'=>$params['id'],
                ])->find();
                if($share_log){
                    $data=[
                        'user_id'=>empty($this->userId)?0:$this->userId,
                        'from_user_id'=>$params['user_id'],
                        'article_id'=>$params['article_id'],
                        'ip'=>$this->request->ip(),
                    ];
                    \app\common\model\ArticleShareLog::create($data);
                }
            }

            // 圈子访问权限判断
            $article = \app\common\model\Article::field('id,title,ip_address,circle_id,user_id,status')
            ->with(['user','circle'])->find($params['id']);

            if(!$article){
                return show(404,'找不到文章'); 
            }

            if ($article->status == 2) {
                return show(config('status.error'),'帖子违规无法访问');
            }

            if($article->is_open===0){
                if(!$this->userId){
                    return show(403,'此文章仅作者可见'); 
                }
                if($article->user_id!=$this->userId){
                    return show(403,'此文章仅作者可见'); 
                }
            }
            
            // dd($article->toArray());
            if(isset($article->circle_id) && $article->circle_id > 0){
                
                // dd($article->circle_id);
                $circle = \app\common\model\Circle::find($article->circle_id);
                // dd($circle->visit_level);
                if($circle){
                    if($circle->visit_level>0 && !$this->userId){
                        return show(config('status.error'),'请登录后阅读');
                    }
                    if($this->userId){
                        $user = \app\common\model\User::find($this->userId);
                        if($user->level < $circle->visit_level){
                            return show(403,'没有权限访问此圈子下的文章');
                        };
                    }
                }
            };
            
            $result = ArticleLogic::detail($params,$this->userId);
        }catch(\Exception $e){
            return show(config('status.error'),$e->getMessage());
        }
        if ($this->userId) {
            $result['dun'] = !!ArticleDun::where('user_id', $this->userId)->where('article_id', $params['id'])->find();
        } else {
            $result['dun'] = false;
        }
        return $this->data($result);
    }

    /**
     * @notes 发送验证码 - 绑定手机号
     */
    public function bindInfoCaptcha()
    {
        // dd(\app\common\enum\NoticeEnum::BIND_INFO_CAPTCHA);
        $params = $this->request->post();
        $code = mt_rand(1000, 9999);
        $result = event('Notice', [
            // 'scene_id' => 301,
            'scene_id'=> \app\common\enum\NoticeEnum::BIND_INFO_CAPTCHA,
            'params' => [
                'user_id'=>$this->userId,
                'mobile' => $params['mobile'],
                'code' => $code,
            ]
        ]);
        if ($result[0] === true) {
            return $this->success('发送成功');
        }

        return $this->fail($result[0], [], 0, 1);
    }

    /**
     * 附近帖子
     */
    public function near()
    {
        $ip = $_SERVER['REMOTE_ADDR'];
        $ip_address = '';
        try {
            // 初始化，指定QQWry.dat文件路径
            $qqwry = new \app\common\service\QQWry('qqwry.dat');
            // 获取客户端IP
            $ip = $_SERVER['REMOTE_ADDR'];
            // 查询IP地理位置
            $location = $qqwry->getLocation($ip);
            $ip_address = $location['country'];
            
        } catch (\Exception $e) {
            // echo "发生错误: " . $e->getMessage();
            return show(0,'没有数据');
        }

        // dd($location);
        $list = \app\common\model\Article::where('ip_address','like','%'.$location['country'].'%')
        ->where('status',1)
        ->order('create_time','desc')
        ->paginate(10);
        
        return show(config('status.success'),'',$list);

    }

    /**
     * @notes 添加帖子
     * @return \think\response\Json
     */
    public function add()
    {
   
        $params =  $this->request->post();

        checkDangerTxt($params['title']);
        checkDangerTxt($params['content']['text']);
        
        // 全局发帖次数限制
        $send_limit_day = \app\common\service\ConfigService::get('article','send_limit_day',10);
        $send_count = \app\common\model\Article::where([
            ['user_id','=',$this->userId],
            ['create_time','>',time() - 60*60*24]
        ])->count();
        if($send_count > $send_limit_day){
            return show(config('status.error'),'您发布次数过多，明天再试');
        }

        if(\app\common\service\ConfigService::get('article', 'send_require_circle',0) == 1 && (!isset($params['circle_id']) || empty($params['circle_id']))){
            return show(config('status.error'),'请选择圈子分类');
        }

        if(empty($params['title']) && empty($params['content']['text'])){
            return show(config('status.error'),'标题或内容至少要填一个');
        }

        if(isset($params['circle_id'])){

            $circle = \app\common\model\Circle::find($params['circle_id']);
            if($circle->only_circle_send == 1){
                if($circle->user_id != $this->userId){
                    return show(config('status.error'),'此圈子只有圈主能发布');
                }
            }

            // 验证手机号
            if($circle->info_mobile_check_status==1 && isset($params['contact_phone']) && !empty($params['contact_phone'])){
                // 如果手机号和本地绑定的一致则无需验证
                $user = \app\common\model\User::find($this->userId);
                if($params['contact_phone'] != $user->mobile){
                    $smsDriver = new \app\common\service\sms\SmsDriver();
                    $result = $smsDriver->verify($params['contact_phone'], $params['code']);
                    if (!$result) {
                        return show(config('status.error'),'验证码错误');
                    }
                }
            }
            
            // 圈子权限判断
            $user = \app\common\model\User::find($this->userId);
            if($circle->send_level>0){
                // 限制发帖等级
                if($user->level<$circle->send_level){
                    return show(config('status.error'),'此圈子需要'.$circle->send_level.'级才能发布');
                }
            }

            // 禁止上传图片
            if($circle->disbale_upload_image==1){
                if(isset($params['image']) && !empty($params['image'])){
                    return show(config('status.error'),'本圈子设置了禁止上传图片');
                };
            }

            // 禁止上传附件
            if($circle->diable_upload_file==1){
                if(isset($params['file']) && !empty($params['file'])){
                    return show(config('status.error'),'本圈子设置了禁止上传附件');
                };
            }
        }
        
        try{
            $res = ArticleLogic::add($params,$this->userId);
        }catch(\Exception $e){
            return show(config('status.error'),$e->getMessage());
        }

        // 异步非阻塞start
        // 1. 先发送响应给客户端
        header('Content-Type: application/json');
        echo json_encode(['code' => 1, 'msg' => '添加成功','data'=>['id'=>$res->id]]);
        // 2. 结束客户端连接
        if (function_exists('fastcgi_finish_request')) {
            fastcgi_finish_request();
        } else {
            // 其他环境的替代方案
            ob_end_flush();
            flush();
        }
        // 异步非阻塞end

        
        // 发帖成功奖励积分
        $send_get_integral = \app\common\service\ConfigService::get('article','send_get_integral',0);
        if($res && $send_get_integral>0){
            \think\facade\Db::startTrans();
            try{
                // 增加用户积分
                $user = \app\common\model\User::findOrEmpty($this->userId);
                // $user->user_money = $user->user_money + $money + $continuousMoney;
                $user->user_integral = $user->user_integral + $send_get_integral;
                $user->save();
                // 记录积分流水
                $remark = '发帖成功奖励积分：'.$send_get_integral;
                \app\common\logic\AccountLogLogic::add($this->userId, \app\common\enum\AccountLogEnum::BW_INC_SIGN, \app\common\enum\AccountLogEnum::INC, $send_get_integral, '', $remark);
                \think\facade\Db::commit();
            }catch(\Exception $e){
                \think\facade\Db::rollback();
            }
        }

 
        if(isset($params['circle_id'])){
            // 发帖成功奖励圈子经验
            $send_get_experience = \app\common\service\ConfigService::get('article', 'send_get_experience',0);
            if($res && $send_get_experience>0){

                 // 查询圈子对应经验
                 $circleLevel = \app\common\model\CircleLevel::where([
                    'circle_id'=>$params['circle_id'],
                    'user_id'=>$this->userId,
                ])->find();

                // 只有关注贴吧的可获得增加经验
                if($circleLevel){
                    $circleLevel->experience = $user->experience + $send_get_experience;
                }

                // 执行圈子等级升级检测
                // $user = \app\common\model\User::with(['circleLevel'])->where([])->select();
                
            }
        }

        // 发帖成功奖励全局用户经验
        $send_get_experience_globle = \app\common\service\ConfigService::get('article', 'send_get_experience_globle',0);
        if($res && $send_get_experience_globle>0){

            // 给用户增加经验
            $user = \app\common\model\User::with(['userLevel'])
            ->find($this->userId);
            $user->inc('experience',$send_get_experience_globle);
            $user->save();
            $user = \app\common\model\User::with(['userLevel'])
            ->find($this->userId);

            // 判断当前等级满足升级条件升级
            // 检查升级条件
            $user_level_list = \app\common\model\UserLevel::where('rank','>',$user->userLevel['rank'])
            ->select()->toArray();

            foreach($user_level_list as $v){
                // 判断当前积分是否满足升级
                if($user->experience > $v['experience']){
                    $user->level = $v['id'];
                    $user->save();
                }
            }

        }
        

        if(\app\common\service\ConfigService::get('article', 'send_examine',0) !=1){
            // 不需要审核走机器人插件自动审核
            try{
                if($res){
                    // 机器人自动回复钩子
                    \think\facade\Event::trigger('article.reply', $res);
                    // 机器人自动审核内容钩子
                    \think\facade\Event::trigger('article.audit', $res);
                }
            }catch (\Exception $e){}
        }else{
            // 需要审核
            // 如果开启了腾讯云审核走腾讯云审核

            $data = [
                'id'=>$res->id,
                'text'=>$res->title.$res->content,
                'image'=>$res->image,//[]图片数组预留
            ];

            // dd($data);
            $res = $this->examine_txy($data);
            // dd($res);
        }
        
    }

    
    /**
     * 腾讯云文本审核
     * @return void
     */
    private function examine_txy($params)
    {

        $config = [
            'is_open'   => \app\common\service\ConfigService::get('security', 'is_open', 0),
            'secret_key'   => \app\common\service\ConfigService::get('security', 'qcloud', "")['secret_key'],
            'secret_id'   => \app\common\service\ConfigService::get('security', 'qcloud',  "")['secret_id'],
            'region'   => \app\common\service\ConfigService::get('security', 'qcloud',  "")['region'],
            'bucket'   => \app\common\service\ConfigService::get('security', 'qcloud',  "")['bucket'],
        ];

        if($config['is_open'] != 1){
            return '未开启腾讯云审核审核';
        }

        $cosClient = new \Qcloud\Cos\Client(
            array(
                'region' => $config['region'],
                'schema' => 'https', // 审核时必须为https
                'credentials'=> array(
                    'secretId'  => $config['secret_id'],
                    'secretKey' => $config['secret_key'],
                )));
        
        
        try {
            $result = $cosClient->detectText(array(
                'Bucket' => $config['bucket'], //存储桶名称，由BucketName-Appid 组成，可以在COS控制台查看 https://console.cloud.tencent.com/cos5/bucket
                'Input' => array(
                    'Content' => base64_encode($params['text']), // 文本需base64_encode
        //            'DataId' => '', // 选填 该字段在审核结果中会返回原始内容，长度限制为512字节。您可以使用该字段对待审核的数据进行唯一业务标识。
                ),
        //        'Conf' => array(
        //            'BizType' => '',
        //        ), // 非必选，在BizType不传的情况下，走默认策略及默认审核场景。
            ));
           
            // Result
            $res = [
                'examine_id'=>$result['JobsDetail']['JobId'],//审核任务id
                'examine_result'=>$result['JobsDetail']['Result'], // 0（审核正常），1 （判定为违规敏感文件），2（疑似敏感，建议人工复核）
                'examine_label'=>$result['JobsDetail']['Label'], // Label Normal：正常，Porn：色情，Ads：广告 
            ];
            $res_msg = '';
            // dd($res);
            if($res['examine_result']==0){
                $res['status']=1;
                $res_msg = '您发布的帖子审核通过';
            }else{
                $res['status']=2;
                if($res['examine_label']=='Porn'){
                    $res_msg = '您发布的内容包含色情';
                }elseif($res['examine_label']=='Ads'){
                    $res_msg = '您发布的内容包含广告';
                }else{
                    $res_msg = '您发布的内容包含敏感内容';
                }
            }

            $res['examine_msg']=$res_msg;

            \app\common\model\Article::update($res,['id'=>$params['id']]);

            event('Notice', [
                'scene_id' => \app\common\enum\NoticeEnum::ARTICLE_EXAMINE_NOTICE,
                'params' => [
                    'type'=>'article',
                    'user_id'    => $this->userId,  //帖子对应的发布者ID
                    'article_id' => $params['id'],   //回复的帖子,
                    'content'    => $res_msg,
                ]
            ]);
            
            return $res_msg;
        } catch (\Exception $e) {
            echo '请求失败';
            dd($e->getMessage());
        }
    }

    /**
     * 用户上下架显示帖子内容
     */
    public function show()
    {
        $params = $this->request->post();
        $res = \app\common\model\Article::where([
            'user_id'=>$this->userId,
            'id'=>$params['id']])
        ->update([
            'is_show'=>$params['is_show']==1?1:0
        ]);
        
        if($res){
            return show(config('status.success'),'设置成功');
        }
        return show(config('stauts.error'),'设置失败');
    }

    /**
     * 编辑查询接口
     */
    public function edit($id)
    {
        // 重新编辑修改状态需重新审核
        $data = \app\common\model\Article::with(['vote'])
        ->where([
            ['id','=',$id],
            ['user_id','=',$this->userId]
        ])->find();

        // 帖子字段
        if(isActivePluginByPluginName('field')){
            $data['field'] = \think\facade\Db::table(config('database.connections.mysql.prefix').'article_field')
            ->alias('a')
            ->where('article_id',$data['id'])
            ->join('circle_field c', 'a.field_id = c.id')
            ->field('a.id as article_field_id,a.value as article_value,a.*, c.*')
            ->select()
            ->toArray();
        }

        return show(config('status.success'),'帖子编辑详情',$data);
        
    }

    /**
     * 查询用户我发布的帖子
     */
    public function mylist()
    {
        $params = $this->request->get();
        $where = [ 'status'=>1,'user_id'=>$this->userId,];

        if(isset($params['status'])){
            // 查询待审核和已拒审
            $where['status'] = $params['status'];
        }else{
            $where['is_show']=$params['is_show']==1?1:0;//用户设置的上架显示和下架
        }

        $list = \app\common\model\Article::with(['circle','sub_category'])
        ->append(['comment_num', 'collect_num', 'zan_num'])
        ->where($where)
        ->order('create_time','desc')
        ->paginate(10);
        return show(config('status.success'),'我发布的列表',$list);
    }

    /**
     * 统计
     */
    public function statistics()
    {
        // 总浏览量
        $visit = \app\common\model\Article::where([
            'user_id'=>$this->userId,
        ])
        ->sum('visit');

        $count = \app\common\model\Article::where([
            'user_id'=>$this->userId,
        ])
        ->count();

        $data = [
            'visit'=>$visit,
            'count'=>$count,
        ];
        
        return show(config('status.success'),'统计数据',$data);
    }
    

    /**
     * @notes 修改帖子内容接口
     * @return \think\response\Json
     */
    public function update()
    {

        $is_update = \app\common\service\ConfigService::get("article","is_update");
        if($is_update==0){
            return show(config("status.error"),"管理设置不允许修改");
        }
        $params = $this->request->post();

        if(isset($params['title']) && !empty($params['title'])){
            checkDangerTxt($params['title']);
        }
        if(isset($params['content']['text']) && !empty($params['content']['text'])){
            checkDangerTxt($params['content']['text']);
        }
        
        $res = \app\common\model\Article::where([
            ['user_id','=',$this->userId],
            ['id','=',$params['id']]
        ])->find();

        
        if($res->user_id != $this->userId){
            return show(config('status.error'),'没有修改权限');
        }

        if($res->status == 0){
            return show(config('status.error'),'正在审核中不能修改');
        }

        try{
            
            $res = ArticleLogic::update($params,$this->userId);

            return show(config("status.success"),"修改成功");
        }catch(\Exception $e){
            return show(config('status.error'),$e->getMessage());
        }

    }

    // 修改权限
    public function updateAuth()
    {
        $is_update = \app\common\service\ConfigService::get("article","is_update");
        if($is_update==0){
            return show(config("status.error"),"管理设置不允许修改");
        }
        
        $params = $this->request->post();

        checkDangerTxt($params['title']);
        checkDangerTxt($params['content']);
        
        $res = \app\common\model\Article::where([
            ['user_id','=',$this->userId],
            ['id','=',$params['id']]
        ])->find();

        if($res->user_id != $this->userId){
            return show(config('status.error'),'没有修改权限');
        }

        $update = [];

        if(isset($params['only_look_user_ids'])){
            $update['only_look_user_ids'] = $params['only_look_user_ids'];
        }

        if(isset($params['disable_look_user_ids'])){
            $update['disable_look_user_ids'] = $params['disable_look_user_ids'];
        }

        if(isset($params['only_look_user_level'])){
            $update['only_look_user_level'] = $params['only_look_user_level'];
        }

        if(isset($params['only_look_follow'])){
            $update['only_look_follow'] = $params['only_look_follow'] == 1?:0;
        }

        \app\common\model\Article::where('id',$params['id'])
        ->update($update);

        return show(config('status.success'),'修改成功');

    }


    /**
     * @notes 添加帖子草稿
     * @return \think\response\Json
     */
    public function addDraft()
    {
        $params =  $this->request->post();
        ArticleLogic::addDraft($params,$this->userId);
        return $this->success('添加成功',[],1,1);
    }

    /**
     * @notes 帖子草稿详情
     * @return \think\response\Json
     */
    public function draftDetail()
    {
        $params =  $this->request->get();
        $result = ArticleLogic::draftDetail($params,$this->userId);
        return $this->data($result);
    }

    /*
    * @notes 删除草稿
    * @return \think\response\Json
    */
    public function draft_del()
    {
        $params =  $this->request->post();
        ArticleLogic::delDraft($params,$this->userId);
        return $this->success('删除成功',[],1,1);
    }

    /**
     * @notes 草稿列表
     * @return \think\response\Json
     */
    public function draft_lists()
    {
        return $this->dataLists( new ArticleDraftLists());
    }

    public function dun()
    {
        $params = $this->request->param();

        if (!isset($params['id'])) {
            return show(0,"蹲贴失败");
        }

        $a = \app\common\model\Article::find($params['id']);

        if (!$a) {
            return show(0,"帖子不存在");
        }

        $res = ArticleDun::where('user_id',$this->userId)
            ->where('article_id',$params['id'])
            ->find();

        if (isset($params['del'])) {
            if (!$res) {
                return show(0,'取消失败');
            }

            $res->delete();

            return show(1, '取消成功');
        }

        if ($res) {
            return show(0, '已蹲');
        }

        ArticleDun::create([
            'article_id'=>$params['id'],
            'user_id'=>$this->userId,
        ]);

        return show(1, '蹲贴成功');
    }


    /**
     * @notes 删除帖子
     * @return \think\response\Json
     */
    public function delete()
    {
        $params =  $this->request->post();
        ArticleLogic::delete($params,$this->userId);
        return $this->success('删除成功',[],1,1);
    }


    /**
     * 帖子置顶
     */
    public function handleTop()
    {   
        $params = $this->request->post();
        ArticleLogic::handleTop($params,$this->userId);
        return $this->success();
    }


    /**
     * 帖子 关注 取关
     */
    public function handleCollect()
    {   
        $params = $this->request->post();
        ArticleLogic::handleArticleCollect($params,$this->userId);
        return $this->success();
    }


    /**
     * @notes 帖子 评价列表
     * @return \think\response\Json
     */
    public function comments_lists()
    {
        return $this->dataLists( new ArticleCommentsLists());
    }

    /**
     * @notes 帖子回复评价
     * @return \think\response\Json
     */
    public function comments_reply()
    {
        $params = $this->request->post();

        // 全局发帖次数限制
        $send_comment_limit_day = \app\common\service\ConfigService::get('article','send_comment_limit_day',10);
        $send_count = \app\common\model\Article::where([
            ['user_id','=',$this->userId],
            ['create_time','>',time() - 60*60*24]
        ])->count();
        if($send_count > $send_comment_limit_day){
            return show(config('status.error'),'评论次数过多，明天再试');
        }

        // 回帖权限
        $article = \app\common\model\Article::find($params['article_id']);
        if($article->circle_id>0){
            $circle = \app\common\model\Circle::find($article->circle_id);
            $user = \app\common\model\User::find($this->userId);
            if($circle->reply_level>0){
                // 限制回帖等级
                if($user->level<$circle->reply_level){
                    return show(config('status.error'),'此圈子需要'.$circle->send_level.'级才能回复');
                }
            }

            // 禁止回复
            if($circle->disable_reply==1){
                return show(config('status.error'),'本圈子设置了禁止回复');
            }

            // 禁止回复图片
            if($circle->disbale_upload_image==1){
                if(strstr($params['data']['text'],'@image')){
                    return show(config('status.error'),'本圈子设置了禁止回复图片');
                };
            }

            // 禁止上传附件
            if($circle->diable_upload_file==1){
                if(strstr($params['data']['text'],'@fiel')){
                    return show(config('status.error'),'本圈子设置了禁止回复附件');
                };
            }
            
        };

        if($article->reply_only_visible_author == 1){
            return show(config('status.error'),'回复仅作者可见');
        }

        checkDangerTxt($params['data']['text']);

        $uid = $this->userId;

        if (isset($params['fake_user_id'])) {
            $fakeUser = (new \app\common\model\User)->queryFake()
                ->where('id',$params['fake_user_id'])
                ->where('is_fake_user', 1)
                ->where('fake_user_owner_id', $this->userId)
                ->find();

            if (!$fakeUser) {
                return show(config('status.error'),'用户不存在');
            }

            $uid = $fakeUser['id'];
            UserLogic::updateFake($fakeUser);
        }
        
        $res = ArticleLogic::commentsReply($params,$uid);

        if($res){
            $this->noticeCommentMp($params);

            $dun = ArticleDun::where('article_id',$params['article_id'])->where('user_id',$this->userId)->find();

            if ($dun) {
                $this->noticeCommentMp($params, $this->userId);
            }

                // 评论奖励积分
                $send_comment_get_integral = \app\common\service\ConfigService::get('article','send_comment_get_integral',0);
                if($send_comment_get_integral>0){
                    \think\facade\Db::startTrans();
                    try{
                        // 增加用户积分
                        $user = \app\common\model\User::findOrEmpty($this->userId);
                        $user->user_integral = $user->user_integral + $send_comment_get_integral;
                        $user->save();
                        // 记录积分流水
                        $remark = '评论成功奖励积分：'.$send_comment_get_integral;
                        \app\common\logic\AccountLogLogic::add($this->userId, \app\common\enum\AccountLogEnum::BW_INC_SIGN, \app\common\enum\AccountLogEnum::INC, $send_comment_get_integral, '', $remark);
                        \think\facade\Db::commit();
                    }catch(\Exception $e){
                        \think\facade\Db::rollback();
                    }
                }
        }

        return $this->success();
    }

    /**
     * 评论置顶
     */
    public function comment_pin($id)
    {
        $comment = \app\common\model\ArticleComment::find($id);

        $article = \app\common\model\Article::find($comment->aid);

        if($article->user_id != $this->userId){
            return show(config('status.error'),'没有权限');
        }

        \app\common\model\ArticleComment::update(['is_pin'=>0],['aid'=>$comment->aid]);
        \app\common\model\ArticleComment::update(['is_pin'=>1],['id'=>$id]);

        return show(config('status.success'),'设置成功');

    }

    /**
     * 评论通知作者
     * @param mixed $params
     * @return void
     */
    private function noticeCommentMp($params, $uid=null)
    {

       try {
           $ouid = $uid;

           // 评论被回复提醒
           $notice_comment_template_id = \app\common\service\ConfigService::get('mini_program', 'notice_comment_template_id', '');
        
           if(!$notice_comment_template_id){
                return;
            }
           $comment = $params['data']['text'];
           $comment = mb_substr($comment,0,6,'UTF-8');
           $comment .='...';
           

           $articleInfo = \app\common\model\Article::find($params['article_id']);

           if(!$uid && $articleInfo->user_id == $this->userId){
                return;
           }

           if (!$uid) {
               $uid = $articleInfo->user_id;
           }

           $userAuth = \app\common\model\UserAuth::where('user_id',$uid)->find();

           if(!$userAuth){
                return;
           }

           $title = $articleInfo->title;
           if(empty($title)){
                $title = mb_substr($articleInfo->content,0,20,'UTF-8');
           }

           $message = [
               'thing1' =>  ['value' => strip_tags($title)],//作品名称
               'time3' =>  ['value' => date('Y-m-d H:i:s')],//评论时间
               'thing4' =>  ['value' => $this->userInfo['nickname']],//评论用户
               'thing5' =>  ['value' => $comment],//评论内容
           ];
           
           $config = \app\common\service\WeChatConfigService::getWechatConfigByTerminal(1);
           $app = new \EasyWeChat\MiniApp\Application($config);
           
           $result = $app->getClient()->post('/cgi-bin/message/subscribe/send', [
              'json'=>[
                   'template_id'=>$notice_comment_template_id,
                   'touser' => $userAuth->openid,
                'data'=> $message,
                'page'=>'/pages_main/reviewDetails/reviewDetails?id='.$articleInfo->id,
              ]
           ]);

           if($result->toArray(false)['errcode'] == '43101'){
                $this->noticeCommentMpLong($params,$ouid);
           };
        //    dd($result->toArray(false));
           

       } catch (\Throwable $e) {
           // 失败
        //    echo '请求失败';
            // dd($e->getMessage());

            // 一次性订阅通知失败调用查询接口
            $this->noticeCommentMpLong($params,$ouid);
       }

   }

   /**
    * 长期推送通知模板
    */
    private function noticeCommentMpLong($params,$uid=null)
    {
       try {
           // 评论被回复提醒
           $notice_chat_template_id = \app\common\service\ConfigService::get('mini_program', 'notice_chat_template_id', '');
        
           if(!$notice_chat_template_id){
                return;
            }
           $comment = $params['data']['text'];
           $comment = mb_substr($comment,0,6,'UTF-8');
           $comment .='...';
           

           $articleInfo = \app\common\model\Article::find($params['article_id']);

           if(!$uid&&$articleInfo->user_id == $this->userId){
                return;
           }

           if (!$uid) {
               $uid = $articleInfo->user_id;
           }

           $userAuth = \app\common\model\UserAuth::where('user_id',$uid)->find();

           if(!$userAuth){
                return;
           }

           $title = $articleInfo->title;
           if(empty($title)){
                $title = mb_substr($articleInfo->content,0,20,'UTF-8');
           }

           $message = [
                'short_thing1' =>  ['value' => '你好'],
                'thing4' =>  ['value' => '您收到一条评论'],
           ];
           
           $config = \app\common\service\WeChatConfigService::getWechatConfigByTerminal(1);
           $app = new \EasyWeChat\MiniApp\Application($config);
           
           $result = $app->getClient()->post('/cgi-bin/message/subscribe/send', [
              'json'=>[
                   'template_id'=>$notice_chat_template_id,
                   'touser' => $userAuth->openid,
                'data'=> $message,
                'page'=>'/pages_main/reviewDetails/reviewDetails?id='.$articleInfo->id,
              ]
           ]);

        //    dd($result->toArray(false));
           

       } catch (\Throwable $e) {
            // 失败
            //    echo '请求失败';
            //    dd($e->getMessage());
       }

   }

    /**
     * @notes 删除帖子评论
     * @return \think\response\Json
     */
    public function comments_delete()
    {
        $params =  $this->request->post();
        ArticleLogic::commentsDelete($params,$this->userId);
        return $this->success('删除成功',[],1,1);
    }

    /**
     * @notes 帖子付费订单
     * @return \think\response\Json
     */
    public function articleOrder()
    {
        $params = $this->request->post();
        $params['user_id'] = $this->userId;
        $params['terminal'] = $this->userInfo['terminal'];
        $result = ArticleLogic::articleOrder($params);
        if($result) {
            return $this->data($result);
        }
        return show(config('status.error'),'');
    }

    /**
     * 擦亮
     */
    public function polish($id)
    {
        $article = \app\common\model\Article::where([
            'user_id'=>$this->userId,
            'id'=>$id,
            'status'=>1,
        ])
        ->find();

        if(time() - $article->polish_time < 60*60*24){
            return show(config('status.error'),'24小时内容只能擦亮一次');
        };

        $article->polish_time = time();
        $article->save();

        return show(config('status.success'),'擦亮成功');
        
    }


    /**
     * 提交打赏
     * @return void
     */
    public function submit_reward()
    {
        $params = $this->request->post();

        // $user = \app\common\model\User::find($this->userId);

        /*
        if($user->user_money < $params['amount']){
            return show(config('status.success'),'余额不足');
        }
        */

        if ($params['amount'] < 0.01) {
            return show(config('status.error'), '金额不能少于0.01');
        }

        if ($params['amount'] > 99999999.99) {
            return show(config('status.error'), '金额不合法');
        }

        $article = \app\common\model\Article::find($params['article_id']);

        if ($this->userId == $article->user_id) {
            return show(0, '不能给自己打赏');
        }

        // $to_user = \app\common\model\User::find($article->user_id);

        // \think\facade\Db::startTrans();
        try{
/*
             //扣除余额
            $res = $to_user->dec('user_money', $params['amount'])->save();

            // 记录余额流水
            \app\common\logic\AccountLogLogic::add(
                $this->userId,
                // \app\common\enum\AccountLogEnum::BNW_DEC_ORDER,
                '103',//帖子打赏
                \app\common\enum\AccountLogEnum::DEC,
                $params['amount'],
                $params['article_id'],
            );

            // 记录打赏记录表
            \app\common\model\Rewards::create([
                "article_id"=>$params['article_id'],
                "from_user_id"=>$this->userId,
                'to_user_id'=>$to_user->id,
                'amount'=>$params['amount'],
                'message'=>isset($params['amount'])?$params['message']:'',
            ]);
            
            \think\facade\Db::commit();

            return show(config('status.success'),'打赏成功');
*/
            // 创建订单
            $order_data = [
                'sn'=>time().round(10000,99999),
                'user_id'=>$this->userId,
                'article_id'=>$article->id,
                'order_amount'=>$params['amount'],
                'message'=>isset($params['amount'])?$params['message']:'',
            ];
            $res = \app\common\model\ArticleRewardOrder::create($order_data);

            if (!$res) {
                return show(config('status.error'),'订单创建失败');
            }

            return show(config('status.success'),'订单创建成功',[
                'order_id'=>$res->id,
            ]);
        }catch(\Exception $e){
            // \think\facade\Db::rollback();
            return show(config('status.error'),$e->getMessage());
        }

    }
    
    /**
     * 打赏记录列表
     */
    public function reward_list($article_id)
    {
        $list = \app\common\model\Rewards::with(['fromUser'])->where('article_id',$article_id)->paginate(20);
        return show(config('status.success'),'帖子打赏列表详情',$list);
    }
        
    /**
     * 删除自己的评论
     */
    public function comment_del($id)
    {
        $comment = \app\common\model\ArticleComment::find($id);

        $article = \app\common\model\Article::find($comment->aid);

        // 别人帖子
        if($article->user_id != $this->userId){

            if($comment->user_id != $this->userId){
                return show(config('status.error'),'您没有权限删除');
            }

            // if($comment->pid==0){
            //     if($comment->user_id != $this->userId){
            //         return show(config('status.error'),'您没有权限删除');
            //     }
            // }else{
            //     // $pid_comment = \app\common\model\ArticleComment::find($comment->pid);
            //     // if($this->userId != $pid_comment->user_id){
            //     //     return show(config('status.error'),'没有权限删除');
            //     // }
            // }

        }

        

        $comment->delete();
        
        return show(config('status.success'),'删除成功');
    }

    /**
     * 我的分享记录
     * @return void
     */
    public function myShareLog()
    {

        $list = \app\common\model\ArticleShareLog::with(['user','fromUser'])
        ->order('create_time','desc')
        ->paginate(20);

        return show(config('status.success'),'我的分享访问记录',$list);
    }

    /**
     * 圈主删贴功能
     */
    public function circle_del($id)
    {

        $article = \app\common\model\Article::find($id);

        $circle = \app\common\model\Circle::find($article->circle_id);

        if($circle->user_id!= $this->userId){
            return show(config('status.error'),'只有圈主能删贴');
        }

        \app\common\model\Article::destroy($id);

        return show(config('status.success'),'删除成功');
    }

    /**
     * 圈主设置推荐
     */
    public function circle_recomment($id)
    {
        $article = \app\common\model\Article::find($id);

        $circle = \app\common\model\Circle::find($article->circle_id);

        if($circle->user_id!= $this->userId){
            return show(config('status.error'),'只有圈主能设置
            ');
        }

        \app\common\model\Article::where('id',$id)->update(['is_recomment'=>1]);

        return show(config('status.success'),'设置成功');
        
    }

    /**
     * 圈主取消推荐
     */
    public function circle_recomment_cancel($id)
    {
        $article = \app\common\model\Article::find($id);

        $circle = \app\common\model\Circle::find($article->circle_id);

        if($circle->user_id!= $this->userId){
            return show(config('status.error'),'只有圈主能设置');
        }

        \app\common\model\Article::where('id',$id)->update(['is_recomment'=>0]);

        return show(config('status.success'),'设置成功');
    }

    /**
     * 分享次数
     */
    public function shareCanllback($id)
    {
        $article = \app\common\model\Article::find($id);
        $article->inc('share_count',1)->save();

        return show(config('status.success'),'ok');
    }

    
        
}