<?php

namespace App\Http\Controllers;

use App\Exceptions\WeChatException;
use App\Http\Controllers\Core\User;
use App\Models\Daily\DailyPushModel;
use App\Models\Daily\SubscribeModel;
use App\Models\User\AuthKey;
use App\Models\User\Openid;
use App\Services\User\ProfileService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;
use Ixudra\Curl\Facades\Curl;

class WeChatController extends Controller
{
    //

    private $resource;


    public function server(Request $request)
    {

        if (isset($_GET['echostr'])) {
            return $_GET['echostr'];
        } else {
            $xml = file_get_contents('php://input');
            $this->resource = xml2array($xml);

            try {
                switch ($this->resource['MsgType']) {
                    case 'text':
                        return $this->text();
                        break;
                    case 'image':
                        return $this->image();
                        break;
                    case 'voice':
                        return $this->voice();
                        break;
                    case 'video':
                        return $this->video();
                        break;
                    case 'shortvideo':
                        return $this->shortVideo();
                        break;
                    case 'event':
                        switch ($this->resource['Event']) {
                            case 'subscribe':
                                return $this->subscribe();
                                break;
                            case 'unsubscribe':
                                return $this->unSubscribe();
                                break;
                            case 'SCAN':
                                return $this->scan();
                                break;
                            case "CLICK":
                                return $this->click();
                        }
                        break;
                }
            } catch (\Exception $e) {
                throw new WeChatException();
            }
        }
    }


    private function text()
    {
        $resource = $this->resource;
        switch ($this->resource['Content']) {
            case "开启每日推送":
                SubscribeModel::updateOrCreate(
                    ['openid' => $resource['FromUserName'], 'public_id' => $resource['ToUserName']],
                    ['subscribe' => 1]
                );
                $resource['Content'] = "已成功开启「时遇记」每日推送\n\n每晚 10:00 不见不散\n时光微妙，遇见你真好~\n\n如需关闭请回复“关闭每日推送”";
                return $this->returnText($resource);
                break;
            case "关闭每日推送":
                $resource = $this->resource;
                $resource['Content'] = "正在关闭「每日推送」消息提醒\n\n关闭后，你将无法收到小遇文章推送，每晚10:00小遇就不能陪你啦~\n\n确认关闭，请<a href='weixin://bizmsgmenu?msgmenucontent=确认关闭每日推送&msgmenuid=234234'>【点此】</a>~";
                return $this->returnText($resource);
                break;
            case '确认关闭每日推送':
                SubscribeModel::updateOrCreate(
                    ['openid' => $resource['FromUserName'], 'public_id' => $resource['ToUserName']],
                    ['subscribe' => 0]
                );
                $resource['Content'] = "已成功关闭「每日推送」\n\n每晚 10:00 ，小遇就不能准时给你报时啦~\n不过无论什么时候你想小遇了，或者说遇到什么心事了，随时记得来找小遇哦，小遇一直都在~\n\n<a href='weixin://bizmsgmenu?msgmenucontent=开启每日推送&msgmenuid=234234'>重新开启请【点此】</a>";
                return $this->returnText($resource);
                break;
            case '今日文章':
                $article = DailyPushModel::where('date', '<=', date('Y-m-d'))->orderBy('date', 'desc')->first();
                $content = $article->reply_content . "\n\n<a href='{$article->article_url}'>点此查看文章~</a>";
//                $page = "pages/starter/starter?launch_type=free&url=".urlencode("/pages/article-redirect/article-redirect?url=".urlencode($article->article_url));
//                $content = $article->reply_content."\n\n<a href='{$article->article_url}'  data-miniprogram-path='{$page}'  data-miniprogram-appid='wx4c1722a4055bd229'>点此查看文章~</a>";
                $resource['Content'] = $content;
                return $this->returnText($resource);
                break;
        }
    }


    private function image()
    {
    }


    private function voice()
    {
    }


    private function video()
    {
    }


    private function shortVideo()
    {
    }


    private function subscribe()
    {
        $resource = $this->resource;
        try {
            $openid = $resource['FromUserName'];
            $public_id = $resource['ToUserName'];
            $userinfo = \WeChat::Fans($public_id)->info($openid);
            $unionid = $userinfo['unionid'];
            $auth = AuthKey::where('auth_key', $unionid)->first();
            if (!collect($auth)->isEmpty()) {
                $uid = $auth->uid;
                $response = Curl::to("http://api.deep.fenpeiduixiang.com/api/analytic/check/new/scan?uid={$uid}")->asJsonResponse(false)->get();
                $isexsts = Redis::Sismember("log:bevip:page:tag", $uid);
                if ((isset($response->isScan) && 1 == $response->isScan) || $isexsts) {
                    $ps = new ProfileService();
                    $ps->beVip($uid, true);
                }
                AuthKey::updateOrCreate(
                    ['auth_key' => $openid, 'auth_type' => $public_id],
                    ['uid' => $uid, 'login_at' => time()]
                );
            }
        } catch (\Exception $exception) {
        }
        $articles = [
            [
                'Title' => '分配对象啦！让我们谈一场72小时的恋爱好吗？',
                'Description' => '点击查看活动详情，内含快捷报名通道',
                'PicUrl' => 'http://mmbiz.qpic.cn/mmbiz_png/8a2FAXRUa7wjyhEBiberqMn6cicHlc9OY1kOPC5XibibAKXEPeWdhpqp8RZRiawyXZ6Z2cXz2UFGlhGlyjakbibDYjIQ/0?wx_fmt=png',
                'Url' => 'https://mp.weixin.qq.com/s/8QRAKfxZgJ6LS1gKMRHqyw',
            ]
        ];
        return $this->returnNews($resource, $articles);
    }


    private function unSubscribe()
    {
        $resource = $this->resource;
        try {
            $openid = $resource['FromUserName'];
            Openid::where('openid', $openid)->update(['subscribe' => 0]);
            $openData = User::getUidByOpenid($openid);
            $profs = new ProfileService();
            $profs->beVip($openData['uid'], false);
        } catch (\Exception $exception) {
            throw new WeChatException();
        }
    }


    private function scan()
    {
    }


    private function click()
    {
        $resource = $this->resource;
        switch ($this->resource['EventKey']) {
            case 'menu_36850':
                SubscribeModel::updateOrCreate(
                    ['openid' => $resource['FromUserName'], 'public_id' => $resource['ToUserName']],
                    ['subscribe' => 1]
                );
                $resource['Content'] = "已成功开启「时遇记」每日推送\n\n每晚 10:00 不见不散\n时光微妙，遇见你真好~\n\n如需关闭请回复“关闭每日推送”";
                return $this->returnText($resource);
                break;
        }
    }


    /**
     * 发送文本消息
     * @param  object  $object
     * @return string
     */
    public function returnText($resuorce)
    {
        $template = '<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%d</CreateTime>
                    <MsgType><![CDATA[text]]></MsgType>
                    <Content><![CDATA[%s]]></Content>
					<FuncFlag>0</FuncFlag>
                    </xml>';
        return sprintf(
            $template,
            $resuorce['FromUserName'],
            $resuorce['ToUserName'],
            $resuorce['CreateTime'],
            $resuorce['Content']
        );
    }


    public function returnImage($resource)
    {
        $template = '<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%d</CreateTime>
                    <MsgType><![CDATA[image]]></MsgType>
                    <Image><MediaId><![CDATA[%s]]></MediaId></Image>
                    </xml>';
        return sprintf(
            $template,
            $resource['FromUserName'],
            $resource['ToUserName'],
            $resource['CreateTime'],
            $resource['MediaId']
        );
    }


    public function returnNews($resource, array $array)
    {
        $template = '<item>
                    <Title><![CDATA[%s]]></Title>
                    <Description><![CDATA[%s]]></Description>
                    <PicUrl><![CDATA[%s]]></PicUrl>
                    <Url><![CDATA[%s]]></Url>
                    </item>';
        $item = null;
        foreach ($array as $value) {
            $item .= sprintf($template, @$value['Title'], @$value['Description'], @$value['PicUrl'], @$value['Url']);
        }
        $template = '<xml>
                <ToUserName><![CDATA[%s]]></ToUserName>
                <FromUserName><![CDATA[%s]]></FromUserName>
                <CreateTime>%d</CreateTime>
                <MsgType><![CDATA[news]]></MsgType>
                <ArticleCount>%d</ArticleCount>
                <Articles>%s</Articles>
                </xml>';
        return sprintf(
            $template,
            $resource['FromUserName'],
            $resource['ToUserName'],
            $resource['CreateTime'],
            count($array),
            $item
        );
    }
}
