<?php
namespace app\admin\controller;

use app\model\Admins;
use app\model\Follows;
use app\model\Orders;
use support\Log;
use support\Request;

class FollowController extends base
{
    public function index(Request $request) {
        $admin = $request->get('admin');
        $sn = $request->get('sn');
        $self = $request->get('self');
        $times = $request->get('times');

        $adminInfo = Admins::where('id', $request->admin->id)->find();
        if ($adminInfo->is_franchisee) {
            return $this->franchiseeList($request, $adminInfo);
        }

        $query = Follows::with(['admin','orders'])->order('id', 'desc');

        if($request->admin->is_super == 0 || $self) {
            $query->where('admin_id', $request->admin->id);
        }

        if(!empty($admin)) {
            $admin_id = Admins::where('username', $admin)->value('id');
            $query->where('admin_id', $admin_id ?? 0);
        }

        if(!empty($sn)) {
            $order_id = Orders::where('sn', $sn)->value('id');
            $query->where('order_id', $order_id ?? 0);
        }

        if(!empty($times) && count($times)) {
            $query->whereBetween('create_time', [strtotime($times[0]),strtotime($times[1])]);
        }
        
        $list = $query->paginate($request->get('limit', 30));

        return $this->success($list->append(['status_name']));
    }

    public function franchiseeList($request, $adminInfo)
    {
        $admin = $request->get('admin');
        $sn = $request->get('sn');
        $times = $request->get('times');

        $thirdProductId = explode(',', $adminInfo->product_ids);
        if (count($thirdProductId) <= 0) {
            return $this->success([]);
        }

        $query = Follows::with(['admin','orders'])
            ->join('orders', 'orders.id = follows.order_id')
            ->order('follows.id', 'desc')
            ->field('follows.*')
            ->whereIn('product_id', $thirdProductId);

        if(!empty($admin)) {
            $admin_id = Admins::where('username', $admin)->value('id');
            $query->where('follows.admin_id', $admin_id ?? 0);
        }

        if(!empty($sn)) {
            $order_id = Orders::where('sn', $sn)->value('id');
            $query->where('follows.order_id', $order_id ?? 0);
        }

        if(!empty($times) && count($times)) {
            $query->whereBetween('follows.create_time', [strtotime($times[0]),strtotime($times[1])]);
        }

        $list = $query->paginate($request->get('limit', 30));

        return $this->success($list->append(['status_name']));
    }
}