<?php
/**
 * 微信接口类 提供给微信调用的接口
 * ============================================================================
 * * 版权所有 蜘蛛出行 * *
 * 网站地址: http://www.zhizhuchuxing.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * Author By: 倪宗锋
 * PhpStorm WeChatController.php
 * Create By 2017/3/2 11:06 $
 */

namespace fx\controllers\weChat;

use common\Controller\FxWebController;
use common\models\OrderMain;
use common\util\CurlInterface;
use common\util\PayService;
use common\util\Util;
use common\util\WeChatPay;
use common\util\WeChatService;
use fx\util\FxUtil;

class WeChatController extends FxWebController
{
    public $service = null;

    public function getService()
    {
        if ($this->service == null) {
            $this->service = new WeChatService();
        }
        return $this->service;
    }

    /*
         * 第三方授权路径
         */
    public function actionLoginRedirect()
    {
        $code = $this->_get('code', '');
        $url = $this->_get('redirect', '');
        $url .= '&code=' . $code;
        header('location:' . $url);
        return $url;
    }

    /**
     * Des:授权登录
     * Name: actionAuthLogin
     * @author 倪宗锋
     */
    public function actionAuthLogin()
    {
        $redirect = $this->_get('redirect');
        $url = FxUtil::getAuthLoginUrl($redirect);
        echo $url;
        return $this->redirect($url);
    }

    /**
     * Des:页面跳转
     * Name: setLoginAction
     * @return string
     * @author 倪宗锋
     */
    public function actionSetLogin()
    {
        $code = $this->_get('code', '');
        $token = WeChatService::getToken($code);
        if ($token['flag'] == true && empty($token['data']['openid']) == false) {
            $openid = $token['data']['openid'];
            $accessToken = $token['data']['access_token'];
            $setLogin = FxUtil::setLoginByOpenid($openid, $accessToken);//设置用户登录
            if ($setLogin['flag'] == false) {
                $msg = $setLogin['msg'];
                include ROOT_PATH . '/web/fx/fx_disable.phtml';
                return '';
            }
        } else {//code如果第二次进入 则判断是否已经登录过了
            $checkLogin = FxUtil::checkLogin(false);
            if ($checkLogin['flag'] == false) {
                $msg = '授权登录失败！请稍后再试！';
                include ROOT_PATH . '/web/fx/fx_disable.phtml';
                return '';
            }
        }
        $url = $this->_get('redirect', '');
        $siteConfig = FxUtil::getSiteConfig();
        $url = empty($url) ? $siteConfig['host_name'] : $url;
        return $this->redirect($url);
    }

    /**
     * Des:校验用户登录
     * Name: actionCheckLogin
     * @return string
     * @author 倪宗锋
     */
    public function actionCheckLogin()
    {
        return Util::returnJsSu();
    }

    /**
     * Des:开放给微信调用的接口
     * Name: indexAction
     * @return bool|string
     * @author 倪宗锋
     */
    public function actionIndex()
    {
        if (isset($_GET['echostr'])) {//首次校验
            $check = $this->getService()->valid();
            return $check;
        }
        return $this->getService()->exec();
    }

    /**
     * Des:设置菜单
     * Name: setMenuAction
     * @author 倪宗锋
     */
    public function actionSetMenu()
    {
        $access_token = $this->getService()->getAccessToken();
        $url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" . $access_token;
        $weChatConfig = WeChatPay::getAuthWeChatConfig();
        $data = require ROOT_PATH . '/common/config/wechatConfig/wxInterface/' . $weChatConfig['mch_id'] . '/wxMenu.config.php';
        $result = $this->getService()->_requestPost($url, $data);
        print_r($result);
    }

    /**
     * Des:获取素材ID
     * Name: getMediaAction
     * @author 倪宗锋
     */
    public function actionGetMedia()
    {
        $type = $this->_get('type', 'news');//素材的类型，图片（image）、视频（video）、语音 （voice）、图文（news）
        $list = $this->getMediaList($type);
        $this->view->params['type'] = $type;
        $this->view->params['list'] = $list;
        $this->view->defaultExtension = 'phtml';
        return $this->render('getMedia');
    }

    public function getMediaList($type)
    {
        $clear = $this->_get('clear', '');
        $cache = \Yii::$app->cache;
        $wxConfig = WeChatPay::getAuthWeChatConfig();
        $keys = $wxConfig['appid'] . 'wxMediaList';
        if ($clear == 'clear') {
            $cache->delete($keys);
        }
        $wxMediaList = $cache->get($keys);
        if (isset($wxMediaList[$type])) {
            return $wxMediaList[$type];
        }
        $access_token = $this->getService()->getAccessToken();
        $url = "https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=" . $access_token;
        $data = '{"type":"' . $type . '","offset":0,"count":20}';
        $result = $this->getService()->httpRequest($url, $data);
        $return = json_decode($result, true);
        $list = array();
        if (isset($return['item'])) {
            $list = $return['item'];
        }
        foreach ($list as $key => $val) {
            if ($type == 'news') {
                $list[$key] = $this->setNewsShow($val);
            }
        }
        $wxMediaList[$type] = $list;
        $cache->set($keys, $wxMediaList, 60 * 10);//缓存10分钟
        return $list;
    }

    public function actionClear()
    {
        $cache = \Yii::$app->cache;
        $wxConfig = WeChatPay::getAuthWeChatConfig();
        $keys = $wxConfig['appid'] . 'wxMediaList';
        $cache->set($keys, array(), 60 * 10);
    }

    /**
     * Des: 设置图文展示
     * Name: setNewsShow
     * @param $list
     * @return array
     * @author 倪宗锋
     */
    public function setNewsShow($list)
    {
        $listArr = $list['content']['news_item'];
        $title = '';
        foreach ($listArr as $val) {
            if ($val['title']) {
                $title .= $val['title'] . '</br>';
            }
        }
        $return = array(
            'media_id' => $list['media_id'],
            'name' => $title
        );
        return $return;
    }

    /**
     * Des:生成微信二维码
     * Name: actionAddQRcode
     * @return array|mixed|string
     * @author 倪宗锋
     */
    public function actionAddQRcode()
    {
        $code = $this->_get('id', '');
        if (empty($code)) {
            return 'id不能为空！';
        }
        $token = $this->getService()->getAccessToken();
        $url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" . $token;
        $data = array(
            'action_name' => 'QR_LIMIT_STR_SCENE',
            'action_info' => array(
                'scene' => array(
                    'scene_str' => $code
                )
            )
        );
        $inface = new CurlInterface($data);
        $inface->setBaseUrl($url);
        $return = $inface->execute('', 'POST');
        return $return;
    }

    public function actionNewQRCode(){

    }

    /**
     * Des:生成二维码
     * Name: qCodeAction
     * @author 倪宗锋
     */
    public function actionQCode()
    {
        $qCode = $this->_get('qCode', '');
        include ROOT_PATH . '/common/util/phpqrcode/phpqrcode.php';
        $value = $qCode;//二维码内容
        $errorCorrectionLevel = 'H';//容错级别
        $matrixPointSize = 6;//生成图片大小
        //生成二维码图片
        $QRFile = ROOT_PATH . '/common/util/phpqrcode/images/' . (microtime(true) * 10000) . 'qrcode.png';
        $logo = false;
        \QRcode::png($value, $QRFile, $errorCorrectionLevel, $matrixPointSize, 2);
        $QR = imagecreatefromstring(file_get_contents($QRFile));
        if ($logo !== FALSE) {
            $logo = imagecreatefromstring(file_get_contents($logo));
            $QR_width = imagesx($QR);//二维码图片宽度
            $logo_width = imagesx($logo);//logo图片宽度
            $logo_height = imagesy($logo);//logo图片高度
            $logo_qr_width = $QR_width / 5;
            $scale = $logo_width / $logo_qr_width;
            $logo_qr_height = $logo_height / $scale;
            $from_width = ($QR_width - $logo_qr_width) / 2;
            //重新组合图片并调整大小
            imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width,
                $logo_qr_height, $logo_width, $logo_height);
        }
        //输出图片
        Header("Content-type: image/png");
        ImagePng($QR);
        unlink($QRFile);
        die;
    }

    /**
     * Des:订单扫描支付测试
     * Name: actionOrder
     * @return \yii\web\Response
     * @author 倪宗锋
     */
    public function actionSaoCe()
    {
        $type = $this->_get('type', 1);
        $order_id = $this->_get('order_id', 1);
        $params = array(
            'order_id' => $order_id,
            'total_fee' => 1,
            'name' => '支付测试' . $order_id
        );
        $info = PayService::sao($params, $type);
        if ($info['flag'] == false) {
            return $info['msg'];
        }
        return $this->redirect($info['data']['codUrl'], 302);
    }

    /**
     * Des:取消订单
     * Name: actionCancel
     * @return string
     * @author 倪宗锋
     */
    public function actionCancel()
    {
        $type = $this->_get('type', 1);
        $order_id = $this->_get('order_id', 1);
        $params = array(
            'order_id' => $order_id,
            'total_fee' => 1,
            'memo' => '支付测试' . $order_id,
            'refund_id' => $order_id,
            'refund_fee' => 0.99
        );
        $info = PayService::cancel($params, $type);
        if ($info['flag'] == false) {
            return $info['msg'];
        }
        return '退款成功';
    }

    /**
     * Des:用户
     * Name: actionUser
     * @return mixed
     * @author 倪宗锋
     */
    public function actionUserQrCode()
    {
        $getImage = FxUtil::getFXQrCode();
        return json_encode($getImage);
    }

    public function actionUserNewQrCode()
    {
        $getImage = FxUtil::getFXNewQrCode();
        return json_encode($getImage);
    }

    public function actionClears()
    {
        $memcache = \Yii::$app->getCache();
        $memcache->flush();
    }

    public function actionFxCode()
    {
        $return = $this->getService()->getFxQrCode(FxUtil::$uid);
        return json_encode($return);
    }
}