<?php
/**
 * 系统模板消息
 * Created by PhpStorm.
 * User: phperstar
 * Date: 2021/05/07
 * Time: 15:22
 */

namespace JinDouYun\Model\System;

use Mall\Framework\Core\ErrorCode;
use Mall\Framework\Core\ResultWrapper;
use Mall\Framework\Core\StatusCode;

use JinDouYun\Cache\SystemCache;

use JinDouYun\Dao\System\DSystemPushMessage;
use JinDouYun\Dao\System\DSystemPushMessageSetting;

use Util\WeiXin\Miniprogram;
use Util\WeiXin\Offiaccount;


class MSystemPushMessage
{
    private $objDSystemPushMessage;

    private $onlineUserId;

    private $onlineEnterpriseId;

    public function __construct($onlineUserId, $enterpriseId)
    {
        $this->onlineUserId = $onlineUserId;
        $this->onlineEnterpriseId = $enterpriseId;

        $this->objDSystemPushMessage = new DSystemPushMessage('default');
    }

    /**
     * 添加系统模版
     * @param $params
     * @return ResultWrapper
     */
    public function add($params)
    {
        $dbResult = $this->objDSystemPushMessage->insert($params);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDSystemPushMessage->error(), ErrorCode::$dberror);
        }
        return ResultWrapper::success($dbResult);
    }

    /**
     * 推送渠道启用/停用
     */
    public function updatePushEnableStatus($params)
    {
        $objDSystemPushMessageSetting = new DSystemPushMessageSetting();
        $id = $params['id'];
        unset($params['id']);

        $dbResult = $objDSystemPushMessageSetting->update($params, $id);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDSystemPushMessage->error(), ErrorCode::$dberror);
        }
        return ResultWrapper::success($dbResult);
    }

    /**
     * 推送消息启用/停用
     * @param $params
     * @return ResultWrapper
     */
    public function updateEnableStatus($params)
    {
        $objDSystemPushMessageSetting = new DSystemPushMessageSetting();

        $settingData = $objDSystemPushMessageSetting->get(['enterpriseId'=>$this->onlineEnterpriseId,'messageId'=>$params['id']]);
        if ($settingData === false) {
            return ResultWrapper::fail($this->$objDSystemPushMessageSetting->error(), ErrorCode::$dberror);
        }

        // 设置表如果为空,新增一条设置项
        if( empty($settingData) ){
            $settingData = [
                'messageId' => $params['id'],
                'enterpriseId' => $this->onlineEnterpriseId,
                'enabledStatus' => StatusCode::$standard,
                'createTime'    => time(),
            ];
            $dbResult = $objDSystemPushMessageSetting->insert($settingData);
        }else{
            $conditon = [
                'messageId'=>$params['id'],
                'enterpriseId' => $this->onlineEnterpriseId,
            ];
            $dbResult = $objDSystemPushMessageSetting->update(['enabledStatus'=>$params['enabledStatus']], $conditon);
        }
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDSystemPushMessage->error(), ErrorCode::$dberror);
        }
        return ResultWrapper::success($dbResult);
    }

    /**
     * 获取系统内置推送消息模板列表
     * @param $selectParams
     * @return ResultWrapper
     */
    public function getAll($selectParams)
    {
        $limit = $selectParams['limit'];
        unset($selectParams['limit']);
        $offset = $selectParams['offset'];
        unset($selectParams['offset']);

        $where = ' where m.deleteStatus = '.StatusCode::$standard;

        // 消息类型
        if( isset($selectParams['type']) && !empty($selectParams['type']) ){
            $where .= ' and m.type = '.$selectParams['type'];
        }

        // 关键字
        if( isset($selectParams['keyword']) && !empty($selectParams['keyword']) ){
            $where .= ' and m.name like "%'.$selectParams['keyword'].'%"';
        }

        // 启用状态
        if( isset($selectParams['enabledStatus']) && !empty($selectParams['enabledStatus']) ){
            $where .= ' and a.enabledStatus = '.$selectParams['enabledStatus'];
        }

        $basesql = 'from qianniao_system_push_message m LEFT JOIN (select enabledStatus,messageId,weixinEnabledStatus,smsEnabledStatus,id from qianniao_system_push_message_setting where enterpriseId = '.$this->onlineEnterpriseId.') a on m.id = a.messageId';

        $sql = 'select m.id,m.name,IFNULL(a.enabledStatus, 4) as enabledStatus,a.weixinEnabledStatus,a.smsEnabledStatus,a.id as settingId '.$basesql.$where.' order by id desc limit '.$offset.','.$limit;
        $dbResult = $this->objDSystemPushMessage->query($sql);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDSystemPushMessage->error(), ErrorCode::$dberror);
        }

        $sql = 'select count(*) as total '.$basesql.$where;
        $total = $this->objDSystemPushMessage->query($sql);

        $return = [
            'data'  => $dbResult,
            'total' => ($total) ? intval($total[0]['total']) : 0,
        ];
        return ResultWrapper::success($return);
    }

    /**
     * 配置详情
     */
    public function settingDetail($id)
    {
        $objDSystemPushMessageSetting = new DSystemPushMessageSetting();

        $sql = 'select s.*,m.weixinTemplate,m.name,m.tid,m.kidList from qianniao_system_push_message_setting s left join qianniao_system_push_message m on m.id = s.messageId where s.id = '.$id;
        $settingData = $objDSystemPushMessageSetting->query($sql);
        if ($settingData === false) {
            return ResultWrapper::fail($this->$objDSystemPushMessageSetting->error(), ErrorCode::$dberror);
        }

        if(empty($settingData)){
            return ResultWrapper::success([]);
        }

        return ResultWrapper::success($settingData);
    }

    /**
     * 获取对应推送模板的推送信息
     */
    public function getSettingDataByMessageIds($selectParams)
    {
        $objDSystemPushMessageSetting = new DSystemPushMessageSetting();

        $sql = 'select s.*,m.weixinTemplate,m.name from qianniao_system_push_message_setting s left join qianniao_system_push_message m on m.id = s.messageId where s.messageId in('.implode(',', $selectParams['id']).') and s.enterpriseId = '.$this->onlineEnterpriseId.' and s.weixinEnabledStatus = '.StatusCode::$standard.' and s.enabledStatus ='.StatusCode::$standard;
        $settingData = $objDSystemPushMessageSetting->query($sql);
        if ($settingData === false) {
            return ResultWrapper::fail($objDSystemPushMessageSetting->error(), ErrorCode::$dberror);
        }

        if(empty($settingData)){
            return ResultWrapper::success([]);
        }

        return ResultWrapper::success($settingData);
    }

    /**
     * 编辑推送设置表
     * @param $params
     * @return ResultWrapper
     */
    public function edit($params)
    {
        $id = $params['id'];
        unset($params['id']);
        $objDSystemPushMessageSetting = new DSystemPushMessageSetting();
        $dbResult = $objDSystemPushMessageSetting->update($params, $id);
        if ($dbResult === false) {
            return ResultWrapper::fail($objDSystemPushMessageSetting->error(), ErrorCode::$dberror);
        }
        return ResultWrapper::success($dbResult);
    }

    /**
     * 删除系统模版
     * @param $ids
     * @return ResultWrapper
     */
    public function del($ids)
    {
        $dbResult = $this->objDSystemPushMessage->update(['deleteStatus' => StatusCode::$delete],$ids);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDSystemPushMessage->error(), ErrorCode::$dberror);
        }
        return ResultWrapper::success($dbResult);
    }

    /**
     * 自动创建微信模板消息
     */
    public function autoCreateWeiXinTemplateId($id)
    {
        $objDSystemPushMessageSetting = new DSystemPushMessageSetting();

        // 1.获取模板信息
        $pushMessageData = self::settingDetail($id);
        if(!$pushMessageData->isSuccess()){
            return ResultWrapper::fail($pushMessageData->getData(), $pushMessageData->getErrorCode());
        }
        $pushMessageData = $pushMessageData->getData();
        if(empty($pushMessageData)){
            return ResultWrapper::fail('小程序内置模板的数据为空', ErrorCode::$contentNotExists);
        }
        $pushMessageData = array_pop($pushMessageData);

        // 2.获取当前登录企业的小程序配置
        $objSystemCache = new SystemCache();
        $miniprogramSetting = $objSystemCache->getAppIdByEnterpriseId($this->onlineEnterpriseId);
        if (empty($miniprogramSetting)) {
            return ResultWrapper::fail('后台小程序配置项为空', ErrorCode::$configEroor);
        }
        $miniprogramSetting = json_decode($miniprogramSetting, true);//获取小程序appid

        // 3.获取access_token
        $objOffiaccount = new Offiaccount($miniprogramSetting['appid'], $miniprogramSetting['APPscrect']);
        $result = $objOffiaccount->token();
        if (!$result->isSuccess()) {
            return ResultWrapper::fail($result->getData(), $result->getErrorCode());
        }
        $access_token = $result->getData();

        // 4.创建模板id
        $objMiniprogram = new Miniprogram($miniprogramSetting['appid'], $miniprogramSetting['APPscrect']);
        $pushMessageData['kidList'] = json_decode($pushMessageData['kidList'], true);

        $result = $objMiniprogram->addtemplate($access_token, $pushMessageData['tid'],  $pushMessageData['kidList'], $pushMessageData['name']);
        if(!$result->isSuccess()){
            return ResultWrapper::fail($result->getData(), $result->getErrorCode());
        }

        // 5.修改设置表中的模板id字段值
        $update = [
            'weixinTemplateId' => $result->getData(),
            'updateTime'       => time(),
        ];
        $dbResult = $objDSystemPushMessageSetting->update($update, ['id' => $pushMessageData['id']]);
        if($dbResult === false){
            return ResultWrapper::fail($objDSystemPushMessageSetting->error(), ErrorCode::$dberror);
        }

        return ResultWrapper::success($update['weixinTemplateId']);
    }

    /**
     * 发送订阅消息
     * @param $templateMessageId
     * @param $openId
     * @param $data
     * @return ResultWrapper
     */
    public function sendWeiXinPushMessage($pushMessageId, $openId, $data, $page = '/pages/index/index')
    {
        // 1.获取当前登录企业的小程序配置
        $objSystemCache = new SystemCache();
        $miniprogramSetting = $objSystemCache->getAppIdByEnterpriseId($this->onlineEnterpriseId);
        if (empty($miniprogramSetting)) {
            return ResultWrapper::fail('后台小程序配置项为空', ErrorCode::$configEroor);
        }
        $miniprogramSetting = json_decode($miniprogramSetting, true);//获取小程序appid

        // 2.获取access_token
        $objOffiaccount = new Offiaccount($miniprogramSetting['appid'], $miniprogramSetting['APPscrect']);
        $result = $objOffiaccount->token();
        if (!$result->isSuccess()) {
            return ResultWrapper::fail($result->getData(), $result->getErrorCode());
        }
        $access_token = $result->getData();

        // 3.查询对应模板id
        $pushMessageSettingData = self::getSettingDataByMessageIds(['id'=>[$pushMessageId]]);
        if(!$pushMessageSettingData->isSuccess()){
            return ResultWrapper::fail($pushMessageSettingData->getData(), $pushMessageSettingData->getErrorCode());
        }
        $pushMessageSettingData = $pushMessageSettingData->getData();
        if(empty($pushMessageSettingData)){
            return ResultWrapper::fail('未查询到对应的推销小程序模板设置数据', ErrorCode::$configEroor);
        }
        $pushMessageSettingData = array_pop($pushMessageSettingData);

        if($pushMessageSettingData['enabledStatus'] == StatusCode::$delete){
            return ResultWrapper::fail('推送消息未启用,不推送', ErrorCode::$notAllowAccess);
        }

        $objMiniprogram = new Miniprogram($miniprogramSetting['appid'], $miniprogramSetting['APPscrect']);
        $result = $objMiniprogram->subscribeMessageSend($access_token, $pushMessageSettingData['weixinTemplateId'], $openId, $page, $data);
        if(!$result->isSuccess()){
            return ResultWrapper::fail('发送订阅消息报错:'.$result->getData(), $result->getErrorCode());
        }
        return ResultWrapper::success('订阅消息发送成功');
    }

}



