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

namespace app\api\controller;
use think\facade\Db;

/**
 * 推广插件
 */
class Pin extends BaseShopController
{

    public array $notNeedLogin = ['position','banner'];

    /**
     * 获取推广位置
     */
    public function position()
    {
        $list = \app\common\model\PinPosition::where('status',1)
        ->select();

        return show(config('status.success'),'',$list);
    }
    
    /**
     * 推广套餐
     */
    public function packageList()
    {
        $where = [];
        $params = $this->request->get();

        if(isset($params['position_id'])){
            $where[]=['position_id','=',$params['position_id']];
        }

        $list = \app\common\model\PinPackage::with('position')
        ->where('status',1)
        ->where($where)
        ->select()->toArray();

        // 计算剩余广告位
        foreach($list as &$v){
            $v['sell_count'] = \app\common\model\PinRecord::where([
                ['position_id','=',$v['position_id']],
                ['end_time','<',time()]
            ])->count();
        }

        return show(config('status.success'),'套餐列表',$list);
        
    }

    /**
     * 创建推广订单
     */
    public function createOrder()
    {
        $params = $this->request->post();

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

        // dd($article->toArray());

        $package = \app\common\model\PinPackage::with('position')
        ->find($params['package_id']);

        if(strstr($package->position->code,'circle') && !$article->circle_id){
            return show(config('status.error'),'当前帖子没有设置圈子，不支持投放到圈子');
        };


        // 重复推广判断（一个帖子一个位置同时只能一个）
        // \app\common\model\PinRecord::where([
        //     ['article_id','=',$params['article_id']],
        //     ['position_id','=',$package->position->id],
        // ])->count();
        $count = \app\common\model\PinRecord::where([
            ['article_id','=',$params['article_id']],
            ['position_id','=',$package['position_id']],
            ['start_time','<',time()],
            ['end_time','>',time()],
        ])->count();
        if($count>0){
            return show(config('status.error'),'此帖子正在推广，请勿重置推广，或更换其他位置推广');
        }

        // 判断有无剩余广告位空缺
        $active_position_num = $package->position->max - $count; 
        if($active_position_num == 0){
            return show(config('status.error'),'没有剩余的广告位');
        }

        // 创建订单
        $params['user_id'] = $this->userId;
        $params['terminal'] = $this->userInfo['terminal'];

        $data = [
            'sn'            => time().rand(00000,99999),
            'terminal'      => $params['terminal'],
            'user_id'       => $params['user_id'],
            'pay_status'    => \app\common\enum\PayEnum::UNPAID,
            'pay_way'       => $params['pay_way'] ?? 2,
            'order_amount'  => $package['price'],
            'article_id'      => $params['article_id'],
            'package_id'      => $params['package_id'],
        ];

        $order = \app\common\model\PinOrder::create($data);
        if(!$order){
            return show(config('status.error'),'error');
        }

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

    /**
     * 推广订单列表
     */
    public function orderList()
    {

        $params = $this->request->get();

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

        if(isset($params['ids'])){
            $where[]=[
                'id','in',explode(',',$params['ids'])
            ];
        }

        $list = \app\common\model\PinOrder::with(['package'])
        ->where($where)
        ->order('create_time','desc')
        ->select();

        return show(config('status.success'),'订单列表',$list);

    }

    /**
     * 推广记录
     */
    public function record()
    {
        $list = \app\common\model\PinRecord::with(['article','position','order'])
        ->where('user_id',$this->userId)
        ->select();
        
        return show(config('status.success'),'推广记录',$list);
    }

    /**
     * 上传广告图
     * @return \think\response\Json
     */
    public function updateBanner()
    {
        $params = $this->request->post();
        $list = \app\common\model\PinRecord::where(
            [
                ['user_id','=',$this->userId],
                ['id','=',$params['record_id']],
            ]
        )->update(['image'=>$params['image']]);

        return show(config('status.success'),'推广记录',$list);
    }

    /**
     * 轮播图广告
     */
    public function banner()
    {
        $code = $this->request->get('code');

        $position = \app\common\model\PinPosition::where('code',$code)->find();

        if(!$position){
            return show(config('status.error'),'没有找到数据');
        }

        // 查询推广记录
        $record = \app\common\model\PinRecord::with(['article'])
        ->where([
            ['position_id','=',$position->id],
            ['start_time','<',time()],
            ['end_time','>',time()],
            ['status','=',1]
        ])
        ->field('id,article_id,image')
        ->select()
        ->toArray();

        return show(config('status.success'),'轮播图列表',$record);
    }



    

}
