<?php
// +----------------------------------------------------------------------
// | A3Mall
// +----------------------------------------------------------------------
// | Copyright (c) 2020 http://www.a3-mall.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: xzncit <158373108@qq.com>
// +----------------------------------------------------------------------

namespace app\common\service\wechat;

use xzncit\core\message\Raw;
use xzncit\core\message\Text;
use app\common\model\wechat\WechatAccountReply as WechatAccountReplyModel;

/**
 * @package app\common\service\wechat
 * @class Message
 * @author xzncit 2024-01-30
 */
class Message {

    protected $receive = [];

    public function __construct($data){
        $this->receive = $data;
    }

    public function text(){
        return $this->keys("{$this->receive['content']}");
    }

    public function event(){
        switch(strtolower($this->receive['event'])) {
            case 'subscribe': // 用户关注
                if (isset($this->receive['eventkey']) && is_string($this->receive['eventkey'])) {
                    //扫描带参数二维码事件
                    if (($key = preg_replace('/^qrscene_/i', '', $this->receive['eventkey']))) {
                        return $this->keys("{$key}");
                    }
                }

                return $this->keys('subscribe', 2);
            case 'unsubscribe': // 取消关注事件
                return false;
            case 'click': // 关键字事件
                return $this->keys("{$this->receive['eventkey']}");
            case 'scancode_push': // 扫码推事件
            case 'scancode_waitmsg': // 扫码推事件且弹出“消息接收中”提示框
                if (empty($this->receive['scancodeinfo'])) return false;
                if (empty($this->receive['scancodeinfo']['scanresult'])) return false;
                return $this->keys("{$this->receive['scancodeinfo']['scanresult']}");
            case 'scan': // 用户已关注时的事件推送
                if (empty($this->receive['eventkey'])) return false;
                return $this->keys("{$this->receive['eventkey']}");
            default:
                return false;
        }
    }

    public function keys($rule,$type=3){
        $condition = [];
        if($type == 3){
            $condition[] = ["keyword","like",'%'.$rule.'%'];
            $condition[] = ["type","=",$type];
        }else if(in_array($type,[1,2])){
            $condition[] = ["type","=",$type];
        }
        $condition[] = ["status","=",1];
        $data = WechatAccountReplyModel::where($condition)->order("sort","DESC")->findOrEmpty()->toArray();
        if(empty($data)){
            $data = WechatAccountReplyModel::where(["type"=>1,"status"=>1])->order("sort","DESC")->findOrEmpty()->toArray();
        }

        if(empty($data)){
            return new Raw("您要查找内容不存在");
        }

        switch($data["content_type"]){
            case 1:
                return new Text($data['content']);
        }
    }

}