<?php

/**
 * +------------------------------------------------------------
 * | 数据-基类 (data/controller/Module.php)
 * +------------------------------------------------------------
 * | @author: zhx (10630650@qq.com)
 * | @create_time: 2018-04-19 11:31:21
 * +------------------------------------------------------------
 * | @copyright: CIM信息聚合系统 (https://cimxx.com)
 * +------------------------------------------------------------
 * | @last_modified_by: zhx
 * | @last_modified_time: 2018-04-19 11:31:21
 * +------------------------------------------------------------
 * | @todo:
 * +------------------------------------------------------------.
 */

namespace app\index\controller;

use app\common\controller\Fields;
use think\Db;
use app\common\controller\Init;
use app\index\model\Data;

class Module extends Init
{
    public static $models;

    public static $area = ['id' => '', 'name' => '', 'parent_id' => 0];

    public static $areas = [];

    public static $column = [];

    public static $columns = [];

    protected function initialize()
    {
        parent::initialize();
        self::$areas = load_areas(0);
        $index_config = include(\Env::get('app_path') . 'index/config/app.php');
        self::$models = $index_config['models'];
        self::$columns = load_columns(0, 0, 'id', '', '');
        if (input('?param.key')) {
            self::$column = load_column(input('param.key'), 0, '', self::$user['group_id']);
        }
        if (input('?param.cid')) {
            self::$column = load_column(input('param.cid'), 0, '', self::$user['group_id']);
        }
    }

    /**
     * 初始化自定义字段.
     */
    protected function _init_fields($vals, $fields = [], $form = 0)
    {
        $rs = new Fields();
        return $rs->_init($vals, $fields, $form);
    }

    /**
     * 查询
     */
    protected function query($attr = [])
    {
        $cache_id = 'data_query_' . md5(json_encode($attr));
        if (isset($attr['cache'])) {
            if ($attr['cache']==-1) cache($cache_id, null);
            $rs = cache($cache_id);
            if (!empty($rs)) return $rs;
        }
        //未设置id/cid/key/model/栏目为空
        if (!isset($attr['id']) && (!isset($attr['cid']) || !isset($attr['key']) || !isset($attr['model'])) && !isset($attr['where']) && empty(self::$columns)) return [];
        //没有条件时默认条件
        if (!isset($attr['where'])) $attr['where'][] = ['status', '=', 1];
        if (isset($attr['cid'])) self::$column = load_column($attr['cid'], 0, '', self::$user['group_id']);
        if (empty(self::$column) && isset($attr['key'])) self::$column = load_column($attr['key'], 0, '', self::$user['group_id']);
        //处理with
        if (!isset($attr['with'])) {
            $attr['with'] = '';
            if (isset(self::$column['model'])) {
                if (isset(self::$models[self::$column['model']]['table'])) $attr['with'] = join(',', self::$models[self::$column['model']]['table']);
            }
        }
        //处理单条数据
        if (isset($attr['id'])) {
            if (isset(self::$column['model']) && method_exists($this, $_method = '_' . self::$column['model'])) {
                $rs = $this->$_method($attr);
            } else {
                $rs = model('data')->with($attr['with'])->where($attr['where'])->find($attr['id']);
                if (!empty($rs)) self::$column = self::$columns[$rs['column_id']];
                if (!empty($rs->image)) $this->_init_image($rs->image);
            }
        } else {
            //处理条件
            !isset($attr['field']) && $attr['field'] = '';
            !isset($attr['limit']) && $attr['limit'] = 20;
            !isset($attr['order']) && $attr['order'] = 'update_time desc';
            //页面模型直接返回
            if (isset($attr['model']) && !isset($attr['cid'])) {
                if (in_array($attr['model'], ['article', 'info', 'phone', 'links'])) {
                    $rs = db($attr['model'])->alias('a')->join('data d', 'a.data_id=d.id')->field('d.id, d.column_id, d.area_id, d.name, d.thumb, d.hits, d.update_time, d.create_time, d.behavior, d.top_end_time, d.end_time, d.status, a.*')->where($attr['where'])->limit($attr['limit'])->order($attr['order']);
                    $rs = isset($attr['page']) ? $rs->paginate($attr['limit'], '', ['page' => $attr['page']])->toArray() : $rs->select();
                }
            } elseif (isset($attr['model']) && $attr['model'] == 'pages') {
                $rs = model('pages')->get($attr['cid']);
            } else {
                //处理cid
                if (isset($attr['cid'])) {
                    if (count(explode(',', $attr['cid'])) == 1) {
                        //未找到栏目
                        if (!isset(self::$columns[$attr['cid']])) {
                            return [];
                        }
                        self::$column = self::$columns[$attr['cid']];
                        $columns = \array_to_tree(self::$columns);
                        if (!empty($columns[$attr['cid']]['child'])) {
                            $cids = array_merge([$attr['cid']], array_keys($columns[$attr['cid']]['child']));
                            $attr['where'][] = ['column_id', 'in', $cids];
                        } else {
                            $attr['where'][] = ['column_id', '=', $attr['cid']];
                        }
                    } else {
                        $cids = \explode(',', $attr['cid']);
                        $attr['where'][] = ['column_id', 'in', $cids];
                    }
                }

                //如果栏目模型与标签模型不符，则返回空数组
                if (isset($attr['model']) && self::$column['model'] != $attr['model']) {
                    return [];
                }

                //如果定义了独立方法，走独立方法
                if (isset(self::$column['model']) && method_exists($this, $_method = '_' . self::$column['model'])) {
                    $rs = $this->$_method($attr);
                } else {
                    $field = 'd.id, d.column_id, d.area_id, d.name, d.thumb, d.hits, d.top_end_time, d.update_time, d.create_time, d.end_time, d.user_id, d.behavior, d.fields, d.status' . $attr['field'];
                    $rs = db('data')->alias('d');
                    if (isset(self::$column['model']) && in_array(self::$column['model'], ['info', 'article', 'phone', 'links'])) {
                        $rs = $rs->join(self::$column['model'] . ' b', 'd.id = b.data_id');
                        $field .= ',b.*';
                    }
                    $rs = $rs->field($field)->where($attr['where'])->order($attr['order']);
                    if (isset($attr['page'])) {
                        $rs = $rs->paginate($attr['limit'], '', ['page' => $attr['page']])->toArray();
                    } else {
                        $rs = $rs->limit($attr['limit'])->select();
                    }
                }
            }
        }
        //缓存时间 单位:分钟
        if (isset($attr['cache'])) {
            cache($cache_id, $rs, ($attr['cache'] * 60));
        }
        return $rs;
    }

    /**
     * 数据添加 / 修改
     */
    protected function _add($data)
    {
        if (!empty($data['column_id'])) self::$column = load_column($data['column_id'], 0, '', self::$user['group_id']);
        if (empty(self::$column)) return;
        if (!isset($data['id'])) return;
        $data['column_id'] = self::$column['id'];
        Db::startTrans();
        try {
            if (self::$sys['controller'] != 'admin') {
                if (!empty(self::$column['setting']['check']['enabled_words'])) {
                    if (isset($data['name'])) {
                        $name = filter_words($data['name'], 'post');
                        if ($name['level'] == 3) return ['code' => 0, 'msg' => '标题包含敏感词【' . join(',', array_slice($name['words']['3'], 0, 5)) . '】,禁止发布...'];
                        $data['status'] = ($name['level'] == 2) ? 0 : 1;
                        if (!empty($name['words']['1'])) $data['name'] = $name['content'];
                    }
                    if (isset($data['info']['content'])) {
                        $content = filter_words($data['info']['content'], 'post');
                        if ($content['level'] == 3) return ['code' => 0, 'msg' => '内容包含敏感词【' . join(',', array_slice($content['words']['3'], 0, 5)) . '】,禁止发布...'];
                        $data['status'] = ($content['level'] == 2) ? 0 : (isset($data['status']) ? $data['status'] : 1);
                        if (!empty($name['words']['1'])) $data['info']['content'] = $content['content'];
                    }
                }
                if (!empty(self::$column['setting']['check']['post'])) $data['status'] = 0;
                $money = self::$column['setting']['group'][self::$user['group_id']]['add_money'] ?? 0;
                $credit = self::$column['setting']['group'][self::$user['group_id']]['add_credit'] ?? 0;
                if ($credit < 0 || $money < 0) {
                    //支付状态2=待支付
                    $data['status'] = 2;
                }
            } else {
                $data['user_id'] = self::$admin['id'];
            }
            //处理自定义字段
            $fields = load_fields($data['column_id']);
            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']];
                    }
                }
            }
            $data['ip'] = self::$sys['ip'];
            $data['port'] = input('server.REMOTE_PORT', '');
            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 ($data['id']) {
                $update = 1;
                $validate = validate('DataUpdate');
                if (!$validate->check($data)) {
                    return ['code' => 0, 'msg' => $validate->getError()];
                }
                $_model = Data::get($data['id']);
                $key = empty($data['key']) ? '' : $data['key'];
                if (!$this->check_power($_model, $key)) {
                    return ['code' => 0, 'msg' => '无权限更改'];
                }
                $_model->allowField(true)->update($data, ['id' => $data['id']]);
                //模型
                if (isset($data[self::$column['model']])) {
                    $_tmp = self::$column['model'];
                    if (model($_tmp)->where('data_id', $data['id'])->count()) {
                        $_model->$_tmp->save($data[self::$column['model']]);
                    } else {
                        $_model->$_tmp()->save($data[self::$column['model']]);
                    }
                }
            } else {
                $validate = validate('DataAdd');
                if (!$validate->check($data)) {
                    return ['code' => 0, 'msg' => $validate->getError()];
                }
                $_model = new Data();
                $data['user_id'] = isset(self::$user['id']) ? self::$user['id'] : 0;
                $_model->allowField(true)->save($data);
                if ($_model->id) {
                    $data['id'] = $_model->id;
                }
                //模型
                if (isset($data[self::$column['model']])) {
                    $_tmp = self::$column['model'];
                    $_model->$_tmp()->save($data[self::$column['model']]);
                }
            }
            //处理图片上传
            $image_data = [];
            if (!empty($data['image'])) {
                foreach ((array)$data['image'] as $k => $v) {
                    if (!empty($v)) {
                        array_push($image_data, [
                            'data_id' => $data['id'],
                            'path' => $v,
                        ]);
                    }
                }
            }

            $upload_config = empty(self::$column['setting']['upload']) ? [] : ['upload' => self::$column['setting']['upload']];
            $image = action('files/api/upload', [$upload_config, 0]);
            if (isset($image['success'])) {
                foreach ($image['success'] as $v) {
                    array_push($image_data, [
                        'data_id' => $data['id'],
                        'path' => $v['path'],
                    ]);
                }
            }
            //如果是编辑信息 则查询已有图片
            if (isset($update)) {
                $delete_images = array_diff(array_column($_model->image->toArray(), 'path'), array_column($image_data, 'path'));
                if (!empty($delete_images)) db('data_image')->where('data_id', '=', $data['id'])->where('path', 'in', $delete_images)->delete();
                $add_images = array_intersect(array_column($image_data, 'path'), array_column($_model->image->toArray(), 'path'));
                foreach ($add_images as $k=>$v) {
                    if (in_array($v, array_column($image_data, 'path'))) unset($image_data[$k]);
                }
            }
            model('image')->saveAll($image_data);

            if (!empty($image_data) || !empty($data['thumb'])) {
                $source = [];
                if (!empty($update)) {
                    if (!empty($_model['thumb'])) {
                        $source[] = [
                            'data_id' => $data['id'],
                            'path' => $_model->getData('thumb'),
                            'fields' => 'data|thumb',
                        ];
                    }
                    if ($_model->image) {
                        $source[] = [
                            'path' => array_column($_model->image->toArray(), 'path'),
                            'data_id' => $data['id'],
                            'fields' => 'data_image|path',
                        ];
                    }
                }
                if (!empty($image_data)) {
                    $path = array_column($image_data, 'path');
                    if (empty($data['thumb'])) {
                        model('data')->where('id', '=', $data['id'])->update(['thumb' => $image_data[0]['path']]);
                    }
                    $update_file_info[] = [
                        'data_id' => $data['id'],
                        'path' => $path,
                        'fields' => 'data_image|path',
                        'title' => $data['name'],
                    ];
                }
                $update_file_info[] = [
                    'data_id' => $data['id'],
                    'path' => empty($data['thumb']) ? $image_data[0]['path'] : action('files/api/original_thumb', [$data['thumb']]),
                    'fields' => 'data|thumb',
                    'title' => $data['name'],
                ];
                //更新附件信息
                action('files/api/update_file_info', [$update_file_info, $source]);
            }
            // 提交事务
            Db::commit();
            $this->after_add($data);
            $msg = ['code' => 1, 'id' => $data['id']];
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $msg = ['code' => 0, 'msg' => $e->getMessage()];
        }

        return $msg;
    }

    protected function _init_image($rs)
    {
        foreach ($rs as $k => $v) {
            $rs[$k]['url'] = config('files.url') . $v['path'];
        }
    }

    /**
     * 解析url
     * 仅用于PC端
     */
    protected function _url($id, $key = '')
    {
        if (!$key) $key = empty(self::$column['key']) ? '' : self::$column['key'];
        if (!$key) return '';
        return url('index/index/view', ['key' => $key, 'id' => $id], true, true);
    }

    /**
     * 初始化数据
     */
    protected function _init_data($rs, $form = 0)
    {
        if (isset($rs['id'])) {
            $rs['thumb'] = action('files/api/_init_thumb', [$rs['thumb'], 1]);
            $rs['column'] = get_array_keys(self::$columns[$rs['column_id']], 'id,name,key,model,url');
            $rs['fields'] = $this->_init_fields((array)$rs['fields'], load_fields($rs['column_id']), $form);
            if (self::$column['model'] == 'info') {
                $rs['info']['expired'] = 0;
                if ($rs->getData('end_time') < time()) {
                    $rs['info']['phone'] = '';
                    $rs['info']['expired'] = 1;
                }
                unset($rs['info']['password']);
            }
            if (isset($rs['area_id'])) $rs['area'] = empty(self::$areas[$rs['area_id']]) ? '' : self::$areas[$rs['area_id']];
            if (!empty($rs['user_id'])) $rs = $rs->append(['user']);
            if (!self::$sys['is_mobile']) $rs['url'] = $this->_url($rs['id'], $rs['column']['key']);
            return $rs;
        }
        $data = isset($rs['total']) ? $rs['data'] : $rs;
        $user_id = array_filter(array_column($data, 'user_id'));
        !empty($user_id) && $user = model('app\user\model\User')->where('id', 'in', $user_id)->field('id,name,group_id,phone,email')->select();
        !empty($user) && $user = array_column($user->toArray(), null, 'id');
        foreach ($data as $k => &$v) {
            if (isset(self::$areas[$v['area_id']])) $v['area'] = self::$areas[$v['area_id']];
            if (!empty($v['fields'])) {
                $v['fields'] = $this->_init_fields($v['fields'], load_fields($v['column_id'], 0, 1));
            }
            if (!empty($v['behavior'])) $v['behavior'] = json_decode($v['behavior'], 1);
            $v['column'] = get_array_keys(self::$columns[$v['column_id']], 'id,name,key,model,url');
            $v['thumb'] = action('files/api/_init_thumb', [$v['thumb'], 1, 1]);
            if (self::$columns[$v['column_id']]['model'] != 'links') {
                $v['url'] = $this->_url($v['id'], self::$columns[$v['column_id']]['key']);
                if (self::$columns[$v['column_id']]['model'] == 'info') unset($v['password']);
            }
            $v['time'] = time_format($v['update_time']);
            $v['end_time'] = $v['end_time'] ? time_format($v['end_time']) : '';
            if (isset($v['top_end_time'])) {
                $v['is_top'] = ($v['top_end_time'] > time()) ? 1 : 0;
            }
            if (!empty($v['user_id']) && isset($user[$v['user_id']])) {
                $v['user'] = $user[$v['user_id']];
            } else {
                $v['user'] = [
                    'avatar' => action('files/api/_init_thumb', ['avatar', 1]),
                    'name' => '',
                    'group_id' => 0
                ];
            }
        }
        isset($rs['total']) ? $rs['data'] = $data : $rs = $data;
        return $rs;
    }

    /**
     * 判断是否有权限操作信息
     */
    public function check_power($data = [], $key = '')
    {
        $status = 0;
        if (!empty($data)) {
            if (!empty(self::$user['admin'])) $status = 1;
            //优先判断key值
            if ($key && !empty(cache($key)) && cache($key)['data_id'] == $data['id'] && cache($key)['time'] + 600 > time()) {
                $status = 1;
            } else {
                //登录,判断user_id是否一致
                if (!empty(self::$user['id'])) {
                    if ($data['user_id'] == self::$user['id']) {
                        $status = 1;
                    }
                }
            }
        }
        return $status;
    }

    /**
     * 检测栏目登录才能查看
     */
    public function check_login()
    {
        $check_login = empty(self::$column['setting']['check']['login']) ? 0 : self::$column['setting']['check']['login'];
        if ($check_login && empty(self::$user['id'])) {
            if (self::$sys['is_mobile']) {
                die(json_encode(['code' => 1000, 'msg' => '请登录后查看']));
            } else {
                return $this->error('请登录后查看');
            }
        }
    }

    /**
     * 发布前行为
     */
    public function before_add()
    {
        $cache_key = 'column_' . self::$column['id'] . '_group_' . self::$user['group_id'] . '_' . date('Ymd') . '_user_id_';
        $add_cache_key = 'add_';
        if (self::$user['group_id'] == 0) {
            $cache_key .= self::$sys['ip'];
            $add_cache_key .= self::$sys['ip'];
        } else {
            $cache_key .= self::$user['id'];
            $add_cache_key .= self::$user['id'];
        }
        $cache_data = cache($cache_key);
        if (empty($cache_data)) {
            $cache_data = [
                'time' => 0,
                'num' => 0,
            ];
            cache($cache_key, $cache_data);
        }
        //发布频率检测
        $cim_config = load_setting('cim');
        if (!empty($cim_config['add_space']) && !empty(cache($add_cache_key))) {
            if (time() - cache($add_cache_key) <= $cim_config['add_space']) {
                return ['code' => 0, 'msg' => '操作过快，请休息一下重试...'];
            }
        }
        //每天发布数检测
        if (!empty(self::$column['setting']['group'][self::$user['group_id']]['add_limit'])) {
            if ($cache_data['num'] >= self::$column['setting']['group'][self::$user['group_id']]['add_limit']) {
                return ['code' => 0, 'msg' => '超出每天发布数量限制...'];
            }
        }
    }

    /**
     * 发布成功后行为
     */
    public function after_add($data = [])
    {
        if (self::$user['id']) {
            //操作用户积分
            if (!empty(self::$column['setting']['group'][self::$user['group_id']]['add_credit'])) {
                $order = [
                    'user_id' => self::$user['id'],
                    'payment' => 4,
                    'type' => 1,
                    'money' => self::$column['setting']['group'][self::$user['group_id']]['add_credit'],
                    'balance' => self::$column['setting']['group'][self::$user['group_id']]['add_credit'] > 0 ? 1 : 0,
                    'memo' => '发布信息' . (self::$column['setting']['group'][self::$user['group_id']]['add_credit'] > 0 ? '增加' : '减少') . '积分',
                ];
                action('finance/api/credit', [$order, 0]);
            }
            $check = 0;
            if (self::$sys['is_mobile']) {
                $check = (!empty(self::$column['setting']['check']['post_phone_mobile']) || !empty(self::$cim['post_phone_mobile'])) ? 1 : 0;
            } else {
                $check = (!empty(self::$column['setting']['check']['post_phone_pc']) || !empty(self::$cim['post_phone_pc'])) ? 1 : 0;
            }
            if ($check) {
                $user = model('app\user\model\User')->find(self::$user['id']);
                //用户未绑定手机号，进行绑定
                if (empty($user['phone'])) {
                    db('user')->where('id', '=', $user['id'])->setField('phone', $data['phone']);
                } else {
                    //if ($data['phone'] != $user['id'] )
                }
            }
        }
        //更改缓存数据
        $cache_key = 'column_' . self::$column['id'] . '_group_' . self::$user['group_id'] . '_' . date('Ymd') . '_user_id_';
        $add_cache_key = 'add_';
        if (self::$user['group_id'] == 0) {
            $cache_key .= self::$sys['ip'];
            $add_cache_key .= self::$sys['ip'];
        } else {
            $cache_key .= self::$user['id'];
            $add_cache_key .= self::$user['id'];
        }
        cache($add_cache_key, time());
        $cache_data = cache($cache_key);
        $cache_data = [
            'time' => time(),
            'num' => intval($cache_data['num']) + 1,
        ];
        cache($cache_key, $cache_data);
    }

    /**
     * 全站搜索
     */
    protected function _search($attr = [])
    {
        $where[] = ['d.update_time', '>', strtotime(date('Y-m-d')) - 31536000];
        $where[] = ['d.name', 'like', '%' . $attr['keyword'] . '%'];
        $where[] = ['d.status', '=', 1];
        $cache_key = md5(json_encode($where));
        $config = load_setting('cim');
        if (!empty($config['search_space']) && empty(cache($cache_key))) {
            $key = 'search_space_';
            if (isset(self::$user['id'])) {
                $key .= self::$user['id'];
            } else {
                $key .= self::$sys['ip'];
            }
            if (!empty(cache($key)) && time() - cache($key) < $config['search_space']) return ['code' => 0, 'msg' => '操作过快，请休息一下重试...'];
        }
        $data['column'] = db('data')->alias('d')->where($where)->field('d.column_id,count(*) count')->group('d.column_id')->cache($cache_key, 3600)->select();
        if (!empty($data['column'])) {
            $columns = load_columns(0);
            foreach ($data['column'] as $k => &$v) {
                $v['name'] = $columns[$v['column_id']]['name'];
                $v['on'] = (isset($attr['cid']) && $attr['cid'] == $v['column_id']) ? 1 : 0;
            }
        }
        $area_id = db('data')->alias('d')->where($where)->group('d.area_id')->cache(true, 3600)->column('area_id');
        if (!empty($attr['cid'])) {
            $where[] = ['d.column_id', '=', $attr['cid']];
        }
        $data['area'] = db('data')->alias('d')->where($where)->field('d.area_id,count(*) count')->group('d.area_id')->cache(true, 3600)->select();
        if (isset($attr['use'])) {
            if (intval($attr['use'])) {
                $where[] = ['d.end_time', '>', time()];
            } else {
                $where[] = ['d.end_time', '<', time()];
            }
        }
        if (!empty($data['area'])) {
            $areas = load_areas(0);
            $area = [];
            $area_id = array_diff($area_id, array_column($data['area'], 'area_id'));
            if (!empty($area_id)) {
                foreach ($area_id as $val) $data['area'][] = [
                    'area_id' => $val,
                    'count' => 0
                ];
            }
            foreach ($data['area'] as $kk => &$vv) {
                if ($vv['area_id'] != 0 && isset($areas[$vv['area_id']])) {
                    $vv['name'] = $areas[$vv['area_id']]['name'];
                    $vv['on'] = (isset($attr['area']) && $attr['area'] == $vv['area_id']) ? 1 : 0;
                    $area[] = $vv;
                }
            }
            $data['area'] = array_values($area);
        }
        if (!empty($attr['area'])) {
            $where[] = ['d.area_id', '=', $attr['area']];
        }
        $order = 'd.update_time desc';
        $data['data'] = db('data')->alias('d');
        if (!empty($attr['cid']) && !empty($columns[$attr['cid']])) {
            $data['data'] = $data['data']->join($columns[$attr['cid']]['model'] . ' b', 'd.id=b.data_id')->field('d.id, d.column_id, d.area_id, d.name, d.thumb, d.hits, d.create_time,d.end_time,d.behavior,d.fields,b.*');
        }
        $data['data'] = $data['data']->where($where)->order($order)->cache(true, 3600)->paginate(20, false, [
            'page' => empty($attr['page']) ? 1 : $attr['page'],
        ])->toArray();
        if (!empty($key)) cache($key, time());
        return $data;
    }

    /**
     * 信息管理
     *
     * @param string $key
     * @param string $id
     *
     * @return \think\response\Json|\think\response\View
     */
    public function manage($key = '', $id = '')
    {
        if (request()->isPost()) {
            $attr = input('post.attr/a', []);
            //搜索信息
            if (isset($attr['phone'])) {
                $data = $this->query([
                    'model' => 'info',
                    'where' => ['phone' => $attr['phone'], 'status' => 1],
                ]);
                if (!empty($data)) {
                    $data = $this->_init_data($data);

                    return json(['code' => 1, 'msg' => '搜索成功', 'data' => $data]);
                } else {
                    return json(['code' => 0, 'msg' => '搜索结果不存在']);
                }
            }
            if (!isset($attr['data_id']) || !isset($attr['cid'])) {
                return json(['code' => 0, 'msg' => '参数错误,缺少参数data_id和cid']);
            }
            $data = $this->query([
                'id' => $attr['data_id'],
                'cid' => $attr['cid'],
                'where' => '',
            ]);
            if (isset($attr['key'])) {
                $cache_data = cache($attr['key']);
                if (!empty($cache_data) && $cache_data['time'] + 600 > time() && $attr['data_id'] == $cache_data['data_id']) {
                    return json(['code' => 1, 'msg' => '验证成功', 'data' => $data, 'key' => $attr['key']]);
                }
            }
            $status = 0;
            if (!empty($data['info'])) {
                if (!empty($attr['password'])) {
                    if (empty($attr['captcha']) || !captcha($attr['captcha'])) {
                        return json(['code' => 0, 'msg' => '验证码错误']);
                    }
                    if (!empty($attr['password']) && $attr['password'] == $data['info']['password']) {
                        $status = 1;
                    }
                } elseif (!empty($attr['code'])) {
                    $cache = cache($data['info']['phone']['value']);
                    if (!empty($attr['code']) && !empty($cache) && $attr['code'] == $cache['code'] && $cache['time'] + 180 > time()) {
                        $status = 1;
                    }
                } elseif (!empty($attr['captcha'])) {
                    //发送验证码
                    if (empty($data['info']['phone']['value'])) {
                        return json(['code' => 0, 'msg' => '手机号不存在']);
                    }
                    $result = action('user/api/send_sms', ['SMS_1', '', $data['info']['phone']['value'], [], $attr['captcha']]);
                    $result = json_decode($result->getContent(), 1);
                    if ($result['code'] == 1) {
                        return json(['code' => 2, 'msg' => '验证码发送成功']);
                    } else {
                        return json(['code' => 0, 'msg' => $result['msg']]);
                    }
                }
            }
            if ($status == 1) {
                $key = create_str();
                $cache_data = cache($key);
                if (empty($cache_data)) {
                    $cache_data = [
                        'data_id' => $attr['data_id'],
                        'time' => time(),
                    ];
                    cache($key, $cache_data, 600);
                }
                if (empty(session('owner_datas'))) {
                    session('owner_datas', [$attr['data_id']]);
                }else{
                    array_push(session('owner_datas'), $attr['data_id']);
                }
                return json(['code' => 1, 'msg' => '验证成功', 'data' => $data, 'key' => $key]);
            }

            return json(['code' => 0, 'msg' => '验证失败']);
        } elseif (request()->isGet()) {
            if ($key && $id) {
                $rs = $this->query(['key' => $key, 'id' => $id]);
                if (!self::$sys['is_mobile']) $rs = $this->_init_data($rs);
                $this->assign('rs', $rs);
            }
            return view('../manage');
        }

        return json(['code' => 0, 'msg' => '非法操作']);
    }
}
