<?php

/**
 * +------------------------------------------------------------
 * | 数据-接口 (index/controller/Api.php)
 * +------------------------------------------------------------
 * | @author: zhx (10630650@qq.com)
 * | @create_time: 2018-03-09 22:56:48
 * +------------------------------------------------------------
 * | @copyright: CIM信息聚合系统 (https://cimxx.com)
 * +------------------------------------------------------------
 * | @last_modified_by: zhx
 * | @last_modified_time: 2018-03-09 22:56:48
 * +------------------------------------------------------------
 * | @todo:
 * +------------------------------------------------------------
 */

namespace app\index\controller;

use think\facade\Hook;
use app\index\model\Data;
use think\Db;
use think\facade\Env;

class Api extends Module
{

    public function phone_image($id)
    {
        $rs = model('info')->where('data_id', $id)->value('phone');
        if (empty($rs)) return;
        $width = strlen($rs) * 15;
        $height = 30;
        $font = \Env::get('app_path') . 'phone.ttf';
        $im = @imagecreate($width, $height) or die("Cannot Initialize new GD image stream");
        $background_color = imagecolorallocate($im, 255, 255, 255);
        $grey = imagecolorallocate($im, 128, 128, 128);
        $text_color = imagecolorallocate($im, mt_rand(0, 200), mt_rand(0, 120), mt_rand(0, 120));
        // 画干扰线     
        for ($i = 0; $i < 5; $i++) {
            $font_color = imagecolorallocate($im, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
            imagearc($im, mt_rand(-$width, $width), mt_rand(-$height, $height), mt_rand(30, $width * 2), mt_rand(20, $height * 2), mt_rand(0, 360), mt_rand(0, 360), $font_color);
        }
        // 画干扰点     
        for ($i = 0; $i < 50; $i++) {
            $font_color = imagecolorallocate($im, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
            imagesetpixel($im, mt_rand(0, $width), mt_rand(0, $height), $font_color);
        }
        imagettftext($im, 16, 0, 5, 21, $grey, $font, $rs);
        imagettftext($im, 16, 0, 5, 21, $text_color, $font, $rs);
        ob_start();
        imagepng($im);
        $content = ob_get_clean();
        imagedestroy($im);

        return response($content, 200, ['Content-Length' => strlen($content)])->contentType('image/png');
    }

    /**
     * 读取
     */
    public function read($attr = [])
    {
        is_string($attr) && $attr = \json_decode($attr, true);
        $filter = $this->filters($attr);
        isset($filter['order']) && $attr['order'] = $filter['order'];
        isset($filter['where']) && $attr['where'] = $filter['where'];
        if (!isset($attr['id']) && isset($attr['cid'])) {
            $column = load_column($attr['cid']);
            if (empty($column)) return;
            $attr['cid'] = $column['id'];
            $attr['key'] = $column['key'];
        }
        $attr['where'][] = ['delete_time', '=', 0];
        if (isset($attr['top'])) {
            if ($attr['top'] == 1) $attr['where'][] = ['top_end_time', '>', time()];
            if ($attr['top'] == 0) $attr['where'][] = ['top_end_time', '<', time()];
        }
        //非管理员身份
        if (empty(self::$user['admin'])) {
            $attr['where'][] = ['status', '=', 1];
            if ((isset($attr['id']) || isset($attr['cid']))) $this->check_login();
        } else {
            $attr['order'] = 'status asc' . (isset($attr['order']) ? (',' . $attr['order']) : '');
        }
        $rs = $this->query($attr);
        if (!empty($rs)) {
            $rs = $this->_init_data($rs, (isset($attr['form']) ? 1 : 0));
            if (isset($attr['id'])) {
                $rs['hits'] = $this->hits($rs['id']);
                $rs['like'] = 0;
                $rs['fav'] = 0;
                if (isset($attr['share_key']) && isset($attr['user_id'])) $this->share_redpack($attr, $rs);
                if (self::$user['id']) {
                    $count = db('like')->where('user_id', '=', self::$user['id'])->where('type', 'in', ['like', 'fav'])->where('data_id', '=', $attr['id'])->column('*', 'type');
                    $rs['like'] = empty($count['like']) ? 0 : 1;
                    $rs['fav'] = empty($count['fav']) ? 0 : 1;
                }
            }
        }
        return json($rs);
    }

    /**
     * 处理分享红包
     */
    private function share_redpack($attr, $rs)
    {
        //分享红包行为处理
        $behavior = db('data_behavior')->where('key', '=', $attr['share_key'])->find();
        if (!empty($behavior)) {
            $extend = json_decode($behavior['extend'], 1);
            if ($extend[0]['type']) {
                //随机红包
                $extend[0]['rand'] = array_values($extend[0]['rand']);
                if (empty($extend[0]['rand'][0])) return '';
                $money = $extend[0]['rand'][0];
            } else {
                //等额红包
                $money = $extend[0]['money'] / $extend[0]['num'];
            }
            if ($extend[0]['balance'] > 0 && $extend[0]['balance'] >= $money) {
                $where = [
                    ['ip', '=', self::$sys['ip']],
                    ['memo', '=', $attr['id'] . '+' . $attr['share_key']]
                ];
                $log = db('user_log')->where($where)->find();
                if (empty($log)) {
                    //增加分享人余额
                    $order = action('finance/api/order', [
                        [
                            'payment' => 4,
                            'money' => $money,
                            'balance' => 1,
                            'type' => 1,
                            'memo' => '分享红包获得余额',
                            'user_id' => $attr['user_id'],
                            'extend' => [
                                'key' => $attr['share_key']
                            ]
                        ], 0
                    ]);
                    if ($order['code'] == 1) action('finance/api/pay', [['order' => $order['order']]]);
                    //减少红包余额
                    $extend[0]['balance'] -= $money;
                    //随机红包，删除红包队列
                    if ($extend[0]['type'] == 1) {
                        unset($extend[0]['rand'][0]);
                        if (empty($extend[0]['rand'])) unset($extend[0]['rand']);
                    }
                    db('data_behavior')->where('key', '=', $attr['share_key'])->update(['extend' => json_encode($extend)]);
                    if ($extend[0]['balance'] == 0) {
                        if (!empty($rs['behavior'])) {
                            $data_behavior = '';
                            foreach ($rs['behavior'] as $k => $v) {
                                if ($v['key'] != $attr['share_key']) $data_behavior[] = $v;
                            }
                            db('data')->where('id', '=', $attr['id'])->update(['behavior' => empty($data_behavior) ? '' : json_encode($data_behavior)]);
                        }
                    }
                    //增加日志记录
                    action('user/api/log', ['分享红包', $attr['id'] . '+' . $attr['share_key'], $attr['user_id']]);
                }
            }
        }
    }

    /**
     * 发布
     */
    public function add($id = 0)
    {   
        if (empty(self::$column)) {
            return json(['code' => 12009, 'msg' => '未找到目标栏目']);
        }else{
            if (self::$column['setting']['group'][self::$user['group_id']]['add_limit'] < 0) {
                return json(['code' => 12001, 'msg' => '您暂时不能在《' . self::$column['name'] . '》发布信息。']);
            }
        }
        if (request()->isPost()) {
            $data = request()->except(['create_time', 'update_time']);
            if (isset($data['captcha'])) {
                if (empty($data['captcha']) || !captcha_check($data['captcha'])) $this->error([
                    'msg' => '图片验证码错误',
                    'code' => 12010
                ]);
            }
            if (!$id) $data['id'] = 0;
            $data['column_id'] = self::$column['id'];
            if (!empty(self::$column['setting']['check']['post_phone_mobile']) || !empty(self::$cim['post_phone_mobile'])) {
                //验证短信验证码
                if (empty($data['code']) || empty($data['phone'])) return json(['code' => 12002, 'msg' => '请填写手机号、短信验证码']);
                if (empty(cache($data['phone'])) || cache($data['phone'])['code'] != $data['code'] || cache($data['phone'])['time'] + 180 < time()) return json(['code' => 12003, 'msg' => '手机号验证码错误']);
                unset($data['code'], $data['verify']);
            }
            if (!empty($data['image']) || !empty(request()->file())) {
                $upload_limit = self::$column['setting']['group'][self::$user['group_id']]['upload_limit'] ?? 3;
                $count = 0;
                if (!empty($data['image'])) $count += count($data['image']);
                if (!empty(request()->file())) {
                    if (count(request()->file()) == count(request()->file(), 1)) {
                        $count += count(request()->file());
                    } else {
                        $count += (count(request()->file(), 1) - count(request()->file()));
                    }
                }
                if ($count > $upload_limit) return json(['code' => 12004, 'msg' => '上传图片数量超出系统限制,超出数量:' . ($count - $upload_limit)]);
            }
            $rs = $this->_add($data);
            if ($id) $rs['data'] = db('data')->where('id', '=', $id)->find();
            return json($rs);
        } else {
            $rs['step'] = 1;
            if (!empty(self::$column)) {
                if (input('param.id')) {
                    $rs['step'] = 3;
                } else {
                    $rs['step'] = 2;
                    $before = $this->before_add();
                    if (!empty($before)) return json(['code' => 0, 'msg' => $before['msg']]);
                    $rs['upload_limit'] = self::$column['setting']['group'][self::$user['group_id']]['upload_limit'] ?? 3;
                    $rs['fields'] = load_fields(self::$column['id'], 0, '', 1);
                    $rs['post_phone_mobile'] = (empty(self::$column['setting']['check']['post_phone_mobile']) && empty(self::$cim['post_phone_mobile'])) ? 0 : 1;
                }
                if (self::$column['model'] == 'info') $rs['areas'] = \load_areas();
            }
            $rs['columns'] = action('api/columns', ['use' => 'form', 'return' => 0]);
            if (!empty($rs['columns'])) {
                foreach ($rs['columns'] as $k => $v) {
                    unset($rs['columns'][$k]['setting'], $rs['columns'][$k]['create_time'], $rs['columns'][$k]['update_time'], $rs['columns'][$k]['list_order'], $rs['columns'][$k]['status']);
                    if (!empty($v['child'])) {
                        foreach ($v['child'] as $kk => $vv) unset($rs['columns'][$k]['child'][$kk]['setting'], $rs['columns'][$k]['child'][$kk]['create_time'], $rs['columns'][$k]['child'][$kk]['update_time'], $rs['columns'][$k]['child'][$kk]['list_order'], $rs['columns'][$k]['child'][$kk]['status']);
                    }
                }
            }
            return json($rs);
        }
    }

    /**
     * 栏目
     */
    public function columns($tree = 0, $refresh = 0, $key = 'key', $id = '', $use = '', $return = 1, $child = 0, $model = [])
    {
        if ($use == 'form') {
            $rs = $this->allow_post_columns();
        } else {
            if ($id) {
                $rs = load_column($id, $child);
                if (!empty($rs)) $rs['fields'] = load_fields($rs['id']);
            } else {
                $rs = \load_columns([
                    'tree' => $tree,
                    'refresh' => $refresh,
                    'key' => $key,
                    'model' => $model,
                    'count' => 1
                ]);
            }
        }
        if ($return) {
            return $id ? json($rs) : json(array_values($rs));
        } else {
            return $rs;
        }
    }


    public function hits($id)
    {
        db('data')->where('id', $id)->setInc('hits', 1);
        return db('data')->where('id', $id)->value('hits');
    }

    /**
     * 举报
     */
    public function report()
    {
        if (request()->isPost()) {
            $data = input('post.');
            $result = $this->validate($data, 'app\index\validate\Report');
            if (true !== $result) {
                return json(['code' => 0, 'msg' => $result]);
            }
            if (!empty(self::$user['id'])) {
                $data['user_id'] = self::$user['id'];
                //action('user/api/log', [$this->_module['report_type'][$data['module']] . '举报', '举报']);
            }
            $data['ip'] = self::$sys['ip'];
            model('report')->allowField(true)->save($data);
            $info = model('app\index\model\Data')->get($data['data_id']);
            $attr = [
                'content' => '用户举报信息【' . $info['name'] . '】:' . config('app.report')[$data['type']],
                'extend' => $data,
                'admin_id' => 1
            ];
            action('message/api/send', [$attr]);
            return json(['code' => 1, 'msg' => '举报成功']);
        } else {
            return json(['code' => 12005, 'msg' => '举报失败']);
        }
    }

    private function allow_post_columns()
    {
        $data = [];
        foreach (self::$columns as $k => $v) {
            if (!in_array($v['model'], ['article', 'info', 'phone'])) continue;
            if (isset($v['setting']['group'][self::$user['group_id']]) && $v['setting']['group'][self::$user['group_id']]['add_limit'] > -1) $data[$k] = $v;
        }
        return array_to_tree($data);
    }

    /**
     * 提交反馈信息
     */
    function feedback()
    {
        if (request()->isPost()) {
            $data = input('post.');
            if (!self::$sys['is_mobile']) {
                if (empty($data['captcha']) || !captcha_check($data['captcha'])) return json(['code' => 12006, 'msg' => '验证码错误']);
            }
            $result = $this->validate($data, [
                'title' => 'require',
                'content' => 'require'
            ], [
                'title.require' => '反馈标题不能为空',
                'content.require' => '反馈内容不能为空'
            ]);
            if ($result !== true) return json(['code' => 12007, 'msg' => '反馈内容不能为空']);
            if (session('user . id')) {
                $data['user_id'] = session('user.id');
            } else {
                if (!empty($data['linkway'])) {
                    $user_id = model('app\user\model\User')->where('phone|email', '=', $data['linkway'])->value('id');
                    if ($user_id) $data['user_id'] = $user_id;
                }
            }
            $id = model('app\index\model\Feedback')->data($data)->allowField(true)->save();
            $message = [
                'content' => "收到用户反馈的问题:" . $data['title'],
                'admin_id' => 1,
                'extend' => [
                    'id' => $id,
                    'action' => 'feedback'
                ]
            ];
            action('message/api/send', [$message]);
            return json(['code' => 1, 'msg' => '保存成功，感谢您的反馈...']);
        }
    }

    /**
     * 关闭信息
     */
    function close($id = 0, $key = '')
    {
        $data = Data::get($id);
        if ($this->check_power($data, $key)) {
            db('data')->where('id', $id)->setField('status', -1);
        }
        return json(['code' => 1, 'msg' => '关闭成功']);
    }

    /**
     * 信息取消置顶
     * @param int $id 信息id
     * @param string $key 凭证key
     * @return \think\response\Json
     */
    public function cancel_top($id = 0, $key = '')
    {
        $data = Data::get($id);
        if ($this->check_power($data, $key)) {
            db('data')->where('id', '=', $id)->setField('top_end_time', 0);
        }
        return json(['code' => 1, 'msg' => '取消置顶成功']);
    }

    /**
     * 刷新
     */
    public function refresh($id = 0, $payment = '', $return = 1, $currency = '')
    {
        $credit = empty(self::$column['setting']['group'][self::$user['group_id']]['refresh_credit']) ? 0 : self::$column['setting']['group'][self::$user['group_id']]['refresh_credit'];
        $money = empty(self::$column['setting']['group'][self::$user['group_id']]['refresh_money']) ? 0 : self::$column['setting']['group'][self::$user['group_id']]['refresh_money'];
        //线上支付
        if (in_array($payment, [2, 3])) {
            //创建订单
            $order = [
                'payment' => $payment,
                'money' => $money,
                'balance' => 0,
                'type' => 1,
                'behavior' => 'refresh',
                'extend' => [
                    'id' => $id,
                ]
            ];
            $order = action('finance/api/order', [$order, 0]);
            if ($order['code'] == 1) {
                $result = ['code' => 2, 'msg' => '订单创建成功', 'order' => $order['order']];
            } else {
                $result = ['code' => 12008, 'msg' => '订单创建失败，请重试'];
            }
        } else {
            //账号支付
            Db::startTrans();
            $result = $this->handle_info('refresh', $money, $credit, (($currency === '') ? $payment : $currency));
            if ($result['code'] == 1 && Db::name('data')->where('id', $id)->update(['update_time' => time()])) {
                Db::commit();
                $result = ['code' => 1, 'msg' => '刷新成功'];
            } else {
                Db::rollback();
                $result = ['code' => $result['code'], 'msg' => $result['msg']];
            }
        }
        return $return ? json($result) : $result;
    }

    /**
     * 置顶
     */
    function top($id = 0, $days = 0, $payment = '', $return = 1, $currency = '')
    {
        if (!is_numeric($days) || $days <= 0) {
            $result = ['code' => 12010, 'msg' => '置顶天数必须大于0'];
        } else {
            if (empty(self::$column)) return json(['code' => 12011, 'msg' => '获取信息失败']);
            $credit = intval(self::$column['setting']['group'][self::$user['group_id']]['top_credit']) * $days;
            $money = intval(self::$column['setting']['group'][self::$user['group_id']]['top_money']) * $days;
            //线上支付
            if (in_array($payment, [2, 3])) {
                //创建订单
                $order = [
                    'payment' => $payment,
                    'money' => $money,
                    'balance' => 0,
                    'type' => 1,
                    'behavior' => 'top',
                    'extend' => [
                        'id' => $id,
                        'days' => $days
                    ]
                ];
                $order = action('finance/api/order', [$order, 0]);
                if ($order['code'] == 1) {
                    $result = ['code' => 2, 'msg' => '订单创建成功', 'order' => $order['order']];
                } else {
                    $result = ['code' => 12012, 'msg' => $order['msg']];
                }
            } else {
                //账号支付
                Db::startTrans();
                $result = $this->handle_info('top', $money, $credit, ($currency === '') ? $payment : $currency);
                if ($result['code'] == 1) {
                    $info = Db::name('data')->where('id', $id)->find();
                    if (!empty($info)) {
                        $top_end_time = $info['top_end_time'];
                        if ($top_end_time < time()) $top_end_time = time();
                        $data['top_end_time'] = $top_end_time + $days * 86400;
                        $rs = Db::name('data')->where('id', $id)->update($data);
                        if ($rs) $top_end_status = 1;
                    }
                    if (!empty($top_end_status)) {
                        Db::commit();
                        $result = ['code' => 1, 'msg' => '置顶成功'];
                    } else {
                        Db::rollback();
                        $result = ['code' => 12013, 'msg' => '置顶失败'];
                    }
                } else {
                    Db::rollback();
                    $result = ['code' => $result['code'], 'msg' => $result['msg']];
                }
            }
        }
        return $return ? json($result) : $result;
    }


    /**
     * 信息加红包
     */
    function redpack($id = 0, $money = 0, $num = 0, $payment = '', $type = '', $return = 1)
    {
        if (is_numeric($money) && $money > 0) {
            if (!$id || !$num || $type == '') return json(['code' => 12015, 'msg' => '请设置红包数量和红包类型']);
            if (in_array($payment, [2, 3])) {
                include(Env::get('extend_path') . 'Redpack.php');
                $redpack = new \Redpack(['money' => $money, 'num' => $num]);
                if (!$redpack->isCanBuilder()) return json(['code' => 12016, 'msg' => '红包均值小于0.01']);
                //创建订单
                $order = [
                    'payment' => $payment,
                    'money' => $money,
                    'balance' => 0,
                    'type' => 1,
                    'behavior' => 'redpack',
                    'memo' => '信息分享红包',
                    'extend' => [
                        'id' => $id,
                        'num' => $num,
                        'type' => $type
                    ]
                ];
                $order = action('finance/api/order', [$order, 0]);
                if ($order['code'] == 1) {
                    $result = ['code' => 2, 'msg' => '订单创建成功', 'order' => $order['order']];
                } else {
                    $result = ['code' => 12017, 'msg' => $order['msg']];
                }
            } else {
                Db::startTrans();
                try {
                    $result = $this->handle_info('redpack', $money, 0, 1);
                    if ($result['code'] == 1) {
                        //执行行为
                        Hook::exec('app\\index\\behavior\\Redpack', [
                            'id' => $id,
                            'num' => $num,
                            'type' => $type,
                            'money' => $money
                        ]);
                        Db::commit();
                    } else {
                        Db::rollback();
                        $result = ['code' => $result['code'], 'msg' => $result['msg']];
                    }
                } catch (\Exception $e) {
                    Db::rollback();
                    $result = ['code' => 12018, 'msg' => $e->getMessage()];
                }
            }
        } else {
            $result = ['code' => 12019, 'msg' => '金额必须大于0'];
        }
        return $return ? json($result) : $result;
    }

    /**
     * 账号支付置顶，刷新,发红包
     */
    private function handle_info($action = '', $money = 0, $credit = 0, $currency)
    {
        if (empty(self::$user['id'])) return ['code' => 1000, 'msg' => '请登录'];
        if ($currency == '') return ['code' => 12020, 'msg' => '请选择支付货币'];
        if (!in_array($currency, [0, 1, 2])) return ['code' => 12021, 'msg' => '非法参数'];
        $status = 1;
        $config = [
            'top' => ['message' => '信息置顶', 'msg' => '置顶成功'],
            'refresh' => ['message' => '信息刷新', 'msg' => '刷新成功'],
            'redpack' => ['message' => '发红包', 'msg' => '操作成功']
        ];
        $message = $config[$action]['message'];
        $msg = $config[$action]['msg'];
        if (in_array($currency, [0, 2])) {
            if (self::$user['credit'] < $credit) return ['code' => 12022, 'msg' => '积分不足'];
            $attr = [
                'balance' => 0,
                'money' => $credit,
                'user_id' => self::$user['id'],
                'payment' => 0,
                'type' => 0,
                'memo' => $message . '扣除【' . $credit . '】积分'
            ];
            $result = action('finance/api/credit', [$attr, 0]);
            if ($result['code'] == 0) {
                $status = 0;
                $msg = $result['msg'];
            }
        }
        if (in_array($currency, [1, 2])) {
            if (self::$user['money'] < $money) return ['code' => 12023, 'msg' => '余额不足'];
            $attr = [
                'balance' => 0,
                'money' => $money,
                'user_id' => self::$user['id'],
                'payment' => 1,
                'type' => 1,
                'memo' => $message . '扣除【' . $money . '】余额'
            ];
            $result = action('finance/api/money', [$attr, 0]);
            if ($result['code'] == 0) {
                $status = 0;
                $msg = $result['msg'];
            }
        }
        return ['code' => $status, 'msg' => $msg];
    }

    /**
     * 个人发布信息
     */
    function user_data($cid = 0, $return = 1, $user_id = 0)
    {
        if (empty(self::$user['id']) && empty($user_id)) return json(['code' => 1000, 'msg' => '请登录...']);
        $user_id = $user_id ? : self::$user['id'];
        $where[] = ['user_id', '=', $user_id];
        if ($cid) $where[] = ['column_id', '=', $cid];
        $rs = db('data')->where($where)->where('status', '=', 1)->order('create_time desc, status desc')->paginate(20)->toArray();
        $rs = $this->_init_data($rs);
        if (!empty($rs['data'])) {
            foreach ($rs['data'] as $k => &$v) {
                $column = load_column($v['column_id']);
                $v['refresh_money'] = empty($column['setting']['group'][self::$user['group_id']]['refresh_money']) ? 0 : $column['setting']['group'][self::$user['group_id']]['refresh_money'];
                $v['refresh_credit'] = empty($column['setting']['group'][self::$user['group_id']]['refresh_credit']) ? 0 : $column['setting']['group'][self::$user['group_id']]['refresh_credit'];
                $v['top_money'] = empty($column['setting']['group'][self::$user['group_id']]['top_money']) ? 0 : $column['setting']['group'][self::$user['group_id']]['top_money'];
                $v['top_credit'] = empty($column['setting']['group'][self::$user['group_id']]['top_credit']) ? 0 : $column['setting']['group'][self::$user['group_id']]['top_credit'];
            }
        }
        return $return ? json($rs) : $rs;
    }

    /**
     * 检测区域是否允许发布
     * @return int
     */
    function allow_area()
    {
        $status = 0;
        if (!empty(self::$cim['onlyarea'])) {
            $ip_info = get_ip_address();
            if (!empty($ip_info)) {
                $allow_area = explode(',', self::$cim['onlyarea']);
                $area_str = $ip_info['country'] . $ip_info['area'];
                if (isset($ip_info['region'])) $area_str .= $ip_info['region'] . '省';
                if (isset($ip_info['city'])) $area_str .= $ip_info['city'] . '市';
                if (isset($ip_info['county'])) $area_str .= $ip_info['county'] . '县';
                foreach ($allow_area as $k => $v) {
                    if (strpos($area_str, $v) !== false) {
                        $status = 1;
                        break;
                    }
                }
            }
        } else {
            $status = 1;
        }
        return $status;
    }

    /**
     * 数据行为详情
     */
    function view_behavior($key = '', $cid = 0, $id = 0)
    {
        if ($key && $cid && $id) {
            $data = db('data_behavior')->where('key', '=', $key)->find();
            if (empty($data)) return '';
            $data = array_merge($data, json_decode($data['extend'], 1)[0]);
            $data['count'] = 0;
            if ($data['name'] == 'share_redpack') {
                //红包获得历史
                $data['history'] = db('order')
                    ->alias('o')
                    ->join('__USER__ u', 'u.id=o.user_id')
                    ->where('o.extend', 'neq', '')
                    ->where('extend->key', '=', $key)
                    ->field('round(sum(o.money),2) total_money,u.name,count(*) count,o.user_id')
                    ->group('user_id')
                    ->select();
            }
            if (!empty($data['history'])) {
                foreach ($data['history'] as $k => &$v) {
                    $v['avatar'] = action('user/api/avatar', [$v['user_id']]);
                }
                $data['count'] = array_sum(array_column($data['history'], 'count'));
            }
            return json($data);
        }
    }

    /**
     * 移动端筛选项接口
     */
    public function load_filter($attr = [])
    {
        is_string($attr) && $attr = json_decode($attr, 1);
        $data['columns'] = array_values(load_columns(1, 0, '', isset($attr['model']) ? (array)$attr['model'] : []));
        $data['areas'] = array_values(load_areas());
        if (!empty($data['columns'])) {
            foreach ($data['columns'] as $k => $v) {
                if (!empty($v['child'])) $data['columns'][$k]['child'] = array_values($v['child']);
            }
        }
        if (!empty($data['areas'])) {
            foreach ($data['areas'] as $k => $v) {
                if (!empty($v['child'])) $data['areas'][$k]['child'] = array_values($v['child']);
            }
        }
        return json($data);
    }

    /**
     * 筛选项
     */
    function filters($attr = [])
    {
        $rs = [];
        if (isset($attr['order'])) {
            switch ($attr['order']) {
                case '1':
                    $rs['order'] = 'create_time desc';
                    break;
                case '2':
                    $rs['order'] = 'hits desc';
                    break;
                case '3':
                    $rs['order'] = 'create_time desc';
                    $rs['where'][] = ['behavior', 'neq', ''];
                    break;
                case '4':
                    $rs['order'] = 'hits desc';
                    break;
                case '5':
                    $rs['order'] = 'create_time desc';
                    break;
                case '6':
                    if (isset($attr['lat']) && isset($attr['lon'])) {
                        $rs['order'] = 'sqrt((lat-' . $attr['lat'] . ')*(lat-' . $attr['lat'] . ')+(lon-' . $attr['lon'] . ')*(lon-' . $attr['lon'] . ')) asc';
                    }
                    break;
            }
        }
        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'])) $rs['where'][] = ['name', 'like', '%' . $attr['keywords'] . '%'];
        return $rs;
    }

    /**
     * 生成二维码
     */
    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']);
    }

    /**
     * 移动端搜索
     */
    public function search($attr = [])
    {
        if (empty($attr['keyword'])) return json(['code' => 12025, 'msg' => '参数错误']);
        $data = $this->_search($attr);
        if (isset($data['code']) && $data['code'] == 0) return json(['code' => 0, 'msg' => $data['msg']]);
        if (!empty($data['data'])) $data['data'] = $this->_init_data($data['data']);
        return json(['code' => 1, 'data' => $data]);
    }

    /**
     * 反馈热门标签
     * @return \think\response\Json
     */
    function feedback_tags($num = 20)
    {
        $tags = db('feedback')->alias('f')->field('f.id,substring_index(substring_index(f.tags,\',\',b.id+1),\',\',-1) tags')->join('__TEMP__ b', 'b.id<(length(f.tags)-length(replace(f.tags,\',\',\'\'))+1)')->where('f.tags', 'neq', '')->select();
        if (!empty($tags)) {
            $count = array_count_values(array_column($tags, 'tags'));
            arsort($count);
            $data = [];
            $i = 0;
            foreach ($count as $k => $v) {
                if ($i < $num) {
                    $data[$i] = [
                        'name' => $k,
                        'count' => $v
                    ];
                    $i++;
                } else {
                    break;
                }
            }
        } else {
            $data = [];
        }
        return json(['code' => 1, 'data' => $data]);
    }


    /**
     * 评论
     */
    public function comment($data_id = '', $comment_id = '', $reply = '')
    {
        $comment = model('comment');
        if (request()->isPost()) {
            if (!input('?post.content'))
                return;
            if (empty(self::$user['id'])) {
                return json(['code' => 1000, 'msg' => '请先登录后再进行评论操作。']);
            }
            $config = load_setting('index');
            //评论时间间隔
            $space = empty($config['comment']['space']) ? 0 : $config['comment']['space'];
            if ($space) {
                if (!empty(cache('last_comment_time_' . self::$sys['ip'])) && (time() - cache('last_comment_time_' . self::$sys['ip']) < $space)) {
                    return json(['code' => 12026, 'msg' => '您评论的太快，请先休息一下..']);
                }
            }
            if (!empty(input('param.column_id'))) {
                $column = load_column(input('param.column_id', ''));
                if (!empty($column)) {
                    //每天发布数检测
                    if (isset($column['setting']['group'][self::$user['group_id']]['comment_limit']) && is_numeric($column['setting']['group'][self::$user['group_id']]['comment_limit'])) {
                        if ($column['setting']['group'][self::$user['group_id']]['comment_limit'] > -1) {
                            $cache_key = 'column_' . $column['id'] . '_group_' . self::$user['group_id'] . '_' . date('Ymd') . '_user_id_' . self::$user['id'] . '_comment';
                            $cache_data = cache($cache_key);
                            if (!empty($cache_data)) {
                                if ($cache_data['count'] <= 0) return json(['code' => 12027, 'msg' => '超出每天评论数量限制']);
                            } else {
                                cache($cache_key, ['count' => $column['setting']['group'][self::$user['group_id']]['comment_limit']], 86400);
                            }
                        } else {
                            return json(['code' => 12028, 'msg' => '当前栏目禁止评论']);
                        }
                    }
                }
            }
            $user_id = self::$user['id'];
            $user_name = self::$user['name'];
            $data = input('post.');
            $data['user_id'] = $user_id;
            $data['create_time'] = time();
            $data['status'] = empty($config['comment']['check']) ? 1 : 0;
            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;
            }
            if ($comment_id != '') {
                //楼层
                $data['floor'] = intval(db('comment')->where('comment_id', '=', $comment_id)->max('floor')) + 1;
            } else {
                $data['floor'] = intval(db('comment')->where('data_id', '=', $data_id)->max('floor')) + 1;
            }
            $comment->allowField(true)->save($data);
            if ($space) cache('last_comment_time_' . self::$sys['ip'], $data['create_time'], $space);
            if ($data['status']) {
                if ($comment_id != '') {
                    db('comment')->where('id', $comment_id)->setInc('reply_count');
                }
                db('data')->where('id', '=', $data_id)->setInc('comment_count');
            }
            $data['user'] = [
                'id' => $user_id,
                'avatar' => action('user/api/avatar', ['id' => $user_id]),
                'name' => $user_name,
                'url' => url('user/index/index', ['id' => $user_id])
            ];
            if (!empty($cache_key)) {
                $cache_data = cache($cache_key);
                cache($cache_key, ['count' => $cache_data['count'] - 1], 86400);
            }
            return json(['code' => 1, 'data' => $data, 'msg' => '感谢您的评论' . (!$data['status'] ? '，系统审核后即可显示' : '') . '。']);
        }
        if (request()->isGet()) {
            $where = [
                ['status', '=', 1]
            ];
            if ($comment_id == '') {
                $where[] = ['comment_id', '=', 0];
                $where[] = ['data_id', '=', $data_id];
                if ($reply) {
                    $with = 'user,reply';
                } else {
                    $with = 'user';
                }
                $data = $comment->with($with)->where($where)->order('create_time desc')->select();
            } else {
                $where[] = ['comment_id', '=', $comment_id];
                $data = $comment->with('user')->where($where)->order('create_time asc')->select();
            }
            $arr = [];
            foreach ($data as $k => $v) {
                if (empty($v['user'])) $v['user'] = ['name' => '匿名', 'url' => ''];
                if (!empty($v['content'])) $v['content'] = nl2br($v['content']);
                if ($v['to_user_id'] && !self::$sys['is_mobile']) {
                    $v['content'] = str_replace('@' . $v['to_user_name'] . ' ', '<a href="' . url('user/index/index', ['id' => $v['to_user_id']]) . '">@' . $v['to_user_name'] . '</a> ', $v['content']);
                }
                $v['from_now'] = from_now(strtotime($v['create_time']));
                $arr[$k] = $v;
            }
            return json(['code' => 1, 'msg' => '加载成功', 'data' => $arr]);
        }
    }

    /**
     * 检测是否具备管理权
     */
    public function check_owner($rs)
    {
        if ( !empty(self::$admin) && ( self::$admin['role_id'] == 0 || in_array('index_admin_edit', self::$admin['power']) ) ) return 1;
        if ( self::$user['id']>0 && self::$user['id'] == $rs['user_id'] ) return 2;
        if ( !empty(session('owner_datas')) && in_array($rs['id'], session('owner_datas'))) return 3;
        return 0;
    }

}
