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


namespace app\api\logic;

use app\common\logic\BaseLogic;
use app\common\model\Article;
use app\common\model\ChatCircleMessage;
use app\common\model\Circle;
use app\common\model\UserCircle;
use app\common\service\FileService;
use app\common\model\CircleOrder;
use app\common\model\CircleReleaseOrder;
use app\common\enum\PayEnum;

class CircleLogic extends BaseLogic
{

    /**
     * 首页tab列表
     */
    public static function circleHomeLists()
    {
        $lists = Circle::where('is_show', 1)->where('home_show', 1)
            ->order("sort",'desc')
            ->select()
            ->toArray();
        return $lists;
    }


    public static function userLists($userId)
    {
        $lists = UserCircle::with(['circle' => function($query){
            $query->append(['collect_num']);
        }])
            ->where('user_id', $userId)
            ->limit(4)
            ->select()
            ->toArray();
        return $lists;
    }

    /**
     * 圈子详情
     */
    public static function detail($params , $userId = 0)
    {
        // 判断有无安装插件
        $fieldWith = ['user'];
        if(isActivePluginByPluginName('field')){
            $fieldWith[] = 'subCategory';
            $fieldWith[] = 'circleField';
        }

        $data = Circle::with($fieldWith)
        ->where('id',$params['id'])->append(['collect_num'])->find()->toArray();

        if($data['is_pay'] == 0){
            throw new \think\Exception('圈子创建者未支付');
        }

        if($data['status'] != 1){
            throw new \think\Exception('圈子待审核或已被封');
        }
        
        if($userId) {
            
            //是否收藏过
            $IsCollect = UserCircle::where(['circle_id' => $params['id'], 'user_id' => $userId])->value('id');
            $data['is_collect'] = $IsCollect ? 1 : 0;

            // 判断是否付费圈子
            $data['is_pay'] = 0;
            if($data['subscription_price']>0){
                // 判断是否付费过
                $order = CircleOrder::where([ 'pay_status' => PayEnum::ISPAID, 'circle_id' => $data['id'], 'user_id' => $userId])->count();
                if($order){
                    $data['is_pay'] = 1;
                }
            };

            // 在这个圈子的等级
            $data['circle_level']=\app\common\model\CircleLevel::with(['circleUserLevel'])
            ->where([
                'user_id'=>$userId,
                'circle_id'=>$params['id'],
            ])->find();
            
        }

        $data['chat_user_count'] = ChatCircleMessage::where('circle_id', $params['id'])->group('from_id')->count();

        return $data;
    }

    /**
     * @notes 加入圈子
     * @param $params
     */
    public static function handleCircle($params , $userId = 0)
    {
        //加入
        if($params['is_collect']){
    
            \think\facade\Db::startTrans();
            try{
                $collect = UserCircle::where(['circle_id'=>$params['id'],'user_id'=>$userId])->findOrEmpty();
                if(!$collect->isEmpty()){
                    return true;
                }
                $collect->user_id = $userId;
                $collect->circle_id =  $params['id'];
                $collect->save();

                // 初始化圈子内会员等级
                // 查询有无此圈子的等级 没有则重新初始化等级
                $circle_level = \app\common\model\CircleLevel::where([
                    'user_id'=>$userId,
                    'circle_id'=>$params['id']
                ])->find();
                if(!$circle_level){
                    // 初始化等级
                    $circle_level_data = [
                        'level'=>1,
                        'user_id'=>$userId,
                        'circle_id'=>$params['id']
                    ];
                    \app\common\model\CircleLevel::create($circle_level_data);
                }


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

        //取消删除
        UserCircle::destroy(['circle_id'=>$params['id'],'user_id'=>$userId]);
        return true;
    }

    /**
     * 添加付费订单
     */
    public static function circleOrder($params)
    {

        $circle = Circle::find($params['circle_id']);

        $data = [
            'sn'            => generate_sn((new CircleOrder()),'sn'),
            'terminal'      => $params['terminal'],
            'user_id'       => $params['user_id'],
            'pay_status'    => PayEnum::UNPAID,
            'pay_way'       => $params['pay_way'] ?? 2,
            'order_amount'  => $circle['subscription_price'],
            'circle_id'    => $params['circle_id'],
        ];

        if($circle->user_id){
            $data['sell_user_id']=$circle->user_id;
        }

        $order = CircleOrder::create($data);
        return [
            'order_id' => $order->id,
            'from' => 'circle'
        ];

    }

    /**
     * 发布需付费订单
     */
    public static function releaseOrder($params)
    {

        $circle = Circle::find($params['circle_id']);

        $data = [
            'sn'            => generate_sn((new CircleReleaseOrder()),'sn'),
            'terminal'      => $params['terminal'],
            'user_id'       => $params['user_id'],
            'pay_status'    => PayEnum::UNPAID,
            'pay_way'       => $params['pay_way'] ?? 2,
            'order_amount'  => $circle['subscription_price'],
            'circle_id'    => $params['circle_id']
        ];

        $order = CircleReleaseOrder::create($data);
        return [
            'order_id' => $order->id,
            'from' => 'circle_release'
        ];

    }
    
}