<?php

/**
 * +------------------------------------------------------------
 * | 用户 user/controller/Api.php
 * +------------------------------------------------------------
 * | @author: bsh (844783437@qq.com)
 * | @create_time: 2018-04-28 19:14:25
 * +------------------------------------------------------------
 * | @copyright: CIM信息聚合系统 (https://cimxx.com)
 * +------------------------------------------------------------
 * | @last_modified_by: bsh
 * | @last_modified_time: 2018-04-28 19:14:25
 * +------------------------------------------------------------
 * | @todo:
 * +------------------------------------------------------------
 */

namespace app\user\controller;


use think\facade\Env;
use think\captcha\Captcha;
use think\Validate;
use think\Db;
use app\message\controller\Sms;
use app\message\controller\Mail;

class Api extends Module
{
    function read($attr = [])
    {
        if (!isset($attr['id']) && empty(session('user.id'))) {
            return json(['code' => 1000, 'msg' => '请登录...']);
        }
        return json($this->query($attr));
    }

    /**
     * 用户头像
     */
    function avatar($id)
    {
        $id = $id ?: session('user.id');
        $path = 'avatar/' . ceil($id / 10000) . '/' . $id . '.png';
        return action('files/api/_init_thumb', [$path, 1]) . '?rand=' . rand(1, 10000);
    }

    /**
     * 创建日志
     * @param array $ops
     */
    function log($event, $memo = '', $user_id = 0, $action = '')
    {
        if (empty($event) || (empty(session('user')) && empty($user_id)))
            return;
        $ops['event'] = $event;
        $ops['memo'] = $memo;
        $ops['admin_id'] = intval(session('admin.id'));
        $ops['user_id'] = session('user.id') ?: $user_id;
        $ops['module'] = self::$sys['module'];
        $ops['action'] = $action ?: self::$sys['action'];
        $ops['ip'] = self::$sys['ip'];
        $ops['port'] = input('server.REMOTE_PORT');
        $ops['os'] = get_client_os();
        $ops['browser'] = get_client_browser();
        $ops['create_time'] = time();
        return db('user_log')->insert($ops);
    }

    /**
     * 发送短信
     */
    function send_sms($type = '', $content = '', $phone = '', $gateways = [], $verify = '')
    {
        $sms = new Sms();
        $rule = [
            'type' => 'require',
            'phone' => 'require',
        ];
        $msg = [
            'type.require' => '短信类型不能为空',
            'phone.require' => '手机号不能为空'
        ];
        if (self::$sys['controller'] != 'admin') {
            $rule['verify'] = 'require';
            $msg['verify.require'] = '验证码不能为空';
        }
        $validate = new Validate($rule, $msg);
        $data = [
            'phone' => $phone,
            'verify' => $verify,
            'content' => $content,
            'type' => $type,
            'gateways' => $gateways
        ];
        if ($validate->check($data) !== true) {
            return json(['code' => 32001, 'msg' => $validate->getError()]);
        }
        return json($sms->phone($phone)->type($type)->gateways($gateways)->verify($verify)->send());
    }

    /**
     * 发送邮件
     */
    function send_email($attr = [], $return = 1)
    {
        if ($this->validate($attr, ['email' => 'require|email', 'type' => 'require']) !== true) {
            $result = ['code' => 32002, 'msg' => '请检查邮件格式'];
        } else {
            $mail = new Mail();
            $data = empty($attr['data']) ? '' : $attr['data'];
            $result = $mail->address($attr['email'])->type($attr['type'], $data)->send();
        }
        return $return ? json($result) : $result;
    }

    /**
     * 异步验证手机
     */
    public function check_phone($phone = '')
    {
        if (!request()->isAjax())
            halt('页面不存在');
        $where = array('phone' => $phone);
        $count = db('user')->where($where)->count();
        if ($count)
            echo '手机号已被注册，请更换。';
    }

    /**
     * 异步验证手机
     */
    public function check_email($email = '')
    {
        if (!request()->isAjax())
            halt('页面不存在');
        $where = array('email' => $email);
        $count = db('user')->where($where)->count();
        if ($count)
            echo '邮箱已被注册，请更换。';
    }

    /**
     * 异步验证用户名
     */
    public function check_name($name = '')
    {
        if (!request()->isAjax())
            halt('页面不存在');
        $where = ['name' => $name];
        if (db('user')->where($where)->count()) {
            echo '用户名已被注册，请更换。';
        }
    }

    /**
     * 异步验证手机
     */
    public function check_forget_phone($name = '')
    {
        if (!request()->isAjax())
            halt('页面不存在');
        $where = array('phone' => $name);
        $count = db('user')->where($where)->count();
        if (!$count)
            echo '该手机号未注册，请先注册。';
    }

    /**
     * 异步校验验证码
     */
    public function check_captcha($captcha = '')
    {
        if (!request()->isAjax())
            halt('页面不存在');
        if (!captcha_check($captcha)) {
            echo '您输入的验证码错误';
        }
    }

    /**
     * 异步验证身份证
     */
    public function check_id_card($id_card = '')
    {
        if (!request()->isAjax())
            halt('页面不存在');
        $where = array('id_card' => $id_card);
        $where['status'] = 3;
        $count = db('user_auth')->where($where)->count();
        if ($count)
            echo '该身份证已绑定用户';
    }

    /**
     * 统一注册接口
     * 参数：注册方式，注册数据
     */
    function register($type = '', $attr = [], $json = 1)
    {
        if (!empty($this->user_setting['close_register'])) {
            if (!empty($type) && !empty($attr)) {
                if (!empty($attr['email'])) {
                    if (db('user')->where('email', $attr['email'])->count()) {
                        $result = ['code' => 32003, 'msg' => '邮箱已被注册，请修改后重试...'];
                    }
                }
                if (!empty($attr['phone'])) {
                    if (db('user')->where('phone', $attr['phone'])->count()) {
                        $result = ['code' => 32004, 'msg' => '手机号已被注册，请修改后重试...'];
                    }
                }
                if (empty($result)) {
                    switch ($type) {
                        case 1:
                            $filter_result = filter_words($attr['name'], 'register', 'forbid');
                            if (empty($filter_result['level'])) {
                                if (db('user')->where('name', $attr['name'])->count('name')) {
                                    $result = ['code' => 32005, 'msg' => '用户名已被占用，请修正后重试..'];
                                } else {
                                    $status = 1;
                                    if (self::$sys['controller'] != 'admin') {
                                        if (!empty($this->user_setting['reg_phone_pc']) && !self::$sys['is_mobile']) {
                                            if (empty($attr['code']) || empty($attr['phone'])) {
                                                $status = 0;
                                                $result = ['code' => 32006, 'msg' => '请填写手机号、短信验证码'];
                                            }
                                            if (empty(cache($attr['phone'])) || cache($attr['phone'])['code'] != $attr['code'] || cache($attr['phone'])['time'] + 180 < time()) {
                                                $status = 0;
                                                $result = ['code' => 32007, 'msg' => '手机号验证码错误'];
                                            }
                                        } else {
                                            if (!empty($this->user_setting['reg_check'])) {
                                                if (empty($attr['captcha']) || !captcha_check($attr['captcha'])) {
                                                    $status = 0;
                                                    $result = ['code' => 32008, 'msg' => '验证码输入错误'];
                                                }
                                            }
                                        }
                                    }
                                    if ($status) {
                                        unset($attr['captcha']);
                                        //账号，邮箱，手机号注册
                                        $validate = validate('app\user\validate\Register');
                                        if ($validate->check($attr)) {
                                            $attr['pwd'] = md5($attr['pwd']);
                                            $attr['group_id'] = 1;
                                            $attr['status'] = 1;
                                            unset($attr['repwd'], $attr['agreed'], $attr['code'], $attr['verify']);
                                            if (!$id = db('user')->insertGetId($attr)) {
                                                $result = ['code' => 32009, 'msg' => '注册失败,请重试...'];
                                            } else {
                                                $result = ['code' => 1, 'msg' => '注册成功'];
                                            }
                                        } else {
                                            $result = ['code' => 0, 'msg' => $validate->getError()];
                                        }
                                    }
                                }
                            } else {
                                $result = ['code' => 32010, 'msg' => '包含敏感词【' . join(',', $filter_result['words']['3']) . '】，禁止注册'];
                            }
                            break;
                        case 2:
                            $msg = $this->validate($attr, ['type' => 'require', 'openid' => 'require'], ['type.require' => '请选择登录方式', 'openid.require' => '参数错误']);
                            if ($msg === true) {
                                $oauth = model('app\user\model\Oauth')->where('type', $attr['type'])->where('openid', $attr['openid'])->find();
                                if (empty($oauth)) {
                                    if (!empty($attr['name'])) {
                                        if (!empty(db('user')->where('name', '=', $attr['name'])->find())) $attr['name'] .= rand(1, 99999);
                                    }
                                    $user_data = [
                                        'name' => empty($attr['name']) ? '' : $attr['name'],
                                        'pwd' => empty($attr['pwd']) ? '' : pwd_md5($attr['name']),
                                        'email' => empty($attr['email']) ? '' : $attr['email'],
                                        'phone' => empty($attr['phone']) ? '' : $attr['phone'],
                                        'group_id' => 1,
                                        'status' => 1
                                    ];
                                    $id = db('user')->insertGetId($user_data);
                                    $oauth_data = [
                                        'user_id' => $id,
                                        'openid' => $attr['openid'],
                                        'type' => $attr['type'],
                                        'nickname' => empty($attr['name']) ? '' : $attr['name']
                                    ];
                                    db('user_oauth')->insert($oauth_data);
                                    $result = ['code' => 1, 'msg' => '注册成功'];
                                } else {
                                    $result = ['code' => 10001, 'msg' => '已注册，请直接登录...'];
                                }
                            } else {
                                $result = ['code' => 32011, 'msg' => '注册失败'];
                            }
                            break;
                        default :
                            $result = ['code' => 32012, 'msg' => '注册失败'];
                    }
                }
            } else {
                $result = ['code' => 32013, 'msg' => '注册失败'];
            }
        } else {
            $result = ['code' => 32014, 'msg' => '系统暂时关闭了注册，请稍后再来。'];
        }
        if (in_array($result['code'], [1, 10001])) {
            if ($result['code'] == 1) action('user/api/log', ['用户注册', '', $id, 'register']);
            $result['data'] = model('app\user\model\User')::with('register')->field('pwd', true)->where('id', $id)->find()->append(['login'])->toArray();
            $result['data']['token'] = get_token($result['data']);
            if ($result['code'] == 1) {
                session('user', $result['data']);
                //执行注册相关行为
                //注册赠送积分
                if (!empty($this->user_setting['register_credit'])) {
                    $credit = intval($this->user_setting['register_credit']);
                    $attr = [
                        'balance' => 1,
                        'money' => $credit,
                        'user_id' => $id,
                        'payment' => 4,
                        'type' => 0,
                        'memo' => '注册赠送【' . $credit . '】积分'
                    ];
                    //创建赠送积分订单
                    $order = action('finance/api/order', [$attr, 0]);
                    if ($order['code'] == 1) {
                        //进行支付
                        action('finance/api/credit', [['order' => $order['order']]]);
                    }
                }
            }
        }
        return $json ? json($result) : $result;
    }

    /**
     * 统一登录入口
     * 参数：类型，凭证
     * 类型：1，凭证：账号，密码
     * 类型：2，凭证：openid,oauth_type
     */
    function login($type = '', $attr = [], $json = 1)
    {
        if (!empty($type)) {
            if (in_array($type, [1, 4])) {
                //1:帐号密码登录用户
                //4:帐号密码登录管理员
                $status = 1;
                if ((!empty($this->user_setting['login_check']) && !self::$sys['is_mobile']) || $type == '4') {
                    if (empty($attr['captcha']) || !captcha_check($attr['captcha'])) {
                        $status = 0;
                    }
                }
                if (!$status) {
                    $result = ['code' => 32015, 'msg' => '验证码错误'];
                } else {
                    $msg = $this->validate($attr, ['name' => 'require', 'pwd' => 'require'], ['name.require' => '请填写用户名', 'pwd' => '请填写密码']);
                    if ($msg === true) {
                        $where['name'] = $attr['name'];
                        $where['pwd'] = pwd_md5($attr['pwd']);
                        $info = model('app\user\model\User')->with('register')->where($where)->field('pwd', true)->find();
                        if (!empty($info)) {
                            $result = ['code' => 1, 'msg' => '登录成功', 'data' => $info->append(['login'])->toArray()];
                        } else {
                            $result = ['code' => 32017, 'msg' => '用户不存在或密码错误'];
                        }
                    } else {
                        $result = ['code' => 32016, 'msg' => $msg];
                    }
                }
            } else if (in_array($type, [2, 5])) {
                //2:第三方凭证登录用户
                //5:第三方凭证登录管理员
                $msg = $this->validate($attr, ['openid' => 'require', 'oauth_type' => 'require'], ['openid.require' => '缺少登录凭证', 'oauth_type' => '登录凭证类型错误']);
                if ($msg === true) {
                    $oauth = model('app\user\model\Oauth');
                    $where['type'] = $attr['oauth_type'];
                    $where['openid'] = $attr['openid'];
                    $info = $oauth->where($where)->find();
                    if (!empty($info)) {
                        $user_id = $info['user_id'];
                        $info = model('app\user\model\User')->with('register')->where('id', $user_id)->find();
                        if (!empty($info)) {
                            $result = ['code' => 1, 'msg' => '登录成功', 'data' => $info->append(['login'])->toArray()];
                        } else {
                            $result = ['code' => 32018, 'msg' => '登录失败'];
                        }
                    } else {
                        $result = ['code' => 32019, 'msg' => '用户不存在'];
                    }
                } else {
                    $result = ['code' => 0, 'msg' => $msg];
                }
            } else if (in_array($type, [3])) {
                //3:使用已登录的用户身份登录管理员
                if (self::$user['id'] && !empty(self::$user['admin'])) {
                    $result = ['code' => 1, 'msg' => '登录成功', 'data' => self::$user];
                } else {
                    $result = ['code' => 32020, 'msg' => '管理员登录失败'];
                }
            } else {
                $result = ['code' => 32020, 'msg' => '用户登录失败'];
            }
        } else {
            $result = ['code' => 32020, 'msg' => '用户登录失败'];
        }
        if ($result['code'] == 1) {
            session('user', $result['data']);
            $admin = db('admin')->alias('a')->field('a.*, r.name role_name, r.power,r.status role_status')->join('__ADMIN_ROLE__ r', 'a.role_id=r.id', 'LEFT')->where('a.id', '=', $result['data']['id'])->find();
            $result['data']['admin'] = empty($admin) ? 0 : 1;
            if (in_array($type, [1, 2])) {
                action('user/api/log', ['用户登录', '', '', 'login']);
                //执行用户组相关行为
                $group = array_column($this->group(['id' => $info['group_id']]), null, 'id')[$info['group_id']];
                $allow_login = 1;
                if (!empty($group['setting'])) {
                    $group['setting'] = json_decode($group['setting'], 1);
                    if (isset($group['setting']['base']['allow_login']) && empty($group['setting']['base']['allow_login'])) $allow_login = 0;
                }
                if (empty($allow_login) || session('user.status') == 0) {
                    session('user', null);
                    $result = ['code' => 32021, 'msg' => '该用户禁止登录,请联系管理员....'];
                } else {
                    $result['data']['token'] = get_token($result['data']);
                    if (empty(session('user')['login']['create_time']) || session('user')['login']['create_time'] < strtotime(date('Y-m-d'))) {
                        //判断登录送积分
                        if (!empty($group['setting']->credit->login)) {
                            $credit = intval($group['setting']->credit->login);
                            $attr = [
                                'balance' => 1,
                                'money' => $credit,
                                'user_id' => $info['id'],
                                'type' => '0',
                                'payment' => '4',
                                'memo' => '登录赠送【' . $credit . '】积分'
                            ];
                            //创建赠送积分订单
                            $order = action('finance/api/order', [$attr, 0]);
                            if ($order['code'] == 1) {
                                //进行支付
                                action('finance/api/credit', [['order' => $order['order']]]);
                            }
                        }
                    }
                }
            } else {
                if (!empty($admin)) {
                    $status = 1;
                    if ($admin['role_id'] != 0) {
                        if ($admin['role_status'] != 1) {
                            $status = 0;
                            $result = ['code' => 32022, 'msg' => '管理员禁止登录'];
                        } else if (!empty($admin['allow_week']) && !in_array(date('w'), explode(',', $admin['allow_week']))) {
                            $status = 0;
                            $result = ['code' => 32023, 'msg' => '当前时间禁止登录'];
                        } else if (!empty($admin['allow_time']) && !in_array(date('H'), explode(',', $admin['allow_time']))) {
                            $status = 0;
                            $result = ['code' => 32023, 'msg' => '当前时间禁止登录'];
                        }
                    }
                    if ($status) {
                        db('admin')->where(['id' => $admin['id']])->update(['login_ip' => self::$sys['ip'], 'login_time' => time()]);
                        $admin['message_count'] = db('message')->where('admin_id', 'neq', 0)->where('status', '=', 1)->count();
                        $admin['avatar'] = $this->avatar($admin['id']);
                        $admin = array_merge($admin, get_array_keys($result['data'], 'name,pwd,email,qq,phone'));
                        session('admin', $admin);
                        $this->log('登录成功', '');
                        $result = ['code' => 1, 'msg' => '登录成功', 'data' => ''];
                    }
                } else {
                    $this->log('登录失败', '');
                    $result = ['code' => 32024, 'msg' => '登录失败'];
                }
            }
        }
        return $json ? json($result) : $result;
    }

    /**
     * 获得用户组
     * @param array $attr
     * @return \think\response\Json
     */
    function group($refresh = 0, $group_id = [], $status = [])
    {
        $key = 'user_group';
        if ($refresh) cache($key, null);
        if (!empty(cache($key))) {
            $rs = cache($key);
        } else {
            $group = model('app\user\model\Group');
            $rs = $group->select()->toArray();
            $config = include(Env::get('app_path') . 'user' . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'app.php');
            $sys_group = array_column($config['group'], null, 'id');
            if (!empty($rs)) {
                $rs = array_column((array)$rs, null, 'id');
                $rs = array_values(array_replace($sys_group, $rs));
            } else {
                $rs = $sys_group;
            }
            cache($key, $rs);
        }
        if (!empty($rs)) {
            $data = [];
            if (!empty($status)) {
                foreach ($rs as $k => $v) {
                    if (in_array($v['status'], (array)$status)) $data[] = $v;
                }
                $rs = $data;
            }
            if (!empty($group_id)) {
                foreach ($rs as $k => $v) {
                    if (in_array($v['id'], (array)$group_id)) $data[] = $v;
                }
                $rs = $data;
            }
        }
        return $rs;
    }

    /**
     * 验证码
     * @return \think\Response
     */
    function captcha()
    {
        $config = [
            'length' => 3,
            'codeSet' => '0123456789'
        ];
        $captcha = new Captcha($config);
        return $captcha->entry();
    }

    /*
     * 用户解绑手机号
     */
    function unbind_phone($attr = [], $return = 1)
    {
        $attr['user_id'] = self::$user['id'];
        $validate = $this->validate($attr, [
            'phone' => 'require|mobile',
            'user_id' => 'require',
        ], [
            'phone.require' => '手机号码不能为空',
            'user_id.require' => '请登录',
            'phone.mobile' => '手机号格式错误'
        ]);
        if ($validate === true) {
            if (db('user')->where('id', self::$user['id'])->where('phone', $attr['phone'])->find()) {
                db('user')->where('id', self::$user['id'])->update(['phone' => '']);
                $result = ['code' => 1, 'msg' => '手机解绑成功'];
                $this->log('解绑手机');
            } else {
                $result = ['code' => 32026, 'msg' => '输入手机号与源手机不符，请重新输入...'];
            }
        } else {
            $result = ['code' => 32025, 'msg' => $validate];
        }
        return $return ? json($result) : $result;
    }

    /**
     * 用户修改密码
     */
    function pwd($attr = [], $return = 1)
    {
        $attr['user_id'] = self::$user['id'];
        $validate = $this->validate($attr, [
            'pwd' => 'require',
            'user_id' => 'require',
            'newpwd' => 'require',
            're_newpwd' => 'confirm:newpwd'
        ], [
            'pwd.require' => '密码不能为空',
            'user_id.require' => '请登录',
            'newpwd.require' => '新密码不能为空',
            're_newpwd.confirm' => '两次输入密码不一致'
        ]);
        if ($validate === true) {
            $pwd = db('user')->where('id', '=', self::$user['id'])->value('pwd');
            if (pwd_md5($attr['pwd']) == $pwd) {
                db('user')->where('id', $attr['user_id'])->update(['pwd' => pwd_md5($attr['newpwd'])]);
                $result = ['code' => 1, 'msg' => '密码已更新，下次可使用新密码进行登录'];
                $this->log('修改密码');
            } else {
                $result = ['code' => 32027, 'msg' => '原密码不正确'];
            }
        } else {
            $result = ['code' => 32028, 'msg' => $validate];
        }
        return $return ? json($result) : $result;
    }

    /*
     * 解绑邮箱
     */
    public function unbind_email($attr = [], $return = 1)
    {
        $attr['user_id'] = self::$user['id'];
        $validate = $this->validate($attr, [
            'email' => 'require|email',
            'user_id' => 'require',
        ], [
            'email.require' => '邮箱不能为空',
            'user_id.require' => '请登录',
            'email.email' => '邮箱格式错误'
        ]);
        if ($validate === true) {
            if (db('user')->where('id', self::$user['id'])->where('email', $attr['email'])->find()) {
                db('user')->where('id', self::$user['id'])->update(['email' => '']);
                $result = ['code' => 1, 'msg' => '邮箱解绑成功'];
                $this->log('解绑邮箱');
            } else {
                $result = ['code' => 32030, 'msg' => '输入邮箱与原邮箱不符，请重新输入...'];
            }
        } else {
            $result = ['code' => 32029, 'msg' => $validate];
        }
        return $return ? json($result) : $result;
    }

    /*
     * 用户绑定手机号
     */
    function bind_phone($attr = [], $return = 1)
    {
        $attr['user_id'] = self::$user['id'];
        $validate = $this->validate($attr, [
            'phone' => 'require|mobile',
            'user_id' => 'require',
            'code' => 'require'
        ], [
            'phone.require' => '手机号不能为空',
            'user_id.require' => '请登录',
            'phone.mobile' => '手机格式错误'
        ]);
        if ($validate === true) {
            if (empty(cache($attr['phone'])) || $attr['code'] != cache($attr['phone'])['code'] || cache($attr['phone'])['time'] + 180 < time()) {
                $result = ['code' => 32032, 'msg' => '手机验证码错误'];
            } else {
                db('user')->where('id', session('user.id'))->update(['phone' => $attr['phone']]);
                $log = db('user_log')->where('user_id', '=', $attr['user_id'])->where('action', '=', 'bind_phone')->count();
                if (empty($log)) {
                    if (!empty($this->user_setting['bind_phone_credit'])) {
                        $credit = intval($this->user_setting['bind_phone_credit']);
                        $attr = [
                            'balance' => 1,
                            'money' => $credit,
                            'user_id' => $attr['user_id'],
                            'payment' => 4,
                            'type' => 0,
                            'memo' => '绑定手机号赠送【' . $credit . '】积分'
                        ];
                        //创建赠送积分订单
                        $order = action('finance/api/order', [$attr, 0]);
                        if ($order['code'] == 1) {
                            //进行支付
                            action('finance/api/credit', [['order' => $order['order']]]);
                        }
                    }
                }
                $this->log('绑定手机号');
                $result = ['code' => 1, 'msg' => '手机号绑定成功'];
            }
        } else {
            $result = ['code' => 32031, 'msg' => $validate];
        }
        return $return ? json($result) : $result;
    }

    /**
     * 生成二维码
     */
    function qr_code($content = '')
    {
        $text = urldecode($content);
        include(Env::get('extend_path') . 'Qrcode.php');
        $qrcode = new \QRcode();
        return response($qrcode->png($text, false, QR_ECLEVEL_L, $size = 8, $margin = 2, false))->header(['Content-type' => 'image/png']);
    }

    /**
     * 根据扫码信息返回用户信息
     */
    function qrcode_user($key = '', $token = '', $ticket = '')
    {
        if (!empty($ticket)) {
            $cache_data = cache($ticket);
            if (!empty($cache_data)) {
                if (isset($cache_data['code']) && $cache_data['code'] == 1) session('user', $cache_data['data']);
                return json($cache_data);
            }
            return json(['code' => 32033, 'msg' => '数据不存在']);
        }
        if (empty($key)) return json(['code' => 32034, 'msg' => '参数错误']);
        $cache_data = cache('apps_qrcode');
        if (empty($cache_data)) return json(['code' => 32035, 'msg' => '非法操作']);
        $cache_data = array_column($cache_data, null, 'key');
        if (empty($cache_data[$key]) || $cache_data[$key]['time'] < time()) return json(['code' => 32036, 'msg' => '二维码已失效']);
        if (!empty($token)) {
            $user = cache($token);
            if (!empty($user)) {
                cache($key, $user);
                return json(['code' => 1, 'msg' => '用户登录成功']);
            } else {
                return json(['code' => 32037, 'msg' => '用户不存在']);
            }
        }
        if (!empty(cache($key))) {
            session('user', cache($key));
            //清除缓存数据
            cache($key, null);
            return json(['code' => 1, 'msg' => '登录成功']);
        } else {
            return json(['code' => 32038, 'msg' => '登录失败']);
        }
    }

    /**
     * 筛选项
     */
    function filters($attr = [])
    {
        $rs = [];
        isset($attr['where']) && $rs['where'] = $attr['where'];
        $rs['order'] = 'hits desc';
        if (isset($attr['area_id'])) {
            $areas = load_areas(1);
            if (!empty($areas[$attr['area_id']]['child'])) {
                $area_ids = array_merge([$attr['area_id']], array_keys($areas[$attr['area_id']]['child']));
                $rs['where'][] = ['area_id', 'in', $area_ids];
            } else {
                $rs['where'][] = ['area_id', '=', $attr['area_id']];
            }
        }
        if (isset($attr['keywords'])) $where[] = ['name', 'like', '%' . $attr['keywords'] . '%'];
        return $rs;
    }

    /**
     * 收藏、点赞
     */
    function like($type = '', $to_user_id = '', $user_id = 0, $data_id = 0)
    {
        if (request()->isPost()) {
            if (empty(self::$user['id'])) return json(['code' => 1000, 'msg' => '请登录...']);
            $data = [
                'user_id' => self::$user['id'],
                'type' => $type,
                'to_user_id' => $to_user_id,
                'data_id' => $data_id,
                'create_time' => time()
            ];
            $message = config('app.like_type')[$data['type']];
            $where = [
                ['type', '=', $data['type']],
                ['user_id', '=', self::$user['id']],
                ['to_user_id', '=', $data['to_user_id']],
                ['data_id', '=', $data_id]
            ];
            if (self::$sys['is_mobile']) {
                $os = get_client_os();
                if ($os == 'miniapp') {
                    $data['os'] = '3';
                } else if ($os == 'wechat') {
                    $data['os'] = '2';
                } else {
                    $data['os'] = '1';
                }
            } else {
                $data['os'] = '0';
            }
            $like = db('like')->where($where)->find();
            if (!empty($like)) {
                if (!empty($data['data_id'])) {
                    db('like')->where($where)->delete();
                    return json(['code' => 1, 'msg' => '已取消' . $message]);
                } else {
                    if ($like['delete_time'] == 0) {
                        Db::name('like')->where($where)->useSoftDelete('delete_time', time())->delete();
                        return json(['code' => 1, 'msg' => '已取消' . $message]);
                    } else {
                        db('like')->where($where)->setField('delete_time', 0);
                        return json(['code' => 1, 'msg' => '已' . $message]);
                    }
                }
            } else {
                db('like')->insert($data);
                return json(['code' => 1, 'msg' => '已' . $message]);
            }
        }
        if (request()->isGet()) {
            $user_id = $user_id ?: self::$user['id'];
            if (!$user_id || !$type) return json(['code' => 32039, 'msg' => '参数错误']);
            $where[] = ['type', '=', $type];
            $where[] = ['user_id', '=', $user_id ?: self::$user['id']];
            $data = model('like')->with('item')->where($where)->paginate()->toArray();
            $rs['code'] = 1;
            $rs['data'] = $data;
            return json($rs);
        }
    }


    /**
     * 登录
     */
    public function admin_login($user = '', $pwd = '', $captcha = '')
    {
        if (!empty($user) && !empty($pwd) && !empty($captcha)) {
            if (!captcha_check($captcha)) {
                return json(['code' => 0, 'msg' => '验证码错误']);
            }
            $user = model('app\user\model\User')->with('register')->where('name', '=', $user)->where('pwd', '=', md5($pwd))->field('pwd', true)->find();
        }
        if (self::$user['id']) {
            $user = model('app\user\model\User')->with('register')->where('id', '=', self::$user['id'])->field('pwd', true)->find();
        }
        if (!empty($user)) {
            $user = $user->append(['login'])->toArray();
            $rs = db('admin')->alias('a')->field('a.*, r.name role_name, r.power,r.status role_status')->join('__ADMIN_ROLE__ r', 'a.role_id=r.id', 'LEFT')->where('a.id', '=', $user['id'])->find();
            if (empty($rs)) return json(['code' => 0, 'msg' => '管理员不存在']);
            if ($rs['role_id'] != 0) {
                if ($rs['role_status'] != 1) return json(['code' => 0, 'msg' => '管理员禁止登录']);
                if (!empty($rs['allow_week']) && !in_array(date('w'), explode(',', $rs['allow_week']))) return json(['code' => 0, 'msg' => '当前时间禁止登录']);
                if (!empty($rs['allow_time']) && !in_array(date('H'), explode(',', $rs['allow_time']))) return json(['code' => 0, 'msg' => '当前时间禁止登录']);
            }
            db('admin')->where(['id' => $rs['id']])->update(['login_ip' => self::$sys['ip'], 'login_time' => time()]);
            $rs['message_count'] = db('message')->where('admin_id', 'neq', 0)->where('status', '=', 1)->count();
            $rs = array_merge($rs, get_array_keys($user, 'name,pwd,email,qq,phone'));
            session('admin', $rs);
            session('user', $user);
            $this->admin_log('登录成功', '');
            return json(['code' => 1, 'msg' => '登录成功', 'data' => $rs]);
        } else {
            $this->admin_log('登录失败', '用户名: ' . $user . '密码: ' . $pwd);
            return json(['code' => 0, 'msg' => '登录失败']);
        }
    }

    /**
     * 创建日志
     */
    public function admin_log($event, $memo = '')
    {
        if (empty($event)) return;
        $ops['event'] = $event;
        $ops['memo'] = $memo;
        $ops['admin_id'] = intval(session('admin.id'));
        $ops['module'] = self::$sys['module'];
        $ops['action'] = self::$sys['action'];
        $ops['ip'] = self::$sys['ip'];
        $ops['os'] = get_client_os();
        $ops['browser'] = get_client_browser();
        $ops['create_time'] = time();
        return db('admin_log')->insert($ops);
    }

    /**
     * 退出
     */
    function logout()
    {
        if (session('admin.id')) $this->log('注销');
        session('admin', null);
        return json(['code' => 1, 'msg' => '退出成功']);
    }

    /**
     * 编辑用户信息
     */
    public function info()
    {
        if (!self::$user['id']) return json(['code' => 1000, 'msg' => '请登录']);
        if (self::$sys['method'] == 'post') {
            $data = get_array_keys(input('post.'), 'address,qq,mappoint,fields');
            if (!empty($data['fields'])) {
                //处理自定义字段
                $fields = load_fields(self::$user['group_id'], 0, '', '', 'user');
                if (!empty($fields)) {
                    foreach ($fields as $k => $v) {
                        if (isset($data['fields'][$v['key']])) {
                            if (!empty($v['required']) && $data['fields'][$v['key']] == '') return ['code' => 0, 'msg' => '扩展属性【' . $v['name'] . '】不能为空'];
                            if ($v['type'] == 2 && !is_array($data['fields'][$v['key']])) return ['code' => 0, 'msg' => '扩展字段【' . $v['name'] . '】数据格式错误'];
                            in_array($v['type'], [1, 3]) && $data['fields'][$v['key']] = (string)$data['fields'][$v['key']];
                        }
                    }
                }
            } else {
                unset($data['fields']);
            }
            model('user')->where('id', '=', self::$user['id'])->update($data);
            session('user', array_merge(session('user'), $data));
            return json(['code' => 1, 'msg' => '用户信息修改成功']);
        }
    }

}
