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

namespace app\api\controller;

use app\api\logic\CircleLogic;
use app\common\model\UserCircle;

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

    public function field()
    {
        $circle_data = \app\common\model\CircleField::where('circle_id', input('circle_id'))
        ->where('is_search',1)
        ->select()
        ->toArray();

        foreach($circle_data as &$v){
            $v['value_list'] = explode(PHP_EOL,$v['value']);
        }

        return show(config('status.success'),'筛选条件',$circle_data);
    }

    public function followers($id)
    {
        $data = UserCircle::where('circle_id', $id)
            ->with(['user', 'user.user_level'])
            ->paginate(14)
            ->toArray();

        foreach ($data['data'] as &$item) {
            $item['user']['is_follow'] = !!\app\common\model\UserFollow::where([ 'follow_user_id' => $item['user_id'], 'user_id' => $this->userId ])->find();
            $item['user']['level'] = \app\common\model\User::where('id', $item['user_id'])->with(['user_level' => function ($query) {$query->field('id,name,rank');}])->findOrEmpty()->toArray()['user_level'];
        }

        return show(config('status.success'),'用户列表',$data);
    }

    public function editCircle()
    {
        $params = $this->request->post();

        $circle = \app\common\model\Circle::where('id', $params['id'])->find();

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

        $circle->save($params);

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

    public function cancelFollow()
    {
        $params = $this->request->post();

        $circle_id = $params['circle_id'];
        $follow_user_ids = $params['follow_user_ids'];

        $circle = \app\common\model\Circle::where('id', $circle_id)->find();

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

        $follow = UserCircle::where('circle_id', $circle_id)
            ->where('user_id', 'in', explode(',', $follow_user_ids))
            ->find();

        if ($follow) {
            $follow->delete();
            return show(config('status.success'),'取消成功');
        }

        return show(config('status.error'),'取消失败');
    }

    /**
     * 创建圈子
     */
    public function create()
    {
        $params = $this->request->post();

        $data = [
            'user_id'=>$this->userId,
            'name'=>$params['name'],
            'cate_id'=>$params['cate_id'],
            'icon'=>$params['icon'],
            'synopsis'=>$params['synopsis'],
            'template'=>'circle',
            'chat_status'=>$params['chat_status']==1?1:0,
            'bg_image'=>$params['bg_image'],
            'status'=>0,
            // 'is_pay'=>0,//未支付
            'is_pay'=>1,//已支付
            'subscription_price'=>$params['subscription_price'],
            'only_circle_send'=>$params['only_circle_send']??0,
            'longitude' =>  $params['longitude'],
            'latitude' => $params['latitude']
        ];

        $res=\app\common\model\Circle::create($data);

        // 记录日志
        $text = $_SERVER;
        $text['circle_id']=$res->id;
        \app\common\model\UserLog::create([
            'user_id'=>$this->userId,
            'ip'=>$this->request->ip(),
            'remark'=>'创建圈子',
            'code'=>'create_circle',
            'text'=>json_encode($text,true),
        ]);
        
        return show(config('status.success'),'创建成功');
    }

    /**
     * @notes 圈子列表
     * @return \think\response\Json
     */
    public function lists()
    {
        return $this->dataLists();
    }

    public function cateList()
    {
        return $this->dataCateLists();
    }

    /**
     * 圈子列表-首页
     */
    public function circleHomeLists(){

        $lists = CircleLogic::circleHomeLists();
        return $this->data($lists);
    }

    /**
     * 用户圈子列表
     */
    public function userCircleLists(){

        $lists = CircleLogic::userLists($this->userId);
        return $this->data($lists);
    }


    /**
     * 圈子详情
     */
    public function detail(){

        $params = $this->request->get();
        try{
            $lists = CircleLogic::detail($params,$this->userId);
            return $this->data($lists);
        }catch(\Exception $e){
            return show(config('status.error'),$e->getMessage());
        }

    }

    /**
     * @notes 加入取消圈子
     */
    public function handleCircle()
    {   
        $params = $this->request->post();
        CircleLogic::handleCircle($params,$this->userId);
        return $this->success();
    }

    /**
     * @notes 圈子付费订单
     * @return \think\response\Json
     */
    public function circleOrder()
    {
        $params = $this->request->post();
        $params['user_id'] = $this->userId;
        $params['terminal'] = $this->userInfo['terminal'];
        $result = CircleLogic::circleOrder($params);
        if($result) {
            return $this->data($result);
        }
    }

    /**
     * 圈子发帖需付费
     * 创建订单
     */
    public function releaseOrder()
    {
        $params = $this->request->post();
        $params['user_id'] = $this->userId;
        $params['terminal'] = $this->userInfo['terminal'];
        $result = CircleLogic::releaseOrder($params);
        if($result) {
            return $this->data($result);
        }
    }

    /**
     * 查询用户我创建的圈子
     */
    public function mylist()
    {
        $params = $this->request->get();
        $where = ['user_id'=>$this->userId,];

        if(isset($params['status'])){
            // 查询待审核和已拒审
            $where['status'] = $params['status'];
        }
        
        $list = \app\common\model\Circle::where($where)
        ->order('create_time','desc')
        ->paginate(10);
        return show(config('status.success'),'我发布的列表',$list);
    }

    /**
     * 获取编辑信息接口
     */
    public function edit($id)
    {
        $data = \app\common\model\Circle::where([
            'id'=>$id,
            'user_id'=>$this->userId
        ])
        ->find();

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

    /**
     * 圈主修改圈子信息
     */
    public function update()
    {
        $params = $this->request->post();

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

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

        $update = [];

        if(isset($params['name'])){
            $update['name']=$params['name'];
        }
        if(isset($params['synopsis'])){
            $update['synopsis']=$params['synopsis'];
        }
        if(isset($params['icon'])){
            $update['icon']=$params['icon'];
        }
        if(isset($params['cate_id'])){
            $update['cate_id']=$params['cate_id'];
        }
        if(isset($params['template'])){
            $update['template']=$params['template'];
        }
        if(isset($params['chat_status'])){
            $update['chat_status']=$params['chat_status'];
        }
        if(isset($params['bg_image'])){
            $update['bg_image']=$params['bg_image'];
        }
        if(isset($params['notice'])){
            $update['notice']=$params['notice'];
        }
        if(isset($params['subscription_price'])){
            $update['subscription_price']=$params['subscription_price'];
        }
        if(isset($params['release_price'])){
            $update['release_price']=$params['release_price'];
        }
        if(isset($params['vip_level_id'])){
            $update['vip_level_id']=$params['vip_level_id'];
        }
        if(isset($params['template'])){
            $update['template']=$params['template'];
        }
        if(isset($params['chat_status'])){
            $update['chat_status']=$params['chat_status'];
        }
        if(isset($params['send_level'])){
            $update['send_level']=$params['send_level'];
        }
        if(isset($params['reply_level'])){
            $update['reply_level']=$params['reply_level'];
        }
        if(isset($params['disable_reply'])){
            $update['disable_reply']=$params['disable_reply'];
        }
        if(isset($params['cate_id'])){
            $update['cate_id']=$params['cate_id'];
        }
        if(isset($params['send_limit_day'])){
            $update['send_limit_day']=$params['send_limit_day'];
        }
        if(isset($params['only_circle_send'])){
            $update['only_circle_send']=$params['only_circle_send'];
        }

        $update['status']=0;

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

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

    /**
     * 注销申请
     */
    public function logoff()
    {
        $params = $this->request->post();

        $circle = \app\common\model\Circle::find($params['circle_id']);

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

        $res = \app\common\model\CircleLogoff::where([
            'circle_id'=>$params['circle_id'],
            'status'=>0
        ])->find();
        if(!$res){
            return show(config('status.error'),'当前圈子已提交过注销申请');
        }
        
        // 创建注销信息
        $data = [
            'user_id'=>$this->userId,
            'circle_id'=>$params['circle_id'],
            'msg'=>$params['msg'],
            'status'=>0
        ];

        \app\common\model\CircleLogoff::create($data);

        return show(config('status.success'),'注销申请提交成功');
        
    }

    /**
     *  签到送经验
     * @return void
     */
    public function sign()
    {
        $params = $this->request->get();
        // 仅关注可签到送积分
        $follow = \app\common\model\UserCircle::where([
            'user_id'=>$this->userId,
            'circle_id'=>$params['circle_id']
        ])->find();
        if(!$follow){
            return show(config('status.error'),'请关注后签到');
        }

        $circle = \app\common\model\Circle::find($params['circle_id']);
        // 签到获得经验
        $experience = $circle->signal_get_experience;
        if($experience == 0){
            return show(config('status.error'),'当前圈子未设置签到奖励经验');
        }

        // 每日只能签到一次
        $sign = \app\common\model\CircleSign::where([
            ['user_id','=',$this->userId],
            ['circle_id','=',$params['circle_id']],
            ['create_time','>',strtotime('today')],
        ])->find();
        if($sign){
            return show(config('status.error'),'今天已签到');
        }


        
        // 记录签到数据
        \think\facade\Db::startTrans();
        try{

            $sign_data = [
                'user_id'=>$this->userId,
                'circle_id'=>$params['circle_id'],
                'experience'=>$experience,
            ];

            // 记录签到记录
            \app\common\model\CircleSign::create($sign_data);
            
            // 计算连续签到次数
            // 查看昨天是否签到：有：连续签到次数+1，无:连续签到次数初始化：1
            $yesterdaySignal =  \app\common\model\CircleSign::where([
                ['user_id','=',$this->userId],
                ['circle_id','=',$params['circle_id']],
                ['create_time','<',strtotime('today')],
                ['create_time','>',strtotime('yesterday')]
            ])->count();
            if($yesterdaySignal>0){
                // 增加连续签到次数
                \app\common\model\CircleLevel::where([
                    'user_id'=>$this->userId,
                    'circle_id'=>$params['circle_id'],
                ])->inc('keep_day',1)->save();
            }else{
                \app\common\model\CircleLevel::where([
                    'user_id'=>$this->userId,
                    'circle_id'=>$params['circle_id'],
                ])->update([
                    'keep_day'=>1,
                ]);
            }

            // 增加经验值
            \app\common\model\CircleLevel::where([
                'user_id'=>$this->userId,
                'circle_id'=>$params['circle_id'],
            ])->inc('experience',$experience)->save();

            // 查询用户在圈子内的等级
            $userCircleLevel = \app\common\model\CircleLevel::where('user_id',$this->userId)->find();
            
            // 圈子内等级升级检测
            $circleLevelList = \app\common\model\CircleUserLevel::select()->toArray();
            foreach($circleLevelList as $v){
                if($userCircleLevel->experience > $v['experience']){
                    $userCircleLevel->level = $v['id'];
                    $userCircleLevel->save();
                }
            }

            \think\facade\Db::commit();

            return show(config('status.success'),'签到成功',['experience'=>$experience]);

        }catch(\Exception $e){
            \think\facade\Db::rollback();
            return show(config('status.error'),$e->getMessage());
        }

    }

    /**
     * 查询我的签到记录
     */
    public function mySignList()
    {
        $params = $this->request->get();

        $where = [
            ['user_id','=',$this->userId],
            ['circle_id','=',$params['circle_id']],
        ];

        if(isset($params['min_time'])){
            $where[]=[
                'create_time','<',$params['min_time']
            ];
        }

        if(isset($params['max_time'])){
            $where[]=[
                'create_time','<',$params['max_time']
            ];
        }

        $list = \app\common\model\CircleSign::where($where)->order('create_time','asc')
        ->paginate(31);

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

    /**
     * 查询我的圈子等级连续签到天数信息
     */
    public function myCircleLevel($circle_id)
    {
        $data = \app\common\model\CircleLevel::with(['circleUserLevel'])
        ->where([
            'circle_id'=>$circle_id,
            'user_id'=>$this->userId,
        ])
        ->find();

        return \show(config('status.success'),'',$data);
    }

    /**
     * 签到排行榜
     */
    public function signTop($circle_id)
    {
        $list = \app\common\model\CircleLevel::with(['user'])
        ->where([
            ['circle_id','=',$circle_id],
            ['keep_day','>',0],
        ])
        ->order(['keep_day'=>'desc','update_time'=>'desc'])
        ->paginate(20);

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


    /**
     * 圈子付费创建订单
     */
    public function circle_create_order()
    {
        $params = $this->request->post();

        $circle = \app\common\model\Circle::find($params['circle_id']);

        if(!$circle){
            return show(config('status.error'),'圈子不存在');
        }

        if($circle->is_pay==1){
            return show(config('status.error'),'已支付过了');
        }

        // 创建订单
        $price = \app\common\service\ConfigService::get('circle','create_circle_price');

        $data = [
            'sn'            => time().rand(00000,99999),
            'terminal'      => $this->userInfo['terminal'],
            'user_id'       => $this->userId,
            'pay_status'    => \app\common\enum\PayEnum::UNPAID,
            'pay_way'       => $params['pay_way'] ?? 1,//余额支付
            'order_amount'  => $price,
            'circle_id'      => $params['circle_id'],
        ];

        $order = \app\common\model\CircleCreateOrder::create($data);

        if(!$order){
            return show(config('status.error'),'error');
        }

        return show(config('status.success'),'ok',[
            'order_id' => $order->id,
            'from' => 'create_circle'
        ]);
        
    }


    /**
     * 圈子等级列表
     */
    public function circleLevelList()
    {

        $list = \app\common\model\CircleUserLevel::order('level','desc')
        ->select()
        ->toArray();

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

    }


}