<?php
namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\AccountsInfo;
use App\Models\PrivateMail;
use GatewayWorker\Lib\Gateway;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class ComplaintController extends Controller
{

    //意见反馈列表
    public function opinionList()
    {
//        $data   = DB::connection('write')->table('QPAccountsDB.dbo.Message')
//                ->select('ID','GameID')
//                ->where('type',0)
//                ->orderBy('ID','asc')
//                ->get()->toArray();
//        $id_list = [];
//        foreach ($data as $key => $value) {
//            $id_list[$value->GameID] = $value->ID;
//        }
//        $ids = array_values($id_list);
        $adminChannels = session('admin_channels');
        $message = DB::connection('write')->table('QPAccountsDB.dbo.Message as m')
            ->leftJoin('QPAccountsDB.dbo.AccountsInfo as ai','m.GameID','=','ai.GameID')
            ->leftJoin('QPAccountsDB.dbo.Message as n','n.PID','=','m.ID')
            ->select('m.ID','m.GameID','ai.NickName','m.Msg','m.CreateAt','n.Msg as Reply','ai.UserID')
            ->where('m.type',0);
        if(count($adminChannels)<5)$message=$message->whereIn('ai.Channel', $adminChannels);
        $message=$message->whereRaw('m.CreateAt>CONVERT(varchar(10),DATEADD(DAY,-3,GETDATE()),120)')
//                ->whereIn('m.ID',$ids)
            ->orderBy('m.ID','desc')
            ->paginate(100);

//            ->paginate(10);
//            ->get();

        // 消息改已读
        DB::table('QPAccountsDB.dbo.Message')->update(['admin_read'=>1]);

//        $list = [];
//        foreach ($message as $key => $value) {
//            $list[$value->ID] = $value;
//        }
        return view('admin.complaint.opinion', ['list' => $message]);
    }

    //留言回复页面
    public function replyAddView(Request $request,$id)
    {
        $game_id = $request->input('game_id');
        $ids = DB::connection('write')->table('QPAccountsDB.dbo.Message')
                ->where('GameID',$id)
                ->pluck('ID')->toArray();
        $list = DB::connection('write')->table('QPAccountsDB.dbo.Message as m')
                ->leftJoin('QPAccountsDB.dbo.AccountsInfo as ai','m.GameID','=','ai.GameID')
                ->leftJoin('agent.dbo.admin_users as au','m.admin_id','=','au.id')
                ->select('m.ID','m.GameID',DB::Raw("IsNull(ai.NickName,'') as NickName"),'au.nickname as admin_nickname','m.Msg','m.CreateAt')
                ->whereIn('m.PID',$ids)
                ->orwhere('m.GameID',$id)
                ->get();
        return view('admin.complaint.message_list', ['list' => $list,'id'=>end($ids),'game_id' => $id]);
    }

    //留言回复
    public function replyAdd(Request $request,$id)
    {
        $admin_id = session('admin')->id;

        $insert['PID'] = $id;
        $message = $request->input('message');
        $gameId = $request->input('uid');
        $userId = AccountsInfo::GetUserID($gameId);
        if(empty($message)){
            return ['status'=>false,'msg'=>'请填写回复'];
        }
        $insert['Msg'] = $message;
        $insert['CreateAt'] = date('Y-m-d H:i:s');
        $insert['Type'] = 1;
        $insert['admin_id'] = $admin_id;

        $result = DB::table('QPAccountsDB.dbo.Message')
                ->insert($insert);
//        sendMail($MailType, $UserID, $TitleString, $TextString, $BonusString, $order_sn, $amount = 0, $type = 1, $flag = false)
//        PrivateMail::sendMail(8,$userId,'Resposta do atendimento ao cliente',$message,'','ser'.time().''.rand(100,999),0,9);
        PrivateMail::ReplyMessage($userId,$message);
        if($result){
            return $this->json(200, "发送成功");
        }else{
            return $this->json(500, '发送失败，请重试');
        }
    }

    //玩家举报查询
    public function accusationList(Request $request)
    {
        $plaintiff_uid   = (int)$request->input('plaintiff_uid');
        $defendant_uid   = (int)$request->input('defendant_uid');
        $game            = $request->input('game');//举报位置
        $content         = $request->input('content');//举报内容
        $status          = $request->input('status');//状态
        $sort            = $request->input('sort');
        $game_name       = DB::connection('write')->table('QPPlatformDB.dbo.GameRoomInfo')->pluck('ServerName');//单选框数据
        $where           = [['del','=',1]];
        !empty($plaintiff_uid) ? $where[] = ['plaintiff_uid','=',trim($plaintiff_uid," ")] : $plaintiff_uid = '';
        !empty($defendant_uid) ? $where[] = ['defendant_uid','=',trim($defendant_uid," ")] : $defendant_uid = '';
        !empty($game) ? $where[] = ['ServerName','=',$game]: '';
        !empty($content) ? $where[] = ['content','like','%'.$content.'%']: '';
        isset($status) ? $where[] = ['status','=',$status] : '';
        $query = DB::connection('write')->table('QPAccountsDB.dbo.AccountAccusation as aa')
                ->leftjoin('QPPlatformDB.dbo.GameRoomInfo as ri','aa.game_id','=','ri.ServerID')
                ->select(DB::raw('aa.id,aa.plaintiff_uid,aa.plaintiff_name,aa.defendant_uid,aa.defendant_name,aa.game_id,ri.ServerName,CONVERT(varchar(100),aa.time,20) as time,aa.content,aa.executant_id,aa.executant_name,CONVERT(varchar(100),aa.update_time,20) as update_time,aa.status'))
                ->where($where)
                ->orderBy('id','desc');

        /*排序*/
        if(!empty($sort)){
            $accusation = $query->get();
            $data = DB::connection('write')->table('QPAccountsDB.dbo.AccountAccusation as aa')
                    ->leftjoin('QPPlatformDB.dbo.GameRoomInfo as ri','aa.game_id','=','ri.ServerID')
                    ->select('aa.defendant_uid',DB::raw('count(*) as num'))
                    ->where($where)
                    ->groupBy('defendant_uid')
                    ->orderBy('num','desc')
                    ->get();
            $arr = [];
            foreach ($data as $key => $value) {
                $arr[] = $value->defendant_uid;
            }
            $list = [];
            foreach ($arr as $key => $value) {
                foreach ($accusation as $k => $v) {
                    if($value == $v->defendant_uid){
                        $list[] = $v;
                    }
                }
            }
        }else{
            $list = $query->paginate(10);
        }
        foreach ($list as $key => $value) {
            if($value->status === null){
                $value->status = 0;
            }
        }
        return view('admin.complaint.accusation', ['list' => $list,'game_name'=>$game_name,'sort'=>$sort,'plaintiff_uid'=>$plaintiff_uid,'defendant_uid'=>$defendant_uid,'game'=>$game,'content'=>$content,'status'=>$status]);
    }

    //玩家举报删除
    public function accusationDel(Request $request,$id)
    {
        $result = '';
        $result = DB::table('QPAccountsDB.dbo.AccountAccusation')->where('id',$id)->update(['del'=>0]);
        if($result){
            return $this->json(200, "删除成功");
        }else{
            return $this->json(500, '删除失败，请重试');
        }
    }

    //玩家举报处理
    public function accusationEdit(Request $request,$id)
    {
        $admin = $request->session()->get('admin');//管理员信息
        $update_time = date('Y-m-d H:i:s');//处理时间
        $update_data = [
                    'executant_id' => $admin->id,
                    'executant_name' => $admin->account,
                    'update_time' => $update_time,
                    'status' =>1
            ];
        $result = '';
        $result  = DB::table('QPAccountsDB.dbo.AccountAccusation')->where('id',$id)->update($update_data);
        if($result){
            return $this->json(200, "处理成功");
        }else{
            return $this->json(500, '处理失败，请重试');
        }
    }



    //邮件回复
    public function sendEmail(Request $request,$id)
    {
        $params = $request->post();
        if(!isset($params['email'])){
            return $this->json(500, '发送失败，邮件内容不能为空');
        }
        $data['MailType'] = 2;
        $data['MailStatus'] = 1;
        $user_info = DB::connection('write')->table('QPAccountsDB.dbo.AccountsInfo')->where('GameID',$params['uid'])->first();
        if(!empty($user_info)){
            $data['UserID'] = $user_info->UserID;
        }else{
            return $this->json(500, "未查到对应用户");
        }
        $data['CreateTime'] = date('Y-m-d H:i:s',time());
        $data['TitleString'] = '意见反馈函';
        $data['TextString'] = $params['email'];
        $email_id = DB::table('QPAccountsDB.dbo.PrivateMail')->insertGetId($data);
        $result = DB::table('QPAccountsDB.dbo.AccountOpinion')->where('id',$id)->update(['email_id'=>$email_id]);
        if($result && $email_id){
            // Log::useDailyFiles(storage_path().'/logs/mailPub.log');
            // Log::info('发送人agent_id:'.Auth::user()->id.',收件人:'.$params['uid'].',发送内容:'.$params['email']);
            return $this->json(200, "发送成功");
        }else{
            return $this->json(500, '发送失败，请重试');
        }
    }




}
