<?php
/**
 * +------------------------------------------------------------
 * | 小程序 wechat/controller/Apps.php
 * +------------------------------------------------------------
 * | @author: bsh (844783437@qq.com)
 * | @create_time: 2018/5/28
 * +------------------------------------------------------------
 * | @copyright: CIM信息聚合系统 (https://cimxx.com)
 * +------------------------------------------------------------
 * | @last_modified_by: bsh
 * | @last_modified_time: 2018/5/28
 * +------------------------------------------------------------
 * | @todo:
 * +------------------------------------------------------------
 */

namespace app\wechat\controller;

use EasyWeChat\Factory;

class Apps extends Module
{
    protected $app;

    function initialize()
    {
        parent::initialize();
        $this->app = Factory::miniProgram($this->config['apps']);
    }

    /**
     * 根据code获取用户openid
     * @param string $code
     * @return \think\response\Json
     */
    function session($code = '')
    {
        $result = $this->app->auth->session($code);
        if (!empty($result['openid'])) {
            $attr = [
                'oauth_type' => 2,
                'openid' => $result['openid']
            ];
            $login = action('user/api/login', [2, $attr, 0]);
            if ($login['code'] == 1) {
                $login['data']['openid'] = $result['openid'];
                return json($login);
            } else {
                return json(['code' => 1, 'data' => ['openid' => $result['openid']]]);
            }
        } else {
            return json(['code' => 0, 'msg' => $result['errmsg']]);
        }
    }

    /**
     * @param int $width 小程序码宽度
     * @param string $page 扫码进入的页面
     * @param int $cache 缓存key
     * @param string $user_id 用户id
     * @return \think\response\Json
     */
    function qrcode($width = 200, $page = 'pages/third/third', $cache = 0, $user_id = '', $is_hyaline = false, $data_id = 0)
    {
        //小程序码存放路径
        $file_path = config('')['files']['path'] . DIRECTORY_SEPARATOR . 'apps' . DIRECTORY_SEPARATOR . 'qrcode';
        if (!empty($user_id)) {
            $dir = 'user';
            $key = $user_id;
        } else if (!empty($data_id)) {
            $dir = 'data';
            $key = $data_id;
        } else {
            $dir = 'login';
            $key = create_str();
        }
        $file_path .= DIRECTORY_SEPARATOR . $dir;
        if (!empty($user_id) || !empty($data_id)) {
            if (is_file($file_path . DIRECTORY_SEPARATOR . $key . '.png')) return json(['code' => 1, 'data' => $this->request->domain() . '/uploads/apps/qrcode/' . $dir . '/' . $key . '.png']);
        } else {
            //扫码登录小程序码
            if ($cache == 'apps_qrcode') cache($cache, null);
            $cache_key = 'apps_qrcode';
            $cache_data = cache($cache_key);
            if (!empty($cache_data) && empty($user_id)) {
                //同一ip有效期内只生成一个小程序码
                $ip_data = array_column($cache_data, null, 'ip');
                if (!empty($ip_data[self::$sys['ip']]) && $ip_data[self::$sys['ip']]['time'] > time()) return json(['code' => 1, 'data' => $ip_data[self::$sys['ip']]]);
            }
        }
        //生成二维码
        $qrcode = $this->app->app_code->getUnlimit($key, ['width' => $width, 'page' => $page, 'is_hyaline' => $is_hyaline]);
        //保存到文件
        $qrcode->save($file_path, $key . '.png');
        if (!empty($user_id) || !empty($data_id)) {
            $result = $this->request->domain() . '/uploads/apps/qrcode/' . $dir . '/' . $key . '.png';
        } else {
            //生成缓存
            $result = [
                'key' => $key,
                'time' => time() + 600,
                'ip' => self::$sys['ip'],
                'url' => $this->request->domain() . '/uploads/apps/qrcode/' . $dir . '/' . $key . '.png'
            ];
            if (empty($cache_data)) {
                $cache_data[] = $result;
            } else {
                //循环判断删除过期小程序码 todo 待优化
                foreach ($cache_data as $k => $v) {
                    if ($v['time'] < time()) {
                        //清理图片文件
                        @unlink($file_path . DIRECTORY_SEPARATOR . $v['key'] . '.png');
                        //删除缓存
                        unset($cache_data[$k]);
                    }
                }
                $cache_data = array_values($cache_data);
                $cache_data[] = $result;
            }
            cache($cache_key, $cache_data);
        }
        return json(['code' => 1, 'data' => $result]);
    }

    /**
     * 发送
     */
    public function message($message = '您好', $openid = '')
    {
        $service = $this->app->customer_service;
        $result = $service->message($message)->to($openid)->send();
    }

}
