<?php
/**
 * @package merchant
 *
 * @author xaboy
 * @day 2020/5/27
 *
 *
 */

namespace app\controller\api;


use app\common\model\user\UserCertification;
use app\common\repositories\merchant\order\OrderGzcRepository;
use app\common\repositories\merchant\order\OrderMerchantRepository;
use app\common\repositories\store\order\StoreRefundStatusRepository;
use app\common\repositories\user\UserVisitDayRepository;
use app\controller\api\merchant\sxy\Access;
use app\controller\api\store\product\Jd;
use app\controller\api\store\product\TaoKe;
use app\controller\api\store\product\Vip;
use app\traits\ShouxinyiApiRequest;
use crmeb\basic\BaseController;
use app\common\repositories\store\shipping\ExpressRepository;
use app\common\repositories\store\StoreCategoryRepository;
use app\common\repositories\system\groupData\GroupDataRepository;
use app\common\repositories\user\UserVisitRepository;
use app\common\repositories\wechat\TemplateMessageRepository;
use app\common\repositories\system\merchant\MerchantCategoryRepository;
use crmeb\services\MiniProgramService;
use crmeb\services\UploadService;
use crmeb\services\WechatService;
use Exception;
use think\App;
use think\facade\Cache;
use think\facade\Config;
use think\facade\Log;
use think\Response;
use think\response\Html;
use Alipay\AopClient;
use think\facade\Db;
use function Symfony\Component\String\s;

/**
 * Class Common
 * @package app\controller\api
 * @author xaboy
 * @day 2020/5/28
 */
class Common extends BaseController
{

    protected $merId;
    protected $source;
    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->source = $this->request->header('source');
        $this->merId =  $this->request->header('merId');
    }
    /**
     * @return mixed
     * @author xaboy
     * @day 2020/5/28
     */
    public function hotKeyword()
    {
        $keyword = systemGroupData('hot_keyword');
        return app('json')->success($keyword);
    }

    public function express(ExpressRepository $repository)
    {
        return app('json')->success($repository->options());
    }

    public function home_quick_link(){
        $home_quick_link = systemGroupData('home_quick_link');
        return app('json')->success($home_quick_link);
    }

    public function menus()
    {
        return app('json')->success(['banner' => systemGroupData('my_banner'), 'menu' => systemGroupData('my_menus')]);
    }

    public function refundMessage()
    {
        return app('json')->success(explode("\n", systemConfig('refund_message')));
    }

    public function config()
    {
        $config = systemConfig(['appraise_set', 'mews_all', 'help', 'all_people', 'proclamation', 'my_release', 'ali_login', 'wechat_login', 'real_name', 'hide_mer_status', 'mer_intention_open', 'share_info', 'sys_intention_agree', 'share_title', 'share_pic', 'store_user_min_recharge', 'recharge_switch', 'balance_func_status', 'yue_pay_status', 'site_logo', 'site_name', 'wechat_id']);
        $make = app()->make(TemplateMessageRepository::class);
        $config['tempid'] = $make->getSubscribe();
        return app('json')->success($config);
    }


    /*商户入驻资料配置*/
    public function mer_config()
    {
        $config = systemConfig(['mer_type', 'mer_cate', 'card_person', 'email', 'mer_name', 'name',
            'phone', 'addr', 'door_head', 'business_license', 'bank_account',
            'bank_location', 'bank_deposit', 'bank_branch', 'open_account', 'logo', 'desc', 'business_addr',
            'district_addr', 'spread_account', 'credit_code']);
        return app('json')->success($config);
    }

    /*商户入驻资料配置*/
    public function agent_config()
    {
        $config = systemConfig(['apply_set', 'apply_name', 'apply_type', 'apply_business']);
        return app('json')->success($config);
    }


    /*提现*/
    public function withdrawal_config()
    {
        $config = systemConfig(['withdrawal_status', 'withdrawal_money', 'withdrawal_alipay', 'withdrawal_wchat', 'withdrawal_card']);
        return app('json')->success($config);
    }

    /*关于我们*/
    public function about_config()
    {
        $config = systemConfig(['about_edition_ios', 'about_edition_old_ios',
            'about_edition_android', 'about_edition_old_android',
            'about_address', 'about_name', 'about_phone', 'about_email',
            'about_yl', 'about_zx', 'about_pcpc', 'wechat_id']);

        $config['about_yl_name'] = '养老计划';
        $config['about_zx_name'] = '中信公证处';
        $config['about_pcpc_name'] = 'PCPC';
        if($this->source=='yhc'){
            $config =  merchantConfig($this->merId,['yhc_about_name','yhc_about_address','yhc_about_phone','yhc_about_email']);
        }

        return app('json')->success($config);
    }

    /**
     * 公证处配置
     * author: php迷途小书童
     * created: 2021/3/31 16:12
     */
    public function gzcConfig()
    {
        $config = systemGroupData('gzc');
        return app('json')->success($config);
    }

    /**
     * @param GroupDataRepository $repository
     * @return mixed
     * @author xaboy
     * @day 2020/6/3
     */
    public function userRechargeQuota(GroupDataRepository $repository)
    {
        $recharge_quota = $repository->groupDataId('user_recharge_quota', 0);
        $recharge_attention = explode("\n", systemConfig('recharge_attention'));
        return app('json')->success(compact('recharge_quota', 'recharge_attention'));
    }

    /**
     * @param $field
     * @return mixed
     * @author xaboy
     * @day 2020/5/28
     */
    public function uploadImage($field)
    {
        $file = $this->request->file($field);
        if (!$file)
            return app('json')->fail('请上传图片');
        $file = is_array($file) ? $file[0] : $file;
        validate(["$field|图片" => [
            'fileSize' => 10097152,
            'fileExt' => 'jpg,JPG,jpeg,png,bmp,gif',
            'fileMime' => 'image/jpeg,image/png,image/gif',
        ]])->check([$field => $file]);

        try {
            $upload = UploadService::create();
            $time = date('Y-m-d');
            $path = "chuxubao/images/" . $time . '/';
            $info = $upload->to('def')->move($field,$path);
            if ($info === false) {
                return app('json')->fail($upload->getError());
            }
            $res = $upload->getUploadInfo();
            $res['dir'] = path_to_url($res['dir']);
            if (strpos($res['dir'], 'http') === false) $res['dir'] = "http://" . $this->request->host(true) . $res['dir'];//2222
        } catch (\Throwable $e) {
            Log::info('upload:' . $e->getMessage());
            return app('json')->fail('上传失败');
        }
        return app('json')->success(['path' => $res['dir']]);
    }

    /**
     * @param $field
     * @return mixed
     * @author xaboy
     * @day 2020/5/28
     */
    public function uploadBase64Image()
    {
        $image = $this->request->param('image');
        $base64_img = trim($image);
        // 正则表达式：判断图片文件类型是否正确
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_img, $result)) {
            $type = $result[2];
            if (in_array($type, array('pjpeg', 'jpeg', 'jpg', 'JPG', 'gif', 'bmp', 'png'))) {
                // 如果文件夹不存在则创建
                $up_dir = '/uploads/def/' . date('Ymd') . '/';
                if (!is_dir('./public' . $up_dir)) {
                    mkdir('./public' . $up_dir, 0777, true);
                }
                $new_file = (int)(microtime(true) * 1000);
                $imgName = $up_dir . "{$new_file}." . $type;
                if (file_put_contents('./public' . $imgName, base64_decode(str_replace($result[1], '', $base64_img)))) {
                    // 完整的图片地址（包括域名）
                    $imgurl = "http://" . $this->request->host(true) . $imgName;//2222
                    return app('json')->success(['path' => $imgurl]);
                } else {
                    return app('json')->fail('图片上传失败');
                }
            } else {
                return app('json')->fail('图片类型错误');
            }
        } else {
            return app('json')->fail('文件错误');
        }
    }

    /**
     * @return Response
     * @author xaboy
     * @day 2020/6/3
     */
    public function wechatNotify()
    {
        try {
            return response(WechatService::create()->handleNotify()->getContent());
        } catch (Exception $e) {
            Log::info('支付回调失败:' . var_export([$e->getMessage(), $e->getFile() . ':' . $e->getLine()], true));
        }
    }

    /**
     * @return Response
     * @author xaboy
     * @day 2020/6/3
     */
    public function alipayNotify()
    {
        $post = $this->request->post();
        try {
            $aop = new AopClient;
            $aop->alipayrsaPublicKey = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArHwMZtNYBkK5q2jQ0Ml18H8MhQX9Bpuz/ignvuJC47K7LHY+F6/U/+o/nYeDhqHzUajMAAyM06N3r2qBnWQRjC4JKFMO4i5xIDVycuumzcsWz3LwAkHOFG/S1pGXFWh74zdQDNednhvnNOiTDwjefZRnf5HUqEZK/7tRSaZvzSUIAwHG2zj0C6AYkhg5wr6ZJxgRDjPjqbs6ZMqLT+pITsnCcc6IgIisZbPTdtw1U2FKmQm5n228drI3XKYbE3UVT2y6R0mZNmqmiHDszmYSKOjDrpgtMExWpee8kUFn7J800HIyYtq0nRv1ypdWngUZtkm+szVWOTDGgN4eHQW3FwIDAQAB';
            $flag = $aop->rsaCheckV1($post, NULL, "RSA2");
            if ($flag) {
                event('pay_success_order', ['order_sn' => $post['out_trade_no'], 'data' => $post]);
            }
        } catch (Exception $e) {
            Log::info('支付回调失败:' . var_export([$e->getMessage(), $e->getFile() . ':' . $e->getLine()], true));
        }
    }

    public function routineNotify()
    {
        try {
            return response(MiniProgramService::create()->handleNotify()->getContent());
        } catch (Exception $e) {
            Log::info('支付回调失败:' . var_export([$e->getMessage(), $e->getFile() . ':' . $e->getLine()], true));
        }
        Log::info('小程序支付成功回调');
    }


    /*代理支付支付宝回调*/
    public function aliPayAgentNotify()
    {

        $post = $this->request->post();
        try {
            $aop = new AopClient;
            $aop->alipayrsaPublicKey = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArHwMZtNYBkK5q2jQ0Ml18H8MhQX9Bpuz/ignvuJC47K7LHY+F6/U/+o/nYeDhqHzUajMAAyM06N3r2qBnWQRjC4JKFMO4i5xIDVycuumzcsWz3LwAkHOFG/S1pGXFWh74zdQDNednhvnNOiTDwjefZRnf5HUqEZK/7tRSaZvzSUIAwHG2zj0C6AYkhg5wr6ZJxgRDjPjqbs6ZMqLT+pITsnCcc6IgIisZbPTdtw1U2FKmQm5n228drI3XKYbE3UVT2y6R0mZNmqmiHDszmYSKOjDrpgtMExWpee8kUFn7J800HIyYtq0nRv1ypdWngUZtkm+szVWOTDGgN4eHQW3FwIDAQAB';
            $flag = $aop->rsaCheckV1($post, NULL, "RSA2");
            if ($flag) {
                event('pay_success_order_agent', ['order_sn' => $post['out_trade_no'], 'data' => $post]);
            }
        } catch (Exception $e) {
            Log::info('代理支付支付回调失败:' . var_export([$e->getMessage(), $e->getFile() . ':' . $e->getLine()], true));
        }

    }


    /**
     * 获取图片base64
     * @return mixed
     */
    public function get_image_base64()
    {
        list($imageUrl, $codeUrl) = $this->request->params([
            ['image', ''],
            ['code', ''],
        ], true);
        try {
            $codeTmp = $code = $codeUrl ? image_to_base64($codeUrl) : '';
            if (!$codeTmp) {
                $putCodeUrl = put_image($codeUrl);
                $code = $putCodeUrl ? image_to_base64('./runtime/temp' . $putCodeUrl) : '';
                $code && unlink('./runtime/temp' . $putCodeUrl);
            }

            $imageTmp = $image = $imageUrl ? image_to_base64($imageUrl) : '';
            if (!$imageTmp) {
                $putImageUrl = put_image($imageUrl);
                $image = $putImageUrl ? image_to_base64('./runtime/temp' . $putImageUrl) : '';
                $image && unlink('./runtime/temp' . $putImageUrl);
            }
            return app('json')->success(compact('code', 'image'));
        } catch (\Exception $e) {
            return app('json')->fail($e->getMessage());
        }
    }

    public function home()
    {
        $banner = systemGroupData('home_banner');
        $menu = systemGroupData('home_menu');
        foreach ($menu as $k => $v) {
            if (in_array($v['name'], ['京东', '饿了么', '唯品会', '拼多多', '苏宁易购'])) {
                $menu[$k]['is_change'] = 1;
            }
        }
        $hot = systemGroupData('home_hot');
        $ad = systemConfig(['home_ad_pic', 'home_ad_url']);
        $category = app()->make(StoreCategoryRepository::class)->getTwoLevel();
        $shop_category = app()->make(MerchantCategoryRepository::class)->allOptions();
        return app('json')->success(compact('banner', 'menu', 'hot', 'ad', 'category', 'shop_category'));
    }

    public function home_banner_new()
    {
        $banner = systemGroupData('home_banner_new');
        return app('json')->success($banner);
    }

    public function user_banner()
    {
        $banner = systemGroupData('user_banner');
        return app('json')->success($banner);
    }

    public function visit()
    {
        [$page, $type] = $this->request->params(['page', 'type'], true);
        $uid = $this->request->uid();
        if (!$page || !$uid) return app('json')->fail();
        $userVisitRepository = app()->make(UserVisitRepository::class);
        $type == 'routine' ? $userVisitRepository->visitSmallProgram($uid, $page) : $userVisitRepository->visitPage($uid, $page);
        return app('json')->success();
    }

    /*
     *@ banner图
     *@$type  nearby=附近页面banner
     *@author cabbage
     * */
    public function hotBanner($type)
    {
        if (!in_array($type, ['new', 'hot', 'best', 'good', 'nearby']))
            $data = [];
        else
            $data = systemGroupData($type . '_home_banner');
        return app('json')->success($data);
    }


    /*版本更新*/
    public function about_change()
    {
        $data = $this->request->params(['about', 'type']);

        //安卓
        if ($data['type'] == 1) {
            $config = systemConfig(['about_edition_android', 'about_link_android', 'update_content','Android_forced_update']);

            $version = str_replace('.', '', $data['about']);
            $sysVersion = str_replace('.', '', $config['about_edition_android']);

            if ($version < $sysVersion) {
                return app('json')->success($config);
            }else{
                return app('json')->fail('已是最新版本');
            }
        }

        if ($data['type'] == 2) {
            $config = systemConfig(['about_edition_ios', 'about_link_ios', 'update_content','IOS_forced_update']);
            if ($data['about'] != $config['about_edition_ios']) {
                return app('json')->success($config);
            } else {
                return app('json')->fail('已是最新版本');
            }
        }
    }

    /*版本更新运营商*/
    public function about_change_yys()
    {
        $data = $this->request->params(['about', 'type']);

        //安卓
        if ($data['type'] == 1) {
            $config = systemConfig(['yys_code_android', 'yys_link_android']);
            if ($data['about'] != $config['yys_code_android']) {
                return app('json')->success($config);
            } else {
                return app('json')->fail('已是最新版本');
            }
        }

        if ($data['type'] == 2) {

        }
    }

    //通过curl方式获取请求内容公共方法
    public static function sendCurl($url, $data = array(), $method = 'get',$header = array() )
    {
        if ($method == 'post') {
            //使用crul模拟
            $ch = curl_init();
            //禁用https
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            //允许请求以文件流的形式返回
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
            curl_setopt($ch, CURLOPT_DNS_CACHE_TIMEOUT, 30);
            curl_setopt($ch, CURLOPT_URL, $url);
            if ($header) {
                curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
            }
            $result = curl_exec($ch); //执行发送
            curl_close($ch);
        } else {
            if (ini_get('allow_fopen_url') == '1') {
                $result = file_get_contents($url);
            } else {
                //使用crul模拟
                $ch = curl_init();
                //允许请求以文件流的形式返回
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
                //禁用https
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
                curl_setopt($ch, CURLOPT_URL, $url);
                if ($header) {
                    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
                }
                $result = curl_exec($ch); //执行发送
                curl_close($ch);
            }
        }
        return json_decode($result, true);
    }

    public function iOSExamineStatsu_api($version)
    {
//        $res=2;
//        if ($this->check() == 'ios') {
            $res = Db::name('iosexaminestatsu')->where('version', $version)->value('status');
            if (!$res) {
                return app('json')->fail('未获取到该该版本的信息');
//            }
        }
            Log::info($_SERVER);
        return app('json')->success($res);

    }

    public function check()
    {
        $agent = strtolower($_SERVER['HTTP_USER_AGENT']);
        $is_pc = (strpos($agent, 'windows nt')) ? true : false;
        $is_mac = (strpos($agent, 'mac os')) ? true : false;
        $is_iphone = (strpos($agent, 'iphone')) ? true : false;
        $is_android = (strpos($agent, 'android')) ? true : false;
        $is_ipad = (strpos($agent, 'ipad')) ? true : false;


        if ($is_pc) {
            return 'and';
        }

        if ($is_mac) {
            return 'ios';
        }

        if ($is_iphone) {
            return 'ios';
        }

        if ($is_android) {
            return 'and';
        }

        if ($is_ipad) {
            return 'ios';
        }
    }

    public function roll_yanglaojin(){

        $list = Db::name('UserBill')
            -> alias('ub')
            -> join('User u',"ub.uid = u.uid")
            -> where(['ub.commission_type'=>5,'ub.status'=>1])
            -> orderRand()
            -> limit(20)
            -> field('ub.number,u.nickname')
            -> select()
            -> each(function ($item){
//                $item['msg'] = '养老金快报：【'.$item['nickname']."】获得".$item['number']."养老金";
                $item['msg'] = '【'.$item['nickname']."】获得".$item['number']."养老金";
                return $item;
            })
            -> toArray();

        return app('json')->success($list);

    }

    public function applet_audit()
    {
        $status=Db::name('system_config_value')->where('config_key','xiaochengxu_shenhe')->value('value');
        return app('json')->success($status);
    }

    public function pension_jiesuan()
    {
        $where=[
            'commission_type'=>5,
            'gzc'=>0,
            'status'=>1
        ];
        $bill_data=Db::name('user_bill')->where($where)->select()->toArray();
        $i=0;
        try {
            foreach ($bill_data as $k=>$v){
                $certification =Db::name('user_certification')->where('uid',$v['uid'])->find();
                if($certification) {
                    $online = ['uid' => $v['uid'], 'pay_type' => 1, 'order_sn' => $v['order_sn'], 'order_id' => $v['link_id']];
                    $certification = ['user_name' => $certification['user_name'],  'mobile'=>$certification['mobile'], 'user_card' => $certification['user_card']];
                    $res=$this->GZC($online, $certification, $v['number']);
                    if($res) {
                        Db::name('user_bill')->where('bill_id', $v['bill_id'])->update(['gzc' => 1]);
                        echo $v['bill_id'].'入账成功';
                        $i++;
                    }
                }else{
                    echo $v['uid'].'没有实名注册没有给到养老金';
                }
            }
        }catch (\Exception $exception){
            Db::name('log')->insert(['data'=>'公证处入账错误：'.$exception->getFile().'：'.$exception->getLine().'【'.$exception->getMessage().'】']);
        }
        return app('json')->success('成功处理'.$i.'条数据');
    }
    public function GZC($online,$certification,$pension)
    {
        $OrderMerchantRepository = app()->make(OrderMerchantRepository::class);
        $orderId = $OrderMerchantRepository->getNewOrderId('IN10');
        $OrderGzcRepository = app()->make(OrderGzcRepository::class);
        $create = [
            'uid' => $online['uid'],
            'platform_no' => $orderId,
            'account_type' => $online['pay_type'] == 1 ? 3 : 2,
            'user_name' => $certification['user_name'],
            'mobile' => $certification['mobile'],
            'user_card' => $certification['user_card'],
            'pension' => $pension,
            'order_type' => 2,
            'out_trade_no' => $online['order_sn']
        ];
        $test_user = Db::name('user') -> where('uid',$online['uid']) -> value('test_user');
        if($test_user == 0){
            $res = $OrderGzcRepository->create($create);
        }
//        $res=$OrderGzcRepository->create($create);
        return isset($res)?$res:false;
    }

    public function add_activation_code(){
        $phone = $this->request->param('phone');
        $num = $this->request->param('num');
        $uid = Db::name('user') -> where('account',$phone) -> value('uid');
        if(!$uid){
            return app('json')->fail('找不到用户');
        }
        $access = app() -> make(Access::class);
        $access -> add_activation_code($uid,$num);
    }

    public function refund_sxy_order_id(){
        $order_id = $this->request->param('order_id');
        $group_order = Db::name("store_order")
            ->alias('so')
            ->join('store_group_order sgo', 'so.group_order_id = sgo.group_order_id')
            ->where("so.order_id",$order_id)
            -> field("serialNumber,group_order_sn,mer_money,hf_pay_id,so.pay_price")
            -> find();

        $datas['requestId'] = ShouxinyiApiRequest::getOrderNumber('refund');    //订单号
        $datas['orderId'] = $group_order['serialNumber'];//交易订单的流水号
        $datas['isCollect'] = '1';
        $datas['amount'] = $group_order['pay_price'] * 100;//退款金额
        $datas['remark'] = '退款';

        $order_status=Db::name('store_split_order')->where('group_order_id',$group_order['group_order_sn'])->field('mid,status,subSplitRequestId,hf_pay_id,splitAmount')->select();
        if($order_status){
            $order_status=$order_status->toArray();
        }
        if($order_status && $order_status[0]['status']==1 && $order_status[1]['status']==1){
            //已分账退款（确认收货）
            $refundCollectDetail = [
                [
                    'collectAccType' => 'SPLIT_ACC',//归集类型 被分账方账户
                    'collectAmount' => bcmul ($group_order['mer_money'] , '100'),//归集金额
                    'subSplitRequestId'=>$order_status[0]['subSplitRequestId']
                ],
                [
                    'collectAccType' => 'SPLIT_ACC',//归集类型 被分账方账户
                    'collectAmount' => bcmul (bcsub($group_order['pay_price'],$group_order['mer_money'],2) , '100'),//归集金额
                    'subSplitRequestId'=>$order_status[1]['subSplitRequestId']
                ]
            ];
            $datas['refundCollectDetail'] = $refundCollectDetail;//归集信息
        }else{
            //未分账退款（未确认收货）
            $refundCollectDetail = array(
                'collectAccType' => 'WAIT_ACC',//归集类型
                'collectAmount' => $group_order['pay_price'] * 100,//归集金额
            );
            $datas['refundCollectDetail'] = [$refundCollectDetail];//归集信息
        }
        dump($datas);
        $sxyres = ShouxinyiApiRequest::refund($datas);
        dump($sxyres);
        if($sxyres['status'] != 'SUCCESS'){
            echo '退款失败';
        }
    }
    public function get_mp_access_token($name="WECHAT_MP")
    {

        if ($name == 'WECHAT_MP'){
            $appid = env('WECHAT_MP.APPID');
            $secret = env('WECHAT_MP.SECRET');
        }elseif ($name == 'WECHAT_TDYL'){
            $appid = env('WECHAT_TDYL.APPID');
            $secret = env('WECHAT_TDYL.SECRET');
        }else{
            return false;
        }
        $access_token = Cache::get("{$appid}_mp_access_token");
        if ($access_token)
            return $access_token;
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$secret}";
        $res = curlGet($url);
        Cache::set("{$appid}_mp_access_token", $res['access_token'], $res['expires_in']);
        return $res['access_token'];
    }
    public function getqrcode()
    {
        $data = $this->request->param('page');
        if($data['page'] == ''){
            return app('json')->success('参数为空');
        }

        $user = app()->make(\app\controller\merchant\user\User::class);
        $access_token = $this->get_mp_access_token();
        $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" . $access_token;

        $res = $user->posturl($url, $data);

        //判断是否是 json格式
        if (is_null(json_decode($res))) {
            $new_file = (int)(microtime(true) * 1000);
            $dir = iconv("UTF-8", "GBK", "./public/mpqrcode");
            if (!file_exists($dir)) {
                mkdir($dir, 0777, true);
            }
            $path = $dir . '/' . $new_file . ".jpg";
            file_put_contents($path, $res);
            $imgurl = env('APP_URL') . "/mpqrcode/" . $new_file . ".jpg";
            return app('json')->success(['qrcode' => $imgurl, 'path' => $path]);

        } else {
            //没有接收到数据流
            return false;
        }

    }

    public function user_visit_day_count()
    {
        $redis = Cache::store('redis')->handler();
        $number =  (int)$redis->get('user_visit_day');
        if($number){
            $userVisitDayRepository = app()->make(UserVisitDayRepository::class);
            $userVisitDayRepository->incrUserVisitDay(date('Y-m-d'),$number);
        }
        $ip_list =  $redis->lrange('user_visit', 0, -1);
        if (!empty($ip_list)) {
            foreach ($ip_list as $ip) {
                $userVisitRepository = app()->make(UserVisitRepository::class);
                if (empty($userVisitRepository->getWhere(['ip' => $ip]))) {
                    $userVisitRepository->addVisit(0, 'count', 0, '', $ip);
                }
            }
        }
        $redis->del('user_visit_day');
        $redis->del('user_visit');
        return $number;
    }
}

