<?php


namespace app\api\controller\wechat;


use app\models\user\User;
use app\models\user\UserToken;
use app\models\user\WechatUser;
use app\models\user\BindUser;
use app\models\store\StoreOrder;
use app\models\system\MerchantDailyReport;
use app\Request;
use crmeb\services\WechatService;
use crmeb\services\UtilService;
use crmeb\utils\Canvas;
use think\facade\Cookie;

/**
 * 微信公众号
 * Class WechatController
 * @package app\api\controller\wechat
 */
class WechatController
{
    //公众号appid
    const APPID = 'wx850b73fe48f1e931';

    //公众号appsecret
    const APP_SECRET = 'e1a17191ca4e91657932df9a13a09886';

    /**
     * 微信公众号服务
     * @return \think\Response
     */
    public function serve()
    {
        ob_clean();
        return WechatService::serve();
    }

    /**
     * 支付异步回调
     */
    public function notify()
    {
        ob_clean();
        WechatService::handleNotify();
    }

    /**
     * 公众号权限配置信息获取
     * @param Request $request
     * @return mixed
     */
    public function config(Request $request)
    {
        return app('json')->success(json_decode(WechatService::jsSdk($request->get('url')), true));
    }

    /**
     * 公众号授权登陆
     * @param Request $request
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function auth(Request $request)
    {
        $spreadId = intval($request->param('spread'));
        $login_type = $request->param('login_type', '');
        try {
            $wechatInfo = WechatService::oauthService()->user()->getOriginal();
        } catch (\Exception $e) {
            return app('json')->fail('授权失败', ['message' => $e->getMessage(), 'line' => $e->getLine()]);
        }
        if (!isset($wechatInfo['nickname'])) {
            $wechatInfo = WechatService::getUserInfo($wechatInfo['openid']);
            if (!$wechatInfo['subscribe'] && !isset($wechatInfo['nickname']))
                exit(WechatService::oauthService()->scopes(['snsapi_userinfo'])
                    ->redirect($this->request->url(true))->send());
            if (isset($wechatInfo['tagid_list']))
                $wechatInfo['tagid_list'] = implode(',', $wechatInfo['tagid_list']);
        } else {
            if (isset($wechatInfo['privilege'])) unset($wechatInfo['privilege']);
            if (!WechatUser::be(['openid' => $wechatInfo['openid']]))
                $wechatInfo['subscribe'] = 0;
        }
        $openid = $wechatInfo['openid'];
        event('WechatOauthAfter', [$openid, $wechatInfo, $spreadId, $login_type]);
        $user = User::where('uid', WechatUser::openidToUid($openid, 'openid'))->find();
        if (!$user)
            return app('json')->fail('获取用户信息失败');
        if ($user->login_type == 'h5' && ($h5UserInfo = User::where(['account' => $user->phone, 'phone' => $user->phone, 'user_type' => 'h5'])->find()))
            $token = UserToken::createToken($h5UserInfo, 'wechat');
        else
            $token = UserToken::createToken($user, 'wechat');
        // 设置推广关系
        User::setSpread(intval($spreadId), $user->uid);
        if ($token) {
            event('UserLogin', [$user, $token]);
            return app('json')->success('登录成功', ['token' => $token['token'], 'expires_time' => date('Y-m-d H:i:s', $token['params']['exp'])]);
        } else
            return app('json')->fail('登录失败');
    }

    /**
     * 公众号网页授权登陆
     */
    public function wxAuth(Request $request)
    {
        $mer_id = $request->param('mer_id', '');
        $redirect_uri=urlencode("https://auti.boofly.cn/api/wechat/bindPush");
        header('location:https://open.weixin.qq.com/connect/oauth2/authorize?appid='.self::APPID.'&redirect_uri='.$redirect_uri.'&response_type=code&scope=snsapi_userinfo&state='.$mer_id.'#wechat_redirect');
    }

    /**
     * 公众号绑定推送
     */
    public function bindPush(Request $request)
    {
        try {
            $data = UtilService::getMore([
                ['code', ''],
                ['state', ''],
            ]);
            $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.self::APPID.'&secret='.self::APP_SECRET.'&code='.$data['code'].'&grant_type=authorization_code';
            $res = json_decode(doRequest($url, [], null, false), true);
            if (isset($res['errcode']) && $res['errcode'] != 0) {
                return app('json')->fail($res['errmsg'] ?? $res['msg'] ?? '请求错误');
            }
            $result = $this->getUserInfo($res['access_token'], $res['openid']);
            return app('json')->success('ok', $result);
        } catch (Exception $e) {
            return app('json')->fail($e->getMessage(), ['file' => $e->getFile(), 'line' => $e->getLine()]);
        }
    }

    /**
     * 拉取用户信息
     */
    public function getUserInfo($access_token, $openid)
    {
        try {
            $url = 'https://api.weixin.qq.com/sns/userinfo?access_token='. $access_token. '&openid='. $openid. '&lang=zh_CN';
            $res = json_decode(doRequest($url, [], null, false), true);
            if (isset($res['errcode']) && $res['errcode'] != 0) {
                return app('json')->fail($res['errmsg'] ?? $res['msg'] ?? '请求错误');
            }
            return $res;
        } catch (Exception $e) {
            return app('json')->fail($e->getMessage(), ['file' => $e->getFile(), 'line' => $e->getLine()]);
        }
    }

    /**
     * 用户信息入库
     */
    public function addUserInfo(Request $request)
    {
        try {
            $data = UtilService::postMore([
                ['openid', ''],
                ['nickname', ''],
                ['sex', ''],
                ['language', ''],
                ['city', ''],
                ['province', ''],
                ['country', ''],
                ['headimgurl', ''],
                ['state', '']
            ]);
            $type = 1;
            $status = 1;
            $info = BindUser::where('openid', $data['openid'])->where('is_del', 0)->find();
            if($info){
                BindUser::where('id', $info['id'])->update(['openid' => $data['openid'], 'nickname' => $data['nickname'], 'sex' => $data['sex'], 'language' => $data['language'], 'city' => $data['city'], 'province' => $data['province'], 'country' => $data['country'], 'headimgurl' => $data['headimgurl']]);
            }else{
                $res = BindUser::addBindUser($data['openid'], $data['nickname'], $data['sex'], $data['language'], $data['city'], $data['province'], $data['country'], $data['headimgurl'], $type, $status, $data['state']);
                if(!$res){
                    return app('json')->fail('入库失败');
                }
            }
            return app('json')->success('入库成功');
        } catch (Exception $e) {
            return app('json')->fail($e->getMessage(), ['file' => $e->getFile(), 'line' => $e->getLine()]);
        }
    }

    /**
     * 统计报表列表
     */
    public function getReportList(Request $request)
    {
        $data = UtilService::getMore([
            ['mer_id', ''],
            ['date', '']
        ]);
        $model = new MerchantDailyReport;
        if($data['mer_id']) $model = $model->where('mer_id', $data['mer_id']);
        if($data['date']) $model = $model->where('report_date', $data['date']);
        $yesterday = $model->find();
        //总销售额
        $total_sales = StoreOrder::merSet($data['mer_id'])
            ->where('paid', 1)
            ->where('is_del', 0)
            ->where('refund_status', 0)
            ->sum('pay_price');
        //总访问量
        $total_visits = User::merSet($data['mer_id'])->count();
        //总订单量
        $total_order = StoreOrder::merSet($data['mer_id'])->where('is_system_del', 0)->count();
        //所有用户
        $total_user = User::merSet($data['mer_id'])->count();
        $total = [
            'total_sales' => $total_sales . '元',
            'total_visits' => $total_visits . 'Pv',
            'total_order' => $total_order . '单',
            'total_user' => $total_user . '人',
        ];
        $info = compact('yesterday', 'total');
        return app('json')->success($info);
    }

    public function follow(Request $request)
    {
        $canvas = Canvas::instance();
        $path = 'uploads/follow/';
        $imageType = 'jpg';
        $name = 'follow';
        $siteUrl = sys_config('site_url', '', $request->mer_id());
        $imageUrl = $path . $name . '.' . $imageType;
//        if (file_exists($imageUrl)) {
//            return app('json')->success('ok', ['path' => $siteUrl . '/' . $imageUrl]);
//        }
        $canvas->setImageUrl('statics/qrcode/follow.png')->setImageHeight(720)->setImageWidth(500)->pushImageValue();
        $wechatQrcode = sys_config('wechat_qrcode', '', $request->mer_id());
        if (($strlen = stripos($wechatQrcode, 'uploads')) !== false) {
            $wechatQrcode = substr($wechatQrcode, $strlen);
        }
        if (!$wechatQrcode)
            return app('json')->fail('请上传二维码');
        $canvas->setImageUrl($wechatQrcode)->setImageHeight(344)->setImageWidth(344)->setImageLeft(76)->setImageTop(76)->pushImageValue();
        $image = $canvas->setFileName($name)->setImageType($imageType)->setPath($path)->setBackgroundWidth(500)->setBackgroundHeight(720)->starDrawChart();
        return app('json')->success('ok', ['path' => $image ? $siteUrl . '/' . $image : '']);
    }
}