<?php

namespace App\Services;

use App\Exports\Export;
use App\OrderIssue;
use App\OrderIssueProcessLog;
use App\Owner;
use App\Services\common\QueryService;
use App\User;
use Illuminate\Support\Facades\Auth;
use Maatwebsite\Excel\Facades\Excel;
use App\Traits\ServiceAppAop;


class OrderIssueWorkLoadService
{
    use ServiceAppAop;
    protected $modelClass=OrderIssueWorkLoad::class;
    public function getQuery(array $queryParam)
    {
        $user = Auth::user();
        $owner_ids = $user ? app('UserService')->getPermittingOwnerIds($user) : [];
        $query = OrderIssue::with(['logs.user','order' => function ($query) {
            $query->with(['packages', 'owner']);
        }])->whereHas('order', function ($query) use (&$queryParam, $owner_ids) {
            if ($queryParam['logistic_number'] ?? false) {
               $query->whereHas('packages',function($query)use (&$queryParam){
                   $query->where('order_packages.logistic_number','like',$queryParam['logistic_number']);
               });
            }
            if ($queryParam['owner_id'] ?? false && in_array($queryParam['owner_id'], $owner_ids)) {
                $query->where('owner_id', $queryParam['owner_id']);
            } else {
                $query->whereIn('owner_id', $owner_ids);
            }
        });
        if($queryParam['end_date'] ?? false){
            $query->whereHas('logs',function($query) use(&$queryParam){
                $query->where('type','结束')
                    ->where('created_at','<=',$queryParam['end_date'].' 23:59:59')
                    ->where('created_at','>=',$queryParam['end_date'].' 00:00:00');
            });
        }
        if($queryParam['end_date'] ?? false){
            $query->whereHas('logs',function($query) use(&$queryParam){
                $query->where('type','结束')
                    ->where('created_at','<=',$queryParam['end_date'].' 23:59:59')
                    ->where('created_at','>=',$queryParam['end_date'].' 00:00:00');
            });
        }
        if($queryParam['create_user_id'] ?? false ?? $queryParam['end_user_id'] ?? false){
            if($queryParam['create_user_id'] ?? false){
                $query->whereHas('logs',function($query) use ($queryParam){
                    $query->where('user_id',$queryParam['create_user_id'])->where('type', '创建');
                });
            }
            if($queryParam['end_user_id'] ?? false){
                $query->whereHas('logs',function($query) use ($queryParam){
                    $query->where('user_id',$queryParam['end_user_id'])->where('type', '结束');
                });
            }
        }
        $query->orderByDesc('id');
        unset($queryParam['create_user_id'], $queryParam['end_user_id'], $queryParam['client_no'],
            $queryParam['owner_id'],$queryParam['end_date'],$queryParam['logistic_number']);
        $columnQueryRules = [
            'create_start' => ['alias' => 'created_at', 'startDate' => ' 00:00:00'],
            'order_issue_id'=>['alias' => 'id','multi'=>','],
            'id' =>['multi' => ','],
        ];
        $query = app(QueryService::class)->query($queryParam, $query, $columnQueryRules);
        return $query;
    }

    public function paginate(array $params)
    {
        return $this->getQuery($params)->paginate($params['paginate'] ?? 50);
    }

    public function getUsers()
    {
        $query  =  OrderIssueProcessLog::query()->selectRaw('user_id')->groupBy('user_id')->get();
        $user_ids =  $query->map(function($value){
            return $value->user_id;
        });
        return User::whereIn('id', $user_ids)->get();
    }

    public function getOwners(){
        $owner_ids = app('UserService')->getPermittingOwnerIds(auth()->user())??[];
        return Owner::whereIn('id', $owner_ids)->get();
    }

    public function getOptions(array $arr){
        return [
            'create_user_id' =>$arr['create_user_id'] ?? '',
            'end_user_id' => $arr['end_user_id'] ?? '',
            'client_no' =>  $arr['client_no'] ?? '',
            'owner_id' => $arr['owner_id'] ?? '',
            'create_start' => $arr['owner_id'] ?? '',
            'create_end' => $arr['create_end'] ?? '',
            'order_issue_id' => $arr['order_issue_id'] ?? '',
            'logistic_number'=> $arr['logistic_number'] ?? ''
        ];
    }

    public function exportWorkLoad(array $params)
    {
        unset($params['checkAllSign']);
        if($params['data']??false){
            $params = ['id'=>$params['data']];
        }
        $workLoads = $this->getQuery($params)->get();
        $row = [[
            'id' => '问题件ID',
            'createDate' => '创建时间',
            'endDate' => '完结时间',
            'created_user' => '创建人',
            'end_user' => '结束人',
            'owner' => '客户',
            'logisticNumbers' => '快递单号',
            'processingTime' => '处理时效']];
        $data = [];
        foreach ($workLoads as $workLoad) {
            $logisticNumbers = '';
            if($workLoad['order']['logisticNumbers'] ?? false){
                foreach ($workLoad['order']['logisticNumbers'] as $str){
                    $logisticNumbers.=$str.' ';
                }
            }
            $temp = [
                'id' => $workLoad['id'],
                'createDate' => $workLoad['createLog']['created_at'] ?? '',
                'endDate' => $workLoad['endLog']['created_at'] ?? '',
                'created_user' => $workLoad['createLog']['user']['name'] ?? '',
                'end_user' => $workLoad['endLog']['user']['name'] ?? '',
                'owner' => $workLoad['order']['owner']['name'] ?? '',
                'logisticNumbers' => $logisticNumbers,
                'processingTime' => $workLoad['processingTime'],
            ];
            array_push($data,$temp);
        }
        return  Excel::download(new Export($row,$data),date('YmdHis', time()).'-工作量.xlsx');
    }
}
