<?php

namespace App\Http\Controllers\Admin;

use App\Exports\ReappraiseExport;
use App\Http\Controllers\Controller;
use App\Http\Response\ResponseJson;
use App\Models\Order;
use App\Models\Reappraise;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Facades\Excel;

class ReappraiseController extends Controller
{
    use ResponseJson;

    public function reappraises(Request $request, Order $order)
    {
        $reappraises = $order->reappraises()->keyword()->with('serviceRoleOrder.role:id,name','serviceRoleOrder.serviceUser:user_id,name,mobile', 'operateServiceUser:user_id,name,mobile')->paginate();
        return $this->success('ok', $reappraises);
    }

    /**
     * 获取服务人员被评价数据
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function getUserReappraises(Request $request){
        try {
            $user_id = $request->get('user_id');
            $reappraises = Reappraise::where('user_id',$user_id)->with('serviceRoleOrder.role:id,name','serviceRoleOrder.serviceUser:user_id,name,mobile','operateServiceUser:user_id,name,mobile')->paginate();
            return $this->success('ok',$reappraises);
        }catch (\Exception $e){
            Log::error('getUserReappraises:'.$e->getMessage());
            return $this->failure('获取失败');
        }
    }

    /**
     * 获取用户评分
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function getUserReappraisesScore(Request $request){
        try {
            $user_id = $request->get('user_id');
            $reappraises = Reappraise::where('user_id',$user_id)->select('content','role_id')->get();
            $data = [];
            foreach ($reappraises as $item){
                if(!isset($data[$item->role_id])){
                    $data[$item->role_id] = [];
                    $data[$item->role_id]['firstAnswer'] = 0;
                    $data[$item->role_id]['secondAnswer'] = 0;
                    $data[$item->role_id]['thirdAnswer'] = 0;
                    $data[$item->role_id]['fourthAnswer'] = 0;
                    $data[$item->role_id]['coordinate'] = 0;
                    $data[$item->role_id]['count'] = 0;
                    $data[$item->role_id]['is_recommend'] = 0;
                    $data[$item->role_id]['not_is_recommend'] = 0;
                    $data[$item->role_id]['study'] = 0;
                }
                if(!$item->content){
                    continue;
                }

                $data[$item->role_id]['firstAnswer'] += $item->content['firstAnswer']??0;
                $data[$item->role_id]['secondAnswer'] += $item->content['secondAnswer']??0;
                $data[$item->role_id]['thirdAnswer'] += $item->content['thirdAnswer']??0;
                $data[$item->role_id]['fourthAnswer'] += $item->content['fourthAnswer']??0;
                $data[$item->role_id]['coordinate'] += $item->content['coordinate']??0;
                $data[$item->role_id]['count'] += 1;
                if($item->content['selectValue'] == '推荐'){
                    $data[$item->role_id]['is_recommend'] += 1;
                }else if($item->content['selectValue'] == '不推荐'){
                    $data[$item->role_id]['not_is_recommend'] += 1;
                }
                else if($item->content['selectValue'] == '建议学习升级后'){
                    $data[$item->role_id]['study'] += 1;
                }
            }

            //处理数组
            $list = [];
            foreach ($data as $key =>$value){
                if($value['count'] == 0){
                    continue;
                }
                if($key == 1){
                    $list['main_coach'] = $value;
                    $list['main_coach']['first_answer_avg'] = get_two_float($value['firstAnswer']/$value['count'],2);
                    $list['main_coach']['second_answer_avg'] = get_two_float($value['secondAnswer']/$value['count'],2);
                    $list['main_coach']['third_answer_avg'] = get_two_float($value['thirdAnswer']/$value['count'],2);
                    $list['main_coach']['fourth_answer_avg'] = get_two_float($value['fourthAnswer']/$value['count'],2);
                    $list['main_coach']['coordinate_answer_avg'] = get_two_float($value['coordinate']/$value['count'],2);
                }else if($key == 2){
                    $list['coach'] = $value;
                    $list['coach']['first_answer_avg'] = get_two_float($value['firstAnswer']/$value['count'],2);
                    $list['coach']['second_answer_avg'] = get_two_float($value['secondAnswer']/$value['count'],2);
                    $list['coach']['third_answer_avg'] = get_two_float($value['thirdAnswer']/$value['count'],2);
                    $list['coach']['fourth_answer_avg'] = get_two_float($value['fourthAnswer']/$value['count'],2);
                    $list['coach']['coordinate_answer_avg'] = get_two_float($value['coordinate']/$value['count'],2);
                }else if($key == 3){
                    $list['customer'] = $value;
                    $list['customer']['first_answer_avg'] = get_two_float($value['firstAnswer']/$value['count'],2);
                    $list['customer']['second_answer_avg'] = get_two_float($value['secondAnswer']/$value['count'],2);
                    $list['customer']['third_answer_avg'] = get_two_float($value['thirdAnswer']/$value['count'],2);
                    $list['customer']['fourth_answer_avg'] = get_two_float($value['fourthAnswer']/$value['count'],2);
                    $list['customer']['coordinate_answer_avg'] = get_two_float($value['coordinate']/$value['count'],2);
                }
            }

            return $this->success('ok',$list);
        }catch (\Exception $e){
            Log::error('getUserReappraises:'.$e->getMessage());
            return $this->failure('获取失败');
        }
    }

    /**
     * 获取复评列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function getReappraisesList(Request $request){
        try {
            $keyword = $request->get('keyword');
            $role_id = $request->get('role');
            $start_time = $request->get('start_time');
            $end_time = $request->get('end_time');
            $reappraises = Reappraise::with('serviceRoleOrder.role:id,name','serviceRoleOrder.serviceUser:user_id,name,mobile','operateServiceUser:user_id,name,mobile')
                ->when($role_id,function($query) use ($role_id) {
                    $query->where('role_id',$role_id);
                })
                ->when($start_time,function($query) use ($start_time,$end_time) {
                    $query->whereBetween('created_at',[$start_time,$end_time]);
                })
                ->whereHas('serviceRoleOrder.serviceUser',function ($roleQuery) use ($keyword){
                    if(!empty($keyword)){
                        $roleQuery->where('name','like','%'.$keyword."%")->orWhere('mobile','like','%'.$keyword."%");
                    }
                })
//                ->orWhereHas('operateServiceUser',function ($roleQuery) use ($keyword){
//                    if(!empty($keyword)){
//                        $roleQuery->where('name','like','%'.$keyword."%")->orWhere('mobile','like','%'.$keyword."%");
//                    }
//                })
                ->orderByDesc('id')
                ->paginate();
            return $this->success('ok',$reappraises);
        }catch (\Exception $e){
            Log::error('getReappraisesList:'.$e->getMessage());
            return $this->failure('获取失败');
        }
    }

    /**
     * 导出评价
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function exportReappraises(Request $request){
        try {
            $keyword = $request->get('keyword');
            $role_id = $request->get('role');
            $start_time = $request->get('start_time');
            $end_time = $request->get('end_time');
            $reappraises = Reappraise::with('serviceRoleOrder.role:id,name','serviceRoleOrder.serviceUser:user_id,name,mobile','operateServiceUser:user_id,name,mobile')
                ->when($role_id,function($query) use ($role_id) {
                    $query->where('role_id',$role_id);
                })
                ->when($start_time,function($query) use ($start_time,$end_time) {
                    $query->whereBetween('created_at',[$start_time,$end_time]);
                })
                ->whereHas('serviceRoleOrder.serviceUser',function ($roleQuery) use ($keyword){
                    if(!empty($keyword)){
                        $roleQuery->where('name','like','%'.$keyword."%")->orWhere('mobile','like','%'.$keyword."%");
                    }
                })
                ->orderByDesc('id')
                ->get()->toArray();

            // 下载 Excel 文件
            return Excel::download(new ReappraiseExport($reappraises), 'Reappraises.xlsx');
        }catch (\Exception $e){
            Log::error('exportReappraises:'.$e->getMessage());
            return $this->failure('获取失败');
        }
    }
}
