<?php
/**
 * 系统设置Model
 * Created by PhpStorm.
 * User: 小威
 * Date: 2019/11/28
 * Time: 16:00
 */

namespace JinDouYun\Model\SystemSettings;

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

use JinDouYun\Cache\SystemCache;

use JinDouYun\Model\Oem\MOem;

use JinDouYun\Dao\SystemSettings\DSystem;
use JinDouYun\Dao\SystemSettings\DWxBindEnterprise;

use Util\WeiXin\Oplatform;

class MSystem
{

    // 授权回调地址
    private $redirect_uri = 'http://'.DOMAIN_WWW.'/AuthorizePage';
    private $objDSystem;
    private $userCenterId;
    private $enterpriseId;
    private $objDWxBindEnterprise;

    public function __construct($enterpriseId, $userCenterId = false)
    {
        $this->enterpriseId = $enterpriseId;
        $this->userCenterId = $userCenterId;
        $this->objDSystem = new DSystem('default');
        $this->objDWxBindEnterprise = new DWxBindEnterprise('default');
    }

    /**
     * type = 1
     * 修改系统设置
     * @param $params
     * @param $wxOriginId
     * @return ResultWrapper
     */
    public function updateSystemSettings($params, $wxOriginId)
    {
        $this->objDSystem->beginTransaction();
        if (isset($params['id']) && !empty($params['id'])) {
            $dbData = $this->objDSystem->get(['id' => $params['id']]);
            if ($dbData === false) {
                return ResultWrapper::fail($this->objDSystem->error(), ErrorCode::$dberror);
            }
            if (empty($dbData)) return ResultWrapper::fail('查询数据为空', ErrorCode::$dberror);
            $params['createTime'] = $dbData['createTime'];
        }

        $dbResult = $this->objDWxBindEnterprise->replace(['enterpriseId' => $this->enterpriseId, 'wxOriginId' => $wxOriginId]);
        if ($dbResult === false) {
            $this->objDSystem->rollBack();
            return ResultWrapper::fail($this->objDWxBindEnterprise->error(), ErrorCode::$dberror);
        }

        $dbResult = $this->objDSystem->replace($params);
        if ($dbResult === false) {
            $this->objDSystem->rollBack();
            return ResultWrapper::fail($this->objDSystem->error(), ErrorCode::$dberror);
        }

        $this->objDSystem->commit();
        $objSystemCache = new SystemCache();
        $objSystemCache->cacheEnterpriseRelationWxAppId($params['content'], $this->enterpriseId);
        return ResultWrapper::success($dbResult);
    }

    /**
     * 系统设置详情
     * @param $params
     * @return ResultWrapper
     */
    public function getSystemSettingsInfo($params)
    {
        $dbResult = $this->objDSystem->get(['type' => $params,'enterpriseId' => $this->enterpriseId]);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDSystem->error(), ErrorCode::$dberror);
        }
        $dbResult && $dbResult['content'] = json_decode($dbResult['content'], true);
        return ResultWrapper::success($dbResult);
    }

    /**
     * 获取预授权码(pre_auth_code)
     * 官网文档地址: https://developers.weixin.qq.com/doc/oplatform/Third-party_Platforms/Authorization_Process_Technical_Description.html
     * @return ResultWrapper
     */
    public function preAuthCode()
    {
//        $content = $this->objDSystem->get(['enterpriseId' => $this->enterpriseId], 'content');
//        if ($content === false) {
//            return ResultWrapper::fail($this->objDSystem->error(), ErrorCode::$dberror);
//        }
//        if (empty($content)) return ResultWrapper::fail('请先填写基本信息', ErrorCode::$dberror);
//
//        $oplatformConfigData = json_decode($content['content'],true);

        //获取微信配置
        /*
        $oplatformConfigData = Factory::config()->getAppoint('weixin', 'oplatform');
        if (empty($oplatformConfigData)) {
            return ResultWrapper::fail('配置错误', ErrorCode::$dberror);
        }*/

        $refererUrl = parse_url($_SERVER['HTTP_REFERER']);
        $host = $refererUrl['host'];
        $objMOem = new MOem();
        $result = $objMOem->getOemInfoByDomain($host);
        if( !$result->isSuccess() ){
            return ResultWrapper::fail($result->getData(), $result->getErrorCode());
        }
        $oemData = $result->getData();
        if( empty($oemData) ){
            return ResultWrapper::fail('oem表中获取微信开放平台配置为空', ErrorCode::$contentNotExists);
        }
        $oplatformConfigData = json_decode($oemData['weixinOpen'], true);
        if( empty($oplatformConfigData) ){
            return ResultWrapper::fail('oem表中获取微信开放平台配置为空', ErrorCode::$contentNotExists);
        }

        $objOplatform = new Oplatform($oplatformConfigData['appid'], $oplatformConfigData['token'], $oplatformConfigData['encodingAesKey'], $oplatformConfigData['appSecret']);

        $result = $objOplatform->preAuthCode();
        if (!$result->isSuccess()) {
            return ResultWrapper::fail($result->getData(), $result->getErrorCode());
        }
        $pre_auth_code = $result->getData();

        $this->redirect_uri = 'http://'.$host.'/AuthorizePage';
        $auth_url = 'https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid=' . $oplatformConfigData['appid'] . '&pre_auth_code=' . $pre_auth_code . '&redirect_uri=' . $this->redirect_uri . '&auth_type=2';
        return ResultWrapper::success($auth_url);
    }

    /**
     * type = 4
     * @param $params
     * @return ResultWrapper
     */
    public function saveByteDanceSetting($params)
    {
        $dbResult = $this->objDSystem->replace($params);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDSystem->error(), ErrorCode::$dberror);
        }

        //缓存字节小程序配置
        $objSystemCache = new SystemCache();
        $objSystemCache->cacheByteDanceSetting($params['content'], $this->enterpriseId);
        return ResultWrapper::success($dbResult);
    }

}