<?php

namespace App\Http\Controllers\Admin;

use App\Models\User;
use App\Models\Lang;
use App\Models\Message;
use Illuminate\Http\Request;

class MessageController extends AdminController
{
    /**
     * Display a listing of the resource.
     *
     * @param Request $request
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $where    = $request->except('page');
        $messages = Message::with(['product.description', 'langs', 'user']);
        $messages = $request->has('lang') ? $messages->where('lang', $where['lang']) : $messages;
        $messages = $request->has('name') ? $messages->where('name', 'like', "%{$where['name']}%") : $messages;
        $messages = $request->has('valid') ? $messages->where('valid', $where['valid']) : $messages;

        if (auth()->user()->is_team) {
            if (auth()->user()->is_manager) {
                $messages = $request->has('is_my') && $request->input('is_my') ? $messages->where('user_id', auth()->user()->id) : $messages;
            } else {
                $messages = $messages->where('user_id', auth()->user()->id);
            }
        }

        $messages = $messages->latest()->paginate(20);
        $langs = Lang::where('buy', 1)->where('enabled', 1)->oldest('orders')->lists('name', 'slug')->toArray();
        $user = auth()->user();

        return view('admin.message.messages', compact('messages', 'where', 'langs', 'user'));
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $data = Message::with('product.description')->find($id);

        return view('admin.message.messages_show', compact('data'));
    }

    /**
     * Display the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function allocation($id)
    {
        $data = Message::with('product.description')->find($id);
        $users = User::where('is_team', 1)->where('status', 1)->get()->pluck('name', 'id' )->all();

        return view('admin.message.allocation', compact('data', 'users'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $result = Message::find($id)->update($request->all());

        if ($result) {
            event(new \App\Events\MessageReplyEvent(Message::find($id)));
            return redirect('admin/message')->with('success', '回复成功');
        }

        return back()->withInput()->with('error', '回复失败');
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function updateAllocation(Request $request, $id)
    {
        $isTransfer = $request->input('is_transfer');
        $message = Message::find($id);
        $result = $message->update($request->except('is_transfer'));

        if ($result) {
            if ($isTransfer) {
                $query = Message::where('id', '<>', $id);

                if ($message->phone && $message->email) {
                    $query->where(function ($query) use ($message) {
                        $query->where('email', $message->email)->orWhere('phone', $message->phone);
                    });
                } elseif ($message->phone && !$message->email) {
                    $query->where('phone', $message->phone);
                } elseif (!$message->phone && $message->email) {
                    $query->where('email', $message->email);
                }

                $query->update(['user_id' => $request->input('user_id')]);
            }

            event(new \App\Events\MessageAllocationEvent(Message::with('user')->where('id', $id)->first()));

            return redirect('admin/message')->with('success', '分配成功');
        }

        return back()->withInput()->with('error', '分配失败');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $ids    = array_str($id);
        $result = Message::whereIn('id', $ids)->delete();

        if ($result) {
            flash('success', '留言删除成功！');
            return response()->json(['code' => 200]);
        }

        return response()->json(['code' => 500]);
    }

    //flag异部更新
    public function flag(Request $request, $id)
    {
        $action = $request->action;

        if($action == "flagclose"){
            $data['flag'] = 0;
            Message::find($id)->fill($data)->save();
        }else{
            $data['flag'] = 1;
            Message::find($id)->fill($data)->save();
        }
    }

    //isread异部更新
    public function isread(Request $request, $id)
    {
        $action = $request->action;

        if ($action == "isreadclose") {
            $data['isread'] = 0;
            Message::find($id)->fill($data)->save();
        } else {
            $data['isread'] = 1;
            Message::find($id)->fill($data)->save();
        }
    }

    public function export(Request $request)
    {
        $query = Message::with(['product.description', 'langs']);

        if (auth()->user()->is_team) {
            if (auth()->user()->is_manager) {
                $query = $request->has('is_my') && $request->input('is_my') ? $query->where('user_id', auth()->user()->id) : $query;
            } else {
                $query = $query->where('user_id', auth()->user()->id);
            }
        }

        $temp = $query->get();
        $data = array (
            ['发件人', '电话', '邮箱', '咨询产品', '来源', '地址', 'IP', '内容', '回复']
        );

        if (!$temp->isEmpty()) {
            foreach ($temp as $value) {
                $data[] = [
                    $value->name,
                    $value->phone,
                    $value->email,
                    $value->product ? $value->product->description->title : '无',
                    $value->langs->name,
                    $value->address,
                    $value->ip,
                    $value->content,
                    $value->reply
                ];
            }
        }
        return \Excel::create('询盘列表', function($excel) use ($data) {
            $excel->sheet('导出询盘列表', function($sheet) use ($data) {
                $sheet->setHeight(1, 30);
                $sheet->setWidth(array(
                    'A' => 20,
                    'B' => 20,
                    'C' => 25,
                    'D' => 30,
                    'E' => 10,
                    'F' => 30,
                    'G' => 20,
                    'H' => 50,
                    'I' => 50,
                ));
                $sheet->row(1, function($row) {
                    $row->setValignment('center');
                    $row->setAlignment('center');
                    $row->setFontWeight('bold');
                    $row->setBackground('#dddddd');
                });
                $sheet->setVerticalCentered(true);
                $sheet->setHorizontalCentered(true);
                $sheet->fromArray($data, null, 'A1', false, false);
            });
        })->export('xls');
    }

    public function translate(Request $request)
    {
        try {
            $client = new \GuzzleHttp\Client();
            $res = $client->request('POST', 'https://translation.googleapis.com/language/translate/v2', [
                'form_params' => [
                    'q' => $request->input('q'),
                    'target' => 'zh',
                    'source' => $request->input('source'),
                    'key' => 'AIzaSyDVgcXzt51m5VvwbRFRhR02NJnuZ2iXOVk'
                ]
            ]);

            if ($res->getStatusCode() == 200) {
                $contents = json_decode($res->getBody()->getContents(), true);
                return response()->json(['code' => 200, 'message' => $contents['data']['translations'][0]['translatedText']]);
            }

        } catch (\Exception $e) {
            return response()->json(['code' => 500, 'message' => $e->getMessage()]);
        }

    }

}
