<?php

namespace App\Http\Controllers\Admin;

use App\Events\OperationLoggedEvent;
use App\Exports\QuotaExport;
use App\Exports\QuotaLogExport;
use App\Facades\HttpService;
use App\Http\Controllers\Controller;
use App\Http\Response\ResponseJson;
use App\Models\AgentUser;
use App\Models\Collaborator;
use App\Models\Office;
use App\Models\Quota;
use App\Models\QuotaLog;
use App\Models\Station;
use App\Models\StationLog;
use App\Models\User;
use App\Validators\CollaboratorValidator;
use Exception;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Maatwebsite\Excel\Facades\Excel;

class CollaboratorsController extends Controller
{
    use ResponseJson;

    protected CollaboratorValidator $validator;

    /**
     * @param CollaboratorValidator $validator
     */
    public function __construct(CollaboratorValidator $validator)
    {
        $this->validator = $validator;
    }

    /**
     * 合作商列表
     *
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function index(Request $request)
    {
        $keyword = $request->input('keyword');
        $status = $request->input('status',null);
        $page_size = $request->input('page_size',15);
        $type = $request->input('type');
        $no_page = $request->input('no_page');
        $query = Collaborator::query()
            ->when($status !== null,function ($query) use ($status) {
                $query->where('status',$status);
            })
            ->when(strlen($type) > 0,function ($query) use ($type) {
                $query->where('type',$type);
            })
            ->when($keyword,function ($query) use($keyword){
                $query->where("name", 'like', '%'.$keyword.'%')
                    ->orWhere('mobile', 'like', '%'.$keyword.'%');
            })
            ->orderByDesc('updated_at')
            ->orderByDesc('id');

            if($no_page){
                $collaborator = $query->get();
            }else{
                $collaborator = $query->paginate($page_size);
            }
            foreach ($collaborator as $item){
                $station = Station::where('user_id',$item->user_id)->first();
                $item->office_name = '';
                $item->office_id = '';
                if($station){
                    $office = Office::where('id',$station->office_id)->first();
                    $item->office_name = $office->office_name;
                    $item->office_id = $office->office_id;
                }
            }

        return $this->success('ok', $collaborator);
    }

    public function detail($id)
    {
        try {
            $collaborator = Collaborator::query()->findOrFail($id);
            $station = Station::where('user_id',$collaborator->user_id)->first();
            if($station){
                $office = Office::where('id',$station->office_id)->first();
            }
            $collaborator->office_id = $office->id??'';
            $collaborator->office_name = $office->office_name??'';
            $collaborator->station_id = $station->id??'';
            $collaborator->station_number = $station->number??'';
            return $this->success('ok',$collaborator);
        }catch (ModelNotFoundException){
            return $this->jsonResponse(1,'合作商不存在');
        }
    }


    /**
     * 修改合作商信息
     *
     * @param Request $request
     * @param $id
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function update(Request $request, $id)
    {
        DB::beginTransaction();
        try {
            //绑定工位
            $office_id = $request->get('office_id');
            if(!$office_id){
                return $this->failure('请选择房间');
            }
            $data = $request->only(['avatar','name','mobile','intro','specialty','bio','protocols','diploma','type','id_card','agreement_number']);

            $collaborator = Collaborator::query()->findOrFail($id);

            if ($data['mobile'] && $data['mobile'] != $collaborator->mobile) {
                $exist = Collaborator::where('mobile', $data['mobile'])->whereNot('id', $collaborator->id)->exists();
                if ($exist)throw new Exception("手机号存在账号");
            }

            $collaborator->update($data);

            //查看用户是否有工位
            $user_station = Station::where('user_id',$collaborator->user_id)->first();
            $station_id = $request->get('station_id');
            if(!empty($user_station)){
                $user_station->office_id = $office_id;
                if(!$station_id){
                    //插入解绑记录
                    $log_unbind_map = [];
                    $log_unbind_map['station_id'] = $user_station->id;
                    $log_unbind_map['user_id'] = $collaborator->user_id;
                    $log_unbind_map['type'] = StationLog::TYPE_UNBIND;
                    $log_unbind_map['remark'] = '用户id:'.$collaborator->user_id.'解绑了工位:'.$user_station->number;
                    StationLog::create($log_unbind_map);

                    $user_station->number =  Station::NO_FIXED_STATION;
                    $user_station->save();

                    //插入绑定记录
                    $log_map = [];
                    $log_map['station_id'] = $user_station->id;
                    $log_map['user_id'] = $collaborator->user_id;
                    $log_map['type'] = StationLog::TYPE_BIND;
                    $log_map['remark'] = '用户id:'.$collaborator->user_id.'绑定了工位:'.Station::NO_FIXED_STATION;
                    StationLog::create($log_map);
                }else{
                    $station = Station::where('id',$station_id)->first();
                    if($station->user_id != $collaborator->user_id){
                        return $this->failure('该工位已绑定用户');
                    }
//                    $user_station->user_id =  null;
//                    $user_station->save();
                    $log_unbind_map = [];
                    $log_unbind_map['station_id'] = $user_station->id;
                    $log_unbind_map['user_id'] = $collaborator->user_id;
                    $log_unbind_map['type'] = StationLog::TYPE_UNBIND;
                    $log_unbind_map['remark'] = '用户id:'.$collaborator->user_id.'解绑了工位:'.$user_station->number;
                    StationLog::create($log_unbind_map);

                    $station->user_id =  $collaborator->user_id;
                    $station->save();

                    $log_map = [];
                    $log_map['station_id'] = $user_station->id;
                    $log_map['user_id'] = $collaborator->user_id;
                    $log_map['type'] = StationLog::TYPE_BIND;
                    $log_map['remark'] = '用户id:'.$collaborator->user_id.'绑定了工位:'.$station->number;
                    StationLog::create($log_map);
                }
            }else{
                if(!$station_id){
                    $number = Station::NO_FIXED_STATION;
                    $model = Station::create(['office_id'=>$office_id,'number'=>$number,'user_id'=>$collaborator->user_id]);
                }else{
                    $model = Station::where('id',$station_id)->first();
                    if(!empty($model->user_id)){
                        return $this->failure('该工位已绑定用户');
                    }
                    $number = $model->number;
                    $model->office_id = $office_id;
                    $model->user_id = $collaborator->user_id;
                    $model->save();
                }
                $log_map = [];
                $log_map['station_id'] = $model->id;
                $log_map['user_id'] = $collaborator->user_id;
                $log_map['type'] = StationLog::TYPE_BIND;
                $log_map['remark'] = '用户id:'.$collaborator->user_id.'绑定了工位:'.$number;
                StationLog::create($log_map);
            }


            //操作记录
            OperationLoggedEvent::dispatch("修改了合作商:$id 的信息");

            DB::commit();
            return $this->success('ok');
        }catch (ModelNotFoundException){
            return $this->jsonResponse(1,'合作商记录不存在');
        }catch (Exception $e){
            DB::rollBack();
            return $this->jsonResponse(1,$e->getMessage());
        }
    }


    /**
     * 删除合作商
     *
     * @param $id
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function destroy($id)
    {
        try {
            $collaborator =  Collaborator::query()->findOrFail($id);
            $collaborator->delete();

            return $this->success('ok');
        }catch (ModelNotFoundException){
            return $this->jsonResponse(1,'合作商记录不存在');
        }catch (Exception $e){
            return $this->jsonResponse(1,$e->getMessage());
        }
    }


    /**
     * 合作商审核
     *
     * @param Request $request
     * @param $id
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function audit(Request $request, $id)
    {
        DB::beginTransaction();
        try {
            $data = $request->only(['status','reason','type']);

            $this->validator->scene('audit')->validate($data);

            $collaborator =  Collaborator::query()->findOrFail($id);
            $collaborator->update($data);
            //审核通过携带办公室id
            $office_id = $request->input('office_id');
            if(!empty($office_id)){
                Station::create(['office_id'=>$office_id,'user_id'=>$collaborator->user_id,'number'=>Station::NO_FIXED_STATION]);
            }
            //审核通过以后更新用户表,先查看是否存在
            if ($data['status'] == 1) {
                User::updateServerUser($collaborator->mobile,$collaborator->user_id);
            }
//            if($data['status'] == Collaborator::STATUS_PASS && $data['type'] == Collaborator::TYPE_FULL_TIME){
//                Station::create(['office_id'=>$office_id,'user_id'=>$collaborator->user_id,'number'=>Station::NO_FIXED_STATION]);
//            }


            //审核通过后加入服务用户表
//            if ($data['status'] == 1) {
//                //审核通过以后如果小程序有用户数据，则同步用户数据
//                $user_data = User::getMpUser($collaborator->mobile);
//                if($user_data){
//                    User::sameDataToUser($collaborator->user_id,$user_data->id);
//                }
//            }
            User::where('id', $collaborator->user_id)->update(['name'=>$collaborator->name, 'mobile'=>$collaborator->mobile]);
            //增加批发商
            if ($data['status'] == 1 && $data['type'] == Collaborator::TYPE_FULL_TIME) //员工
            {
                //Mia说合作商审核和批发商角色没有关系
//                AgentUser::changeLevel($collaborator->user_id, AgentUser::AgentStaff, "合作商员工审核", true);
            }
            DB::commit();
            return $this->success('ok');
        }catch (ModelNotFoundException){
            return $this->jsonResponse(1,'合作商记录不存在');
        }catch (Exception $e){
            DB::rollBack();
            return $this->jsonResponse(1,$e->getMessage());
        }
    }

    public function add(Request $request){
        DB::beginTransaction();
        try {
            //绑定工位
            $office_id = $request->get('office_id');
            if(!$office_id){
                return $this->failure('请选择房间');
            }
            $data = $request->only(['avatar','name','mobile','intro','specialty','bio','protocols','diploma','type','id_card','agreement_number']);
            $data['status'] = Collaborator::STATUS_PASS;
            $data['type'] = Collaborator::TYPE_USER;

            $exist = User::where('mobile',$data['mobile'])->exists();
            if ($exist) return $this->failure('手机号已被注册');

            $agreement_number = Collaborator::where('agreement_number', $data['agreement_number'])->exists();
            if ($agreement_number) return $this->failure('协议号已存在');

            $user_model = User::create(['name'=>$data['name'],'mobile'=>$data['mobile'],'avatar'=>$data['avatar']]);

            $station = Station::create(['office_id'=>$office_id,'number'=>Station::NO_FIXED_STATION,'user_id'=>$user_model->id]);

            StationLog::create(['station_id'=>$station->id,'user_id'=>$user_model->id,'type'=>StationLog::TYPE_BIND,'remark'=>'用户id:'.$user_model->id.'绑定了工位:'.Station::NO_FIXED_STATION]);

            $data['user_id'] = $user_model->id;
            Collaborator::create($data);

            DB::commit();
            return $this->success('ok');
        }catch (\Exception $e){
            DB::rollBack();
            return $this->failure($e->getMessage());
        }
    }

    public function addQuota(Request $request){
        try {
            $data = $request->only(['agency_id','collaborator_id','num','agreement_number']);
            $validated = Validator::make($data, [
                'collaborator_id' => 'required',
                'num' => 'required',
            ], [
                'collaborator_id.required' => '请选择人员',
                'num.required' => '请填写名额',
            ]);
            if ($validated->fails()) {
                $errors = $validated->errors()->all();
                $error = count($errors) ? $errors[0] : null;
                return $this->failure($error);
            }
            $agency_id = $data['agency_id']??'';

            $query = Quota::query();
            $query->when($agency_id,function ($query) use($agency_id){
                $query->where("agency_id", $agency_id);
            });
            $quota = $query->where('collaborator_id',$data['collaborator_id'])->where('agreement_number',$data['agreement_number'])->first();

            $admin = auth()->user();
            if($quota){
                $quota->num = $quota->num+$data['num'];
                $quota->operate_user_id = $admin->id;
                $quota->operate_user_name = $admin->name;
                $quota->save();
            }else{
                $data['operate_user_id'] = $admin->id;
                $data['operate_user_name'] = $admin->name;
                Quota::create($data);
            }
            return $this->success('ok');
        }catch (\Exception $e){
            Log::error('addAgreement:'.$e->getMessage());
            return $this->failure($e->getMessage());
        }
    }

    public function getQuotaList(Request $request){
        try {
            $keyword = $request->input('keyword');
            $is_export = $request->input('is_export');
            $no_page = $request->input('no_page');
            if($is_export){
                $no_page = true;
            }
            $id = $request->input('id');

            $query = Quota::query()->with('collaboratorInfo','agencyInfo');

            $query->when($keyword,function ($query) use ($keyword){
//                $query->where('agreement_number','like',"%{$keyword}%");
//                $query->whereHas('collaboratorInfo',function ($query) use ($keyword) {
//                    $query->where('name','like',"%{$keyword}%")->orWhere('mobile','like',"%{$keyword}%");
//                });
                $query->where(function ($query) use ($keyword) {
                    $query->where('agreement_number', 'like', "%{$keyword}%")
                        ->orWhereHas('collaboratorInfo', function ($query) use ($keyword) {
                            $query->where('name', 'like', "%{$keyword}%")
                                ->orWhere('mobile', 'like', "%{$keyword}%");
                        });
                });
            });

            $query->when($id,function ($query) use ($id){
                $query->where('collaborator_id',$id);
            });

            $query->orderByDesc('id');
            if($no_page){
                $list = $query->get();
            }else{
                $list = $query->paginate();
            }
            if($is_export){
                return Excel::download(new QuotaExport($list), '名额.xlsx');
            }
            return $this->success('ok',$list);
        }catch (\Exception $e){
            Log::error('getQuotaList:'.$e->getMessage());
            return $this->failure($e->getMessage());
        }
    }

    public function getQuotaLogList(Request $request,$id){
        try {
            $keyword = $request->input('keyword');
            $is_export = $request->input('is_export');

            $query = QuotaLog::query()->with('orderInfo');

            $query->when($keyword,function ($query) use ($keyword) {
                $query->whereHas('orderInfo',function ($query) use ($keyword) {
                    $query->where('name','like',"%{$keyword}%");
                });
            });

            $query->when($id,function ($query) use ($id){
                $query->where('quota_id',$id);
            });

            $query->orderByDesc('id');

            if($is_export){
                $list = $query->get();
            }else{
                $list = $query->paginate();
            }

            if($is_export){
                return Excel::download(new QuotaLogExport($list), '名额使用记录.xlsx');
            }
            return $this->success('ok',$list);
        }catch (\Exception $e){
            Log::error('getQuotaList:'.$e->getMessage());
            return $this->failure($e->getMessage());
        }
    }

    public function updateQuota(Request $request,$id,Quota $quota){
        try {
            $data = $request->only(['agency_id','collaborator_id','num','agreement_number']);
            $quota_info = $quota->find($id);
            $quota_info->update($data);
            if(!empty($data['num']) && ($data['num'] != $quota_info->num)){
                $admin = auth()->user();
                QuotaLog::addQuotaLog($admin,0,$data['num'],$quota_info->id);
            }
            return $this->success('ok');
        }catch (\Exception $e){
            Log::error('updateQuota:'.$e->getMessage());
            return $this->failure($e->getMessage());
        }
    }

    public function delQuota($id,Quota $quota){
        try {
            $quota->where('id',$id)->delete();
            return $this->success('ok');
        }catch (\Exception $e){
            Log::error('delQuota:'.$e->getMessage());
            return $this->failure($e->getMessage());
        }
    }
}
