<?php

namespace App\Http\Controllers\Admin;

use App\Exceptions\AlertException;
use App\Http\Controllers\Miniprogram\Core;
use App\Models\Fpdx\ActivityModel;
use App\Models\Fpdx\PairModel;
use App\Models\User\UserModel;
use App\Models\LogoutModel;
use App\Models\PartnerModel;
use App\Models\User\AuthKey;
use App\Services\Auth\AuthKeyService;
use App\Services\Pair\PairService;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class LogoutController extends Controller
{


    /**
     * 列表
     * @param  Request  $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     */
    public function index(Request $request)
    {
        $stage_id = ActivityModel::where([
            ['signend_time', '<', time()],
            ['close_time', '>', time()]
        ])->value('stage_id');
        $page = $request->input('page', 1);
        $per_page = $request->input('per_page', 20);
        $build = LogoutModel::when($request->filled('reply'), function ($query) use ($request) {
            if ($request->reply) {
                return $query->where('reply_at', '>', 0);
            } else {
                return $query->where('reply_at', 0);
            }
        })->when($request->filled('uid'), function ($query) use ($request) {
            return $query->where('uid', $request->uid);
        })->when($request->get('logout') && $stage_id, function ($query) use ($stage_id) {
            return $query->whereNotIn(
                'uid',
                PairModel::where('stage_id', $stage_id)
                    ->where('state', '<', 600)
                    ->pluck('uid')
            );
        });
        $total = $build->count();
        $users = $build->orderBy(
            $request->input('sort_by', 'id'),
            $request->input('order', 'asc')
        )->offset(($page - 1) * $per_page)
            ->limit($per_page)
            ->get();
        $last_page = ceil($total / $per_page);
        foreach ($users as $user) {
            $user->user;
        }
        return response([
            'code' => 200,
            'message' => 'OK',
            'data' => $users,
            'meta' => [
                'current_page' => $page,
                'per_page' => $per_page,
                'last_page' => $last_page,
                'total' => $total,
            ]
        ]);
    }


    /**
     * 处理
     * @param  Request  $request
     * @param $id
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     */
    public function handle(Request $request, $id)
    {
        $this->validate($request, [
            'reply_content' => 'required|max:200',
        ], [
            'reply_content.required' => '请写回复内容',
            'reply_content.max' => '回复内容字数不得超出200字',
        ]);
        $logout = LogoutModel::find($id);
        if ($logout->reply_at > 0) {
            return response([
                'code' => 403,
                'message' => '已处理'
            ]);
        }
        $logout->reply_at = time();
        $logout->reply_content = $request->reply_content;

        $this->logout($logout->uid);
        $this->notice($logout);

        $logout->save();
        return response([
            'code' => 200,
            'message' => 'OK'
        ]);
    }


    /**
     * 忽略
     * @param $id
     * @return array|\Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     */
    public function ignore($id)
    {
        $logout = LogoutModel::find($id);
        if ($logout->reply_at > 0) {
            return response([
                'code' => 403,
                'message' => '已处理'
            ]);
        }
        $logout->reply_at = time();
        $logout->save();
        return response([
            "code" => 200,
            "message" => "OK"
        ]);
    }


    /**
     * 通知
     * @param $feedback
     * @return bool
     */
    public function notice($feedback)
    {
        $public_id = config('miniprogram.public_id');
        $template_id = "IFUqurIlP88yg1KJDSGI3zAA0oRSRLFaxgeZerTrbe4";
        $page = '';
        $data = array(
            'keyword1' => [
                'value' => $feedback->content,
            ],
            'keyword2' => [
                'value' => $feedback->created_at->format('Y-m-d H:i'),
            ],
            'keyword3' => [
                'value' => "已回复",
            ],
            'keyword4' => [
                'value' => $feedback->reply_content,
            ],
            'keyword5' => [
                'value' => "感谢你为我们提供宝贵的建议",
            ],
        );
        $core = new Core();
        $result = $core->miniTemplate($feedback->uid, $template_id, $public_id, $page, $data);
        return $result;
    }


    /**
     * 注销
     * @param $uid
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     * @throws AlertException
     * @throws \App\Exceptions\ApiException
     */
    public function logout($uid)
    {
        if (!AuthKey::where('uid', $uid)->first()) {
            throw new AlertException("账户已被注销或不存在", 410);
        }

        // 删除报名数据
        $pairService = new PairService();
        $pairService->deletePair($uid);

        // 注销用户
        $authService = new AuthKeyService();
        $authService->logout($uid);
        return true;
    }


    /**
     * 管理员帮用户申请注册（注销自己号时使用）
     * @param  Request  $request
     * @param $uid
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     */
    public function store(Request $request)
    {
        $this->validate($request, [
            'uid' => 'required|integer',
        ]);
        $uid = $request->uid;
        $attribute['uid'] = $uid;
        $attribute['phone'] = UserModel::where('uid', $uid)->value('phone');
        LogoutModel::create($attribute);
        return response([
            'code' => 200,
            'message' => 'OK'
        ]);
    }
}
