<?php

namespace App\Http\Controllers\Miniprogram;

use App\Models\LogoutModel;
use App\Models\User\AuthKey;
use App\Models\User\Openid;
use App\Services\WeChat\AccessToken;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\User\UserModel;
use App\Models\FeedbackModel;
use PocketBE\MsyPush\Jobs\RegistEventJob;

class FeedbackController extends Controller
{
    //
    public function create(Request $request)
    {
        $this->validate($request, [
            'title' => '',
            'content' => 'required|max:200',
            'images' => 'array',
            'phone' => 'required',
            'device' => '',
            'be_uid' => '',
        ], [
            'content.max' => '内容最长200字',
        ]);

        $uid = Auth::auth();
        $user = UserModel::find($uid);
        // 添加搜索关键字
        $search = [];
        array_push($search, $request->phone);
        array_push($search, $user->nickname);
        array_push($search, $user->uid);
        array_push($search, $user->phone);
        $attribute = $request->all();
        $attribute['uid'] = $uid;
        $attribute['search'] = $search;

        ## 注销
        if (strpos($request->title, '注销') !== false) {
            // 申请注销未注册
            if (LogoutModel::where(['uid' => $uid, 'reply_at' => 0])->first()) {
                return response([
                    'code' => 409,
                    'message' => '已经申请注销,等待1-3个工作日处理'
                ]);
            }
            $logout = LogoutModel::create($attribute);
            try {
                $this->toAdminLogout($logout);
            } catch (\Exception $e) {
            }
        } else {
            $feedback = FeedbackModel::create($attribute);
            try {
                $this->toAdminFeedback($feedback);
            } catch (\Exception $e) {
            }
        }
        return response([
            'code' => 200,
            'message' => 'Success',
        ]);
    }


    private function toAdminFeedback(FeedbackModel $feedback)
    {
        $public_id = "gh_43ba50c16fba";
        $appId = 'wxadd11625f069258a';
        $admins = Openid::where("public_id", $public_id)
            ->whereIn("uid", [10001, 10002, 10007, 11111, 94302, 103143, 62726, 10288718])
            ->pluck("openid");
        $url = "https://m.fenpeiduixiang.com/fpdx-feedback/index.html?#/reply?id={$feedback->id}";
        foreach ($admins as $openid) {
            $payload = [
                'to_user' => [
                    $appId => $openid,
                ]
            ];
            dispatch(new RegistEventJob(10505, $payload))->onQueue("{push}");

            $data = [
                'first' => [
                    'value' => "【分配对象小程序】收到新的用户反馈！",
                    'color' => '#ff0000',
                ],
                'keyword1' => [
                    'value' => $feedback->title ?: "空",
                    'color' => '#000000',
                ],
                'keyword2' => [
                    'value' => date('Y年m月d日 H:i'),
                    'color' => '#000000',
                ],
                'remark' => [
                    'value' => $feedback->content,
                    'color' => '#2ba083',
                ],
            ];

            $access_token = (new AccessToken())->get($public_id);
            $api_url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={$access_token}";
            \Curl::to($api_url)->withData([
                'touser' => $openid,
                'template_id' => 'DhPjGWXQZqKd4ic9hSTccOOSm3AGHiYjM1ppb7td8Wo',
                'url' => $url,
                'data' => $data
            ])->asJsonRequest()->post();
        }
    }

    private function toAdminLogout(LogoutModel $logout)
    {
        $public_id = "gh_43ba50c16fba";
        $appId = 'wxadd11625f069258a';
        $admins = Openid::where("public_id", $public_id)
            ->whereIn("uid", [10001, 10002, 10007, 11111, 94302, 103143, 62726, 10288718])
            ->pluck("openid");
        foreach ($admins as $openid) {
            $payload = [
                'to_user' => [
                    $appId => $openid,
                ]
            ];
            dispatch(new RegistEventJob(10506, $payload))->onQueue("{push}");

            $data = [
                'first' => [
                    'value' => "【分配对象小程序】收到新的用户注销！",
                    'color' => '#ff0000',
                ],
                'keyword1' => [
                    'value' => $logout->title ?: "空",
                    'color' => '#000000',
                ],
                'keyword2' => [
                    'value' => date('Y年m月d日 H:i'),
                    'color' => '#000000',
                ],
                'remark' => [
                    'value' => $logout->content,
                    'color' => '#2ba083',
                ],
            ];
            $access_token = (new AccessToken())->get($public_id);
            $api_url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={$access_token}";
            \Curl::to($api_url)->withData([
                'touser' => $openid,
                'template_id' => 'DhPjGWXQZqKd4ic9hSTccOOSm3AGHiYjM1ppb7td8Wo',
                'data' => $data
            ])->asJsonRequest()->post();
        }
    }
}
