<?php
/**
 * +------------------------------------------------------------
 * | 数据-管理 (index/controller/Admin.php)
 * +------------------------------------------------------------
 * | @author: zhx (10630650@qq.com)
 * | @create_time: 2018-03-09 11:32:24
 * +------------------------------------------------------------
 * | @copyright: CIM信息聚合系统 (https://cimxx.com)
 * +------------------------------------------------------------
 * | @last_modified_by: zhx
 * | @last_modified_time: 2018-03-09 11:32:24
 * +------------------------------------------------------------
 * | @todo:
 * +------------------------------------------------------------
 */

namespace app\index\controller;

use app\index\model\Column;
use think\Db;
use think\Hook;
use app\common\controller\Fields;

class Admin extends Module
{
    private static $fields;

    protected function initialize()
    {
        parent::initialize();
        $this->assign('column', self::$column);
        if (in_array(self::$sys['action'], ['fields', 'fields_form', 'fields_forbid', 'fields_delete', 'fields_status'])) self::$fields = new Fields();
    }


    /**
     * 管理首页
     */
    public function overview()
    {
        $data = [];
        //统计
        $data['count'] = [
            'info' => db('data')->count(),
            'column' => db('column')->count(),
            'feedback' => db('feedback')->count(),
            'report' => db('report')->count(),
            'review' => db('data')->where('status', '=', 0)->count(),
            'comment' => db('comment')->count()
        ];
        //举报
        $data['reports'] = model('report')->with('datas')->order('create_time desc')->limit(10)->select();
        if (!empty($data['reports'])) {
            $columns = load_columns(0, 0, '', '', '');
            foreach ($data['reports'] as $k => &$v) $v['column_name'] = isset($columns[$v['column_id']]) ? $columns[$v['column_id']]['name'] : '';
        }
        //图表
        $result = [];
        $model = config('app.models');
        unset($model['common'], $model['pages']);
        $columns = db('column')->field('group_concat(id) id,model')->group('model')->column('group_concat(id) id,model', 'model');
        if (!empty($columns)) {
            foreach ($columns as $k => $v) {
                $column[$k] = array_column(db('data')->where("`create_time`>UNIX_TIMESTAMP(DATE_SUB(CURDATE(), INTERVAL 7 DAY))")->where('column_id', 'in', explode(',', $v))->group("day")->field("count(*) as count,FROM_UNIXTIME(create_time, '%m-%d') as day")->select(), null, 'day');
            }
            for ($i = 7; $i >= 1; $i--) {
                $day = date("m-d", strtotime("-" . $i . " day"));
                foreach ($model as $k => $v) $rs[$v['name']] = empty($column[$k][$day]['count']) ? 0 : $column[$k][$day]['count'];
                $result['data'][] = array_merge(['day' => $day], $rs);
            }
        }
        $result['fields'] = array_column($model, 'name');
        $data['chart'] = $result;
        return json(['code' => 1, 'data' => $data]);
    }

    /**
     * 内容管理
     */
    public function data($cid = '', $keyword = '', $page = 1, $status = '', $limit = 20)
    {
        $attr = [
            'page' => $page,
            'limit' => $limit
        ];
        if (isset(self::$column['model'])) {
            $attr['cid'] = $cid;
            $attr['model'] = self::$column['model'];
            if (self::$column['model'] == 'info') $attr['with'] = 'info';
        }
        $attr['where'][] = ['id', 'neq', ''];
        if (!empty($keyword)) $attr['where'][] = ['name', 'like', '%' . $keyword . '%'];
        if ($status != '') $attr['where'][] = ['status', '=', $status];
        $attr['field'] = ',status,list_order';
        $attr['where'][] = ['delete_time', '=', '0'];
        $rs = $this->query($attr);
        $rs = $this->_init_data($rs);
        $columns = columns_to_array(load_columns(1, 0, '', '', ''));
        $rs['name'] = isset(self::$column['name']) ? self::$column['name'] : '';
        return json(['code' => 1, 'data' => $rs, 'columns' => $columns]);
    }

    /**
     * 数据新增 / 修改
     */
    public function form($cid = 0, $id = 0)
    {
        if (!$cid) return json(['code' => 15001, 'msg' => '参数错误']);
        if (request()->isPost()) {
            $data = input('post.');
            $data['column_id'] = $cid;
            $data['id'] = $id;
            self::$column = self::$columns[$data['column_id']];
            if (in_array(self::$column['model'], ['article', 'links'])) $data['area_id'] = 0;
            $result = $this->_add($data);
            if ($result['code']) {
                cache('data_view_' . $id, null);
                return json(['code' => 1, 'msg' => '数据《' . $data['name'] . '》已更新。']);
            } else {
                return json(['code' => 15002, 'msg' => '出了点问题，重新提交试试.. [' . $result['msg'] . ']']);
            }
        } else {
            if ($id) {
                $rs = $this->query(['cid' => $cid, 'id' => $id, 'where' => [['id', 'neq', '']]]);
                if (!empty($rs)) {
                    $rs['end_time_day'] = $rs['end_time_day'];
                    $rs = $rs->toArray();
                    if (isset($rs['info']['ip'])) {
                        $rs['ip_location'] = \get_ip_address($rs['info']['ip']);
                    }
                }
            }
            //处理自定义字段
            $column_fields = load_fields($cid);
            if (!empty($column_fields)) {
                $fields = empty($rs['fields']) ? '' : (array)$rs['fields'];
                if (!empty($fields)) {
                    foreach ($fields as $k => $v) {
                        if (isset($column_fields[$k])) {
                            if ($column_fields[$k]['type'] == 2) {
                                if (!is_array($v)) $fields[$k] = [];
                            } else {
                                if (!is_string($v)) $fields[$k] = '';
                            }
                        }
                    }
                }
                $column_fields = array_values($column_fields);
                foreach ($column_fields as $k => $v) $column_fields[$k]['values'] = isset($fields[$v['key']]) ? $fields[$v['key']] : ($v['type'] == 2 ? [] : '');
            }
            $rs['column_fields'] = $column_fields;
            //处理地区
            $areas = array_values(load_areas());
            if (!empty($areas)) {
                foreach ($areas as $k => $v) {
                    if (!empty($v['child'])) $areas[$k]['child'] = array_values($v['child']);
                }
            }
            $rs['areas'] = $areas;
            $rs['column'] = load_column($cid, 0, '');
            return json(['code' => 1, 'data' => $rs]);
        }
    }

    /**
     * 栏目
     */
    public function column($model = [])
    {
        //栏目发布数据总数
        $counts = db('data')->field("count(*) as total, column_id")->where('delete_time', 'eq', '0')->cache(true, 86400)->group("column_id")->column('count(*)', 'column_id');
        //栏目今天发布数量
        $t_counts = db('data')->field('count(*) as total,column_id')->where("FROM_UNIXTIME(create_time, '%Y%m%d')=" . date('Ymd'))->where('delete_time', '=', 0)->cache(true, 86400)->group('column_id')->column('count(*)', 'column_id');
        //栏目今日刷新数量
        $t_counts_up = db('data')->field('count(*) as total,column_id')->where("FROM_UNIXTIME(update_time, '%Y%m%d')=" . date('Ymd'))->where('delete_time', '=', 0)->cache(true, 86400)->group('column_id')->column('count(*)', 'column_id');
        //栏目昨日发布数量
        $y_counts = db('data')->field('count(*) as total,column_id')->where("FROM_UNIXTIME(create_time, '%Y%m%d')=" . date('Ymd', time() - 86400))->where('delete_time', '=', 0)->cache(true, 86400)->group('column_id')->column('count(*)', 'column_id');
        //评论数量
        $comment_count = db('comment')->group('column_id')->where('column_id', 'neq', 0)->column('count(*)', 'column_id');
        $columns = load_columns(0, 0, '', $model, '');
        if (!empty($columns)) {
            $models = config('app.models');
            foreach ($columns as $k => &$v) {
                $v['model_name'] = isset($models[$v['model']]) ? $models[$v['model']]['name'] : '';
                $v['count'] = empty($counts[$v['id']]) ? 0 : $counts[$v['id']];
                $v['t_counts'] = empty($t_counts[$v['id']]) ? 0 : $t_counts[$v['id']];
                $v['t_counts_up'] = empty($t_counts_up[$v['id']]) ? 0 : $t_counts_up[$v['id']];
                $v['y_counts'] = empty($y_counts[$v['id']]) ? 0 : $y_counts[$v['id']];
                $v['comment_count'] = empty($comment_count[$v['id']]) ? 0 : $comment_count[$v['id']];
            }
            $columns = columns_to_array($columns);
        }
        return json(['code' => 1, 'data' => $columns]);
    }

    /**
     * 栏目新建/修改
     */
    public function column_form($id = 0)
    {
        if (request()->isPost()) {
            $data = input('post.');
            if ($id && isset($data['extends'])) {
                $column = Column::get($id);
                if (!empty($column)) {
                    $setting = $column->toArray()['setting'];
                    $setting['fields'] = [
                        'extends' => $data['extends']
                    ];
                    model('Column')->allowField(true)->save(['setting' => $setting], ['id' => $id]);
                    \load_columns(0, 1);
                    load_fields($id, 1);
                } else {
                    return json(['code' => 15003, 'msg' => '栏目不存在']);
                }
                return json(['code' => 1, 'msg' => '保存成功']);
            }
            $validate = validate('Column');
            if (!$validate->check($data)) return json(['code' => 0, 'msg' => $validate->getError()]);
            if ($id > 0 && $data['parent_id'] == $id) return json(['code' => 15004, 'msg' => '上级栏目不能选择自己。']);
            if (!empty($data['sync_column_id'])) {
                model('Column')->allowField(true)->save(['setting' => $data['setting']], [['id', 'in', $data['sync_column_id']]]);
            }
            $column = Column::where('key', '=', $data['key'])->find();
            if ($data['model'] == 'pages' && empty($data['pages']['content'])) return json(['code' => 15005, 'msg' => '内容不能为空...']);
            if ($id) {
                if (!empty($column) && $column['id'] != $id) return json(['code' => 15006, 'msg' => '栏目标识已存在,请更换...']);
                $_model = Column::get($id);
                $_model->allowField(true)->update($data, ['id' => $id]);
                if (isset($data[$_model->model])) {
                    $_tmp = $_model->model;
                    if (model($_tmp)->where('column_id', $id)->count()) {
                        $_model->$_tmp->save($data[$_model->model]);
                    } else {
                        $_model->$_tmp()->save($data[$_model->model]);
                    }
                }
                \load_columns(0, 1);
                //更新栏目自定义字段
                load_fields($id, 1);
                return json(['code' => 1, 'msg' => '栏目《' . $data['name'] . '》已更新。', 'column']);
            } else {
                if (!empty($column)) return json(['code' => 15006, 'msg' => '栏目标识已存在,请更换...']);
                $rs = Column::create($data, true);
                if ($rs->id) {
                    if (isset($data[$data['model']])) {
                        $_tmp = $data['model'];
                        $data[$data['model']]['column_id'] = $rs->id;
                        $rs->$_tmp()->save($data[$data['model']]);
                    }
                    \load_columns(0, 1);
                    return json(['code' => 1, 'msg' => '栏目《' . $data['name'] . '》已创建。']);
                } else {
                    return json(['code' => 15007, 'msg' => '出了点问题，返回重新提交试试..']);
                }
            }
        } else {
            $rs = ['name' => '', 'list_order' => 0, 'keywords' => '', 'description' => '', 'parent_id' => 0];
            if ($id == 0) $rs['list_order'] = db('column')->max('id') + 1;
            if ($id) {
                $rs = model('column')->find($id);
                if ($rs['model'] == 'pages') $rs['pages'] = model('pages')->find($id);
            }
            $groups = action('user/api/group');
            if (!empty($groups)) {
                foreach ($groups as $k => $v) $groups[$k]['column_setting'] = empty($rs['setting']['group'][$v['id']]) ? [] : $rs['setting']['group'][$v['id']];
            }
            return json(['code' => 1, 'data' => [
                'rs' => $rs,
                'columns' => columns_to_array(load_columns(1, 0, '', '', '')),
                'models' => config('app.models'),
                'groups' => $groups,
                'template' => [
                    'list' => $this->load_tpls('column'),
                    'view' => $this->load_tpls('view'),
                    'add' => $this->load_tpls('add'),
                ],
            ]]);
        }
    }

    /**
     * 更改栏目状态
     */
    public function column_status($id = [], $status = 1)
    {
        if ($id && in_array($status, [0, 1])) {
            db('column')->where('id', 'in', (array)$id)->setField('status', $status);
            \load_columns(0, 1);
            return json(['code' => 1, 'msg' => '栏目状态更新成功']);
        }
        return json(['code' => 15008, 'msg' => '更改栏目状态失败,请选择要更改的栏目']);
    }

    /**
     * @param $id
     * @param int $delete 是否清除栏目下的数据
     * @return \think\response\Json
     */
    public function column_delete($id, $delete = 0)
    {
        if (db('column')->where('parent_id', '=', $id)->count()) return json(['code' => 15009, 'msg' => '请先删除该栏目下的子栏目。']);
        $count = db('data')->where('column_id', $id)->count();
        if ($count != 0) {
            if (!$delete) return json(['code' => 15010, 'msg' => '此栏目包含回收站共有' . $count . '条数据，请先清理数据后删除。']);
            if ($delete) {
                $data_id = db('data')->where('column_id', '=', $id)->column('id');
                //删除数据
                db('data')->where('column_id', '=', $id)->delete();
                //删除信息表数据
                db('info')->where('data_id', 'in', $data_id)->delete();
                //删除文章表数据
                db('article')->where('data_id', 'in', $data_id)->delete();
                //删除链接表数据
                db('links')->where('data_id', 'in', $data_id)->delete();
                //删除电话表数据
                db('phone')->where('data_id', 'in', $data_id)->delete();
            }
        }
        $column = db('column')->where('id', '=', $id)->find();
        db('column')->where('id', $id)->delete();
        \load_columns(0, 1);
        action('user/api/log', ['删除栏目【' . $column['name'] . '】', '栏目id:' . $id]);
        return json(['code' => 1, 'msg' => '栏目删除成功']);
    }

    /**
     * 评论管理
     */
    public function comment($id = [])
    {
        if (request()->isPost()) {
            $data = db('comment')->where('id', 'in', $id)->select();
            if (!empty($data)) {
                foreach ($data as $k => $v) {
                    if ($v['comment_id'] != 0) {
                        //回复
                        $reply[] = $v['comment_id'];
                        $comment[] = $v['data_id'];
                    } else {
                        $comment[] = $v['data_id'];
                    }
                }
                if (!empty($reply)) db('comment')->where('id', 'in', $reply)->setInc('reply_count');
                if (!empty($comment)) {
                    foreach ($comment as $k => $v) db('data')->where('id', '=', $k)->setInc('comment_count', $v);
                }
                db('comment')->where('id', 'in', $id)->setField('status', 1);
            }
            return json(['code' => 1, 'msg' => '审核成功']);
        }
        $attr = input('param.');
        $where = [];
        $limit = isset($attr['limit']) ? $attr['limit'] : 20;
        $order = 'create_time desc';
        $page = isset($attr['page']) ? $attr['page'] : 1;
        if (isset($attr['keyword'])) $where[] = ['content', 'like', '%' . $attr['keyword'] . '%'];
        if (isset($attr['status']) && in_array($attr['status'], [0, 1])) $where[] = ['status', '=', $attr['status']];
        if (isset($attr['column_id'])) $where[] = ['column_id', '=', $attr['column_id']];
        $data = model('comment')->with('user')->where($where)->order($order)->paginate($limit)->toArray();
        if (!empty($data['data'])) {
            foreach ($data['data'] as $k => &$v) {
                if (empty($v['user'])) $v['user'] = [];
            }
        }
        return json(['code' => 1, 'data' => $data]);
    }

    /*
     * 评论删除
     */
    function comment_delete($id = [])
    {
        if (!empty($id)) {
            $data = db('comment')->where('id', 'in', $id)->select();
            if (!empty($data)) {
                $comment = [];
                foreach ($data as $k => $v) {
                    $floor = db('comment')->where('id', '=', $v['id'])->value('floor');
                    $where = [
                        ['floor', '>', $floor]
                    ];
                    if ($v['comment_id'] != 0) {
                        $comment[] = $v['data_id'];
                        $reply[] = $v['comment_id'];
                        $where[] = ['comment_id', '=', $v['comment_id']];
                        //改变回复的楼层
                        db('comment')->where($where)->setDec('floor');
                    } else {
                        $comment[] = $v['data_id'];
                        $where[] = ['data_id', '=', $v['data_id']];
                        //改变评论的楼层
                        db('comment')->where($where)->setDec('floor');
                    }
                }
                if (!empty($reply)) {
                    //更改评论的回复数量
                    $reply = array_count_values($reply);
                    foreach ($reply as $k => $v) {
                        db('comment')->where('id', '=', $k)->setDec('reply_count', $v);
                    }
                }
                if (!empty($comment)) {
                    $comment = array_count_values($comment);
                    foreach ($comment as $k => $v) {
                        db('data')->where('id', '=', $k)->setDec('comment_count', $v);
                    }
                }
                db('comment')->where('id', 'in', $id)->delete();
            }
        }
        return json(['code' => 1, 'msg' => '评论删除成功', 'errcode' => 0]);
    }


    /**
     * 举报
     */
    public function report()
    {
        $rs = db('report')->alias('r')->leftJoin('data d', 'r.data_id = d.id')->field('r.*, d.name')->paginate(20)->toArray();
        if (!empty($rs['data'])) {
            $types = config('app.report');
            $columns = load_columns(0, 0, '', '', '');
            foreach ($rs['data'] as $k => &$v) {
                $v['type_name'] = $types[$v['type']];
                $v['url'] = $this->request->domain() . '/' . (empty($columns[$v['column_id']]['key']) ? $v['data_id'] : $columns[$v['column_id']]['key']) . '/' . $v['data_id'];
            }
        }
        return json(['code' => 1, 'data' => $rs]);
    }

    /**
     * 锁定举报信息
     */
    public function report_delete($id = [], $data_id = [])
    {
        //删除举报信息
        if ($id) {
            db('report')->where('id', 'in', (array)$id)->delete();
        }
        //关闭被举报信息
        if ($data_id) {
            db('report')->where('data_id', 'in', (array)$data_id)->setField(['status' => -1]);
            db('data')->where('id', 'in', (array)$data_id)->setField(['status' => -1]);
        }
        return json(['code' => 1, 'msg' => '操作成功']);
    }

    /**
     * 扩展字段
     */
    public function fields($relation_id = 0)
    {
        return self::$fields->fields($relation_id);
    }

    /**
     * 继承自定义字段禁用
     */
    function fields_forbid($fields_id = 0, $relation_id = 0)
    {
        return self::$fields->forbid($fields_id, $relation_id, 'column');
    }

    /**
     * 扩展字段 添加 / 修改
     */
    function fields_form($id = 0)
    {
        return self::$fields->form($id, 'column');
    }

    /**
     * 扩展字段 删除
     */
    public function fields_delete($id = [])
    {
        return self::$fields->delete($id, 'column');
    }

    /**
     * 批量改变字段状态
     */
    function fields_status($id = [], $status = '', $relation_id = 0)
    {
        return self::$fields->status($id, $status, $relation_id);
    }

    /**
     * 移动
     */
    public function move($id = [], $column_id = 0)
    {
        if (!empty($column_id) && !empty($id)) {
            $data = db('data')->where('id', '=', ((array)$id)[0])->find();
            $columns = load_columns(0, 0, '', '', '');
            if ($columns[$data['column_id']]['model'] != $columns[$column_id]['model']) return json(['code' => 15011, 'msg' => '数据移动失败,栏目模型必须一致']);
            db('data')->where('id', 'in', $id)->update(['column_id' => $column_id]);
            action('user/Api/log', ['批量移动信息', '信息ID:' . join(',', $id) . ' 新栏目ID:' . $column_id]);
            return json(['code' => 1, 'msg' => '您选择的信息已移动到新栏目。']);
        }
        return json(['code' => 15012, 'msg' => '请选择要移动的数据']);
    }

    /**
     * 审核
     */
    public function check($id = [])
    {
        db('data')->where('id', 'in', $id)->update(['status' => 1]);
        return json(['code' => 1, 'msg' => '信息审核成功']);
    }

    /**
     * 待审核内容
     */
    function review()
    {
        $data = db('data')
            ->where('status', '=', 0)
            ->where('delete_time', '=', 0)
            ->order('create_time desc')
            ->paginate(20)->toArray();
        if (!empty($data['data'])) {
            $data = $this->_init_data($data);
            $columns = load_columns(0, 0, '', '', '');
            $areas = load_areas(0);
            $models = config('app.models');
            foreach ($data['data'] as $k => &$v) {
                $v['model_name'] = $models[$columns[$v['column_id']]['model']]['name'];
                $v['column_name'] = $columns[$v['column_id']]['name'];
                $v['area_name'] = isset($areas[$v['area_id']]['name']) ? $areas[$v['area_id']]['name'] : '';
            }
        }
        return json(['code' => 1, 'data' => $data]);
    }

    /**
     * 置顶
     */
    public function top($data_id = 0)
    {
        if (request()->isPost()) {
            $data = input('post.');
            if (isset($data['top_end_time'])) $data['top_end_time'] = strtotime($data['top_end_time']);
            db('data')->where('id', '=', $data_id)->update(['top_end_time' => $data['top_end_time']]);
            return json(['code' => 1]);
        } else {
            $rs = db('info')->alias('i')->join('data d', 'i.data_id=d.id')->field('d.id, d.name, i.linkman, i.phone, i.email,d.top_end_time')->find($data_id);
            if ($rs['top_end_time']) $rs['top_end_time'] = date('Y-m-d H:i:s', $rs['top_end_time']);
            return json(['code' => 1, 'data' => $rs]);
        }
    }

    /**
     * @param array $id 数据id
     */
    public function cancel_top($id = [])
    {
        if ($id) {
            db('data')->where('id', 'in', $id)->setField('top_end_time', 0);
            action('user/Api/log', ['取消信息置顶', '信息ID:' . join(',', $id)]);
            return json(['code' => 1, 'msg' => '取消置顶成功']);
        }
        return json(['code' => 15013, 'msg' => '请选择要取消置顶的数据']);
    }

    /**
     * @param array $id 数据id
     * @param int $num 数据条数
     * @param int $time 随机的分钟数
     * @param int $cid 栏目id
     */
    public function refresh($id = [], $num = 0, $time = 0, $cid = 0)
    {
        if ($cid) {
            $where = [];
            if ($id) {
                $where[] = ['id', 'in', $id];
            } else if ($num) {
                if ($num < 0 || !is_int($num)) return json(['code' => 15014, 'msg' => '无效的数量参数']);
                $id = db('data')->where('column_id', '=', $cid)->where('status', '=', 1)->column('id');
                if (empty($id)) return json(['code' => 15015, 'msg' => '栏目无有效信息']);
                shuffle($id);
                $id = array_slice($id, 0, $num);
                $where[] = ['id', 'in', $id];
            } else {
                return json(['code' => 15016, 'msg' => '请选择要操作的数据或选择要处理的数据条数']);
            }
            db('data')->where($where)->setField(['update_time' => time()]);
            action('user/Api/log', ['刷新信息', '信息ID:' . join(',', (array)$id)]);
            return json(['code' => 1, 'msg' => '信息刷新成功']);
        }
        return json(['code' => 15017, 'msg' => '请选择栏目']);
    }

    /**
     * 删除
     */
    public function delete($id = [], $delete = 0)
    {
        if ($delete) {
            if ($delete == 'all') $id = db('data')->where('delete_time', 'neq', 0)->column('id');
            $rs = db('data')->where('id', 'in', (array)$id)->column('*', 'id');
            //删除
            db('data')->where('id', 'in', (array)$id)->delete();
            db('info')->where('data_id', 'in', (array)$id)->delete();
            //删除文章表数据
            db('article')->where('data_id', 'in', (array)$id)->delete();
            //删除链接表数据
            db('links')->where('data_id', 'in', (array)$id)->delete();
            //删除电话表数据
            db('phone')->where('data_id', 'in', (array)$id)->delete();
            $source = [];
            foreach ($rs as $k => $v) {
                $rss = db('data_image')->where('data_id', '=', $k)->select();
                //删除附件数据
                db('data_image')->where('data_id', '=', $k)->delete();
                if (!empty($rss)) {
                    $source[] = [
                        'data_id' => $k,
                        'path' => array_column($rss, 'path'),
                        'fields' => 'data_image|path'
                    ];
                }
                if (!empty($v['thumb'])) {
                    $source[] = [
                        'data_id' => $k,
                        'path' => $v['thumb'],
                        'fields' => 'data|thumb'
                    ];
                }
                if (!empty($source)) action('files/api/update_file_info', [[], $source]);
                action('user/Api/log', ['删除数据', '数据ID:' . $k . ' 标题:' . $v['name']]);
            }
        } else {
            //软删除
            Db::name('data')->where('id', 'in', (array)$id)->useSoftDelete('delete_time', time())->delete();
        }
        return json(['code' => 1, 'msg' => '操作成功']);
    }

    /**
     * 回收站
     */
    function recycle($limit = 20, $keyword = '')
    {
        $where = [
            ['delete_time', 'neq', 0]
        ];
        if ($keyword) $where[] = ['name', 'like', '%' . $keyword . '%'];
        $data = db('data')
            ->where($where)
            ->order('delete_time desc')
            ->paginate($limit)->toArray();
        if (!empty($data['data'])) {
            $data = $this->_init_data($data);
            $columns = load_columns(0, 0, '', '', '');
            $areas = load_areas(0);
            $models = config('app.models');
            foreach ($data['data'] as $k => &$v) {
                $v['model_name'] = $models[$columns[$v['column_id']]['model']]['name'];
                $v['column_name'] = $columns[$v['column_id']]['name'];
                $v['area_name'] = !empty($areas[$v['area_id']]['name']) ? $areas[$v['area_id']]['name'] : '';
                $v['time'] = time_format($v['delete_time']);
                $v['create_time'] = time_format($v['create_time']);
            }
        }
        return json(['code' => 1, 'data' => $data]);
    }

    /**
     * 数据恢复
     */
    function recover($id = [])
    {
        db('data')->where('id', 'in', $id)->update(['delete_time' => 0]);
        return json(['code' => 1, 'msg' => '数据恢复成功']);
    }

    /**
     * 加载模板
     */
    private function load_tpls($path)
    {
        $rs = [];
        $files = get_files(config('template.view_base') . $path);
        foreach ($files as $v) {
            $rs[] = basename($v, '.' . config('template.view_suffix'));
        }
        return $rs;
    }

    /**
     * 解析栏目
     */
    private function _column($val = '', $type = 'key')
    {
        $columns = \load_columns(0, 0, $type, [], '');
        return isset($columns[$val]) ? $columns[$val] : [];
    }

    /**
     * 空方法解析
     */
    public function _empty($name)
    {
        if (in_array($name, array('area_add', 'area_edit'))) {
            return $this->area_form(input('param.id'));
        }
        if (in_array($name, array('fields_add', 'fields_edit'))) {
            return $this->fields_form(input('param.id', 0));
        }
        if (in_array($name, array('column_add', 'column_edit'))) {
            return $this->column_form(input('param.id', 0));
        }
        if (in_array($name, array('add', 'edit'))) {
            if (!input('?param.cid')) $this->error('目标栏目错误');
            return $this->form(input('param.cid'), input('param.id', 0));
        }
        return parent::_empty($name);
    }

    public function group_data($data = '', $field = 'create_time')
    {
        if (!empty($data)) {
            for ($i = 6; $i >= 0; $i--) {
                $time[] = [strtotime(date('Y-m-d', time() - ($i + 1) * 24 * 3600)), strtotime(date('Y-m-d', time() - $i * 24 * 3600))];
            }
            $result = array_fill(0, 7, '0');
            foreach ($data as $k => $v) {
                foreach ($time as $kk => $vv) {
                    if ($v[$field] >= $vv[0] && $v[$field] <= $vv[1]) {
                        $result[$kk] += 1;
                        continue;
                    }
                }
            }
        } else {
            $result = array_fill(0, 7, '0');
        }
        return $result;
    }

    /**
     * 发送整改信息
     */
    public function send_modify()
    {
        $rule = ['content' => 'require|max:500', 'id' => 'require|number', 'module' => 'require'];
        $data = request()->only(['module', 'content', 'id']);
        $result = $this->validate($data, $rule);
        if (true !== $result) {
            return json(['code' => 0, 'message' => $result]);
        }
        $rs = db($data['module'])->field('uid')->where('id', $data['id'])->find();
        $param = [$rs['uid'], $data['module'], $data['content']];
        Hook::listen('message', $param);
        return json(['code' => 1, 'message' => '发送成功']);
    }

    /** 举报详情信息
     * @return mixed
     */
    public function report_detail()
    {
        $param = request()->only('module,id');
        $data = Report::where($param)
            ->order('create_time desc')
            ->paginate();
        return json(['code' => 1, 'data' => $data]);
    }

    /**
     * 删除反馈
     * @param array $id
     */
    function feedback_delete($id = [])
    {
        $where = [];
        if ($id) {
            $where [] = ['id', 'in', (array)$id];
        }
        model('app\index\model\Feedback')->where($where)->delete();
        return json(['code' => 1, 'msg' => '删除成功']);
    }


    /**
     * 反馈回复
     * @return \think\response\Json
     */
    function feedback_reply()
    {
        $data = input('post.');
        $result = $this->validate($data, [
            'feedback_id' => 'require',
            'content' => 'require',
            'type' => 'require'
        ], [
            'feedback_id.require' => '请选择要回复的反馈信息',
            'content.require' => '回复内容不能为空',
            'type.require' => '请选择回复方式',
        ]);
        if ($result !== true) $this->error($result);
        $feedback = action('index/admin/feedback', [[
            'id' => $data['feedback_id'],
            'with' => 'user'
        ], 0]);
        if ($feedback['status'] == 2) return json(['code' => 0, 'msg' => '您已回复']);
        //type: 1站内信，2邮箱
        $type = $data['type'];
        if (is_array($data['type'])) {
            $data['type'] = join(',', $data['type']);
        }
        $data['admin_id'] = session('admin.id');
        foreach ((array)$type as $k => $v) {
            if ($v == 1) {
                $message = [
                    'content' => $data['content'],
                    'user_id' => $feedback['user_id'],
                    'extend' => [
                        'id' => $data['feedback_id']
                    ]
                ];
                action('message/api/send', [$message]);
            }
            if ($v == 2) {
                $email = ($this->validate(['email' => $feedback['linkway']], ['email' => 'require|email']) === true) ? $feedback['linkway'] : (empty($feedback['user']['email']) ? '' : $feedback['user']['email']);
                if ($email) {
                    $attr['email'] = $email;
                    $attr['type'] = 'reply';
                    $attr['data'] = ['content' => $data['content']];
                    action('user/api/send_email', [$attr]);
                }
            }
        }
        model('app\index\model\Feedback')->where('id', '=', $data['feedback_id'])->update(['status' => 2]);
        return json(['code' => 1, 'msg' => '回复成功']);
    }

    /**
     * 导出栏目
     * @param array $id
     */
    function export($id = [])
    {
        if (!empty($id)) {
            $file_name = '栏目配置' . date('Y-m-d');
            if (is_string($id)) $id = explode(',', $id);
            $column = model('column')->with('fields')->where('id', 'in', $id)->select()->toArray();
            if (!empty($column)) {
                $data = [];
                foreach ($column as $k => $v) {
                    $data[$k] = [
                        'model' => $v['model'] ?: ' ',
                        'name' => $v['name'] ?: ' ',
                        'key' => $v['key'] ?: ' ',
                        'title' => $v['title'] ?: ' ',
                        'keywords' => $v['keywords'] ?: ' ',
                        'description' => $v['description'] ?: ' ',
                        'url' => $v['url'] ?: ' ',
                        'setting' => $v['setting'] ? json_encode($v['setting']) : ' ',
                        'list_order' => $v['list_order'],
                        'status' => $v['status'],
                        'fields' => $v['fields'] ? json_encode($v['fields']) : ' ',
                        'id' => $v['id'],
                        'parent_id' => $v['parent_id']
                    ];
                }
                action('user/Api/log', ['导出栏目']);
                $this->save_excel($file_name, ['模型', '名称', '标识', '标题', '关键字', '描述', '链接', '栏目配置', '列表排序', '状态', '扩展字段', 'ID', '父ID'], $data);
            }
        }
        return json(['code' => 15018, 'msg' => '请选择要导出的数据']);
    }

    /**
     * 导入栏目
     */
    function import()
    {
        if (request()->isPost()) {
            $files = request()->file();
            if (!empty($files)) {
                $fileinfo = $files['file']->getInfo();
                $result = $this->load_excel($fileinfo['tmp_name']);
                if (!empty($result)) {
                    $field = ['model', 'name', 'key', 'title', 'keywords', 'description', 'url', 'setting', 'list_order', 'status', 'fields', 'id', 'parent_id'];
                    $max_column_id = db('column')->max('id');
                    $add_nums = [
                        '+' => 0,
                        '-' => 0,
                        'data' => []
                    ];
                    try {
                        foreach ($result as $k => $v) {
                            $data = array_combine(array_slice($field, 0, count($v)), array_values($v));
                            if (isset($data['id'])) {
                                $add_nums['data'][] = $max_column_id - $data['id'];
                                if ($max_column_id - $data['id'] > 0) $add_nums['+'] = 1;
                                if ($max_column_id - $data['id'] < 0) $add_nums['-'] = 1;
                            }
                            if (isset($data['parent_id']) && $data['parent_id'] != 0) {
                                $add_nums['data'][] = $max_column_id - $data['parent_id'];
                                if ($max_column_id - $data['parent_id'] > 0) $add_nums['+'] = 1;
                                if ($max_column_id - $data['parent_id'] < 0) $add_nums['-'] = 1;
                            }
                            $column [] = $data;
                        }
                        if (!empty($add_nums['data'])) {
                            if ($add_nums['+'] && $add_nums['-']) {
                                $add_num = max($add_nums['data']) + 1;
                            } else {
                                if ($add_nums['+']) $add_num = max($add_nums['data']) + 1;
                                if ($add_nums['-']) $add_num = 1;
                            }
                            foreach ($column as $k => $v) {
                                if (isset($v['id'])) $column[$k]['id'] += $add_num;
                                if (isset($v['parent_id']) && $v['parent_id'] != 0) $column[$k]['parent_id'] += $add_num;
                            }
                        }
                        return json(['code' => 1, 'data' => [
                            'data' => $column,
                            'columns' => array_merge(columns_to_array(load_columns(1, 0, '', '', '')), $column, [[
                                'name' => '作为顶级栏目',
                                'id' => 0,
                                'parent_id' => 0,
                                'key' => ''
                            ]])
                        ]]);
                    } catch (\Exception $e) {
                        return json(['code' => 15019, 'msg' => '导入文件格式错误']);
                    }
                } else {
                    return json(['code' => 15020, 'msg' => '导入数据为空']);
                }
            }
            $column = input('post.column/a', '');
            if (!empty($column)) {
                if (count($column) != count(array_column($column, 'key'))) return json(['code' => 15021, 'msg' => '栏目标识不能为空']);
                foreach ($column as $k => &$v) {
                    if (empty($v['name']) || empty($v['key'])) return json(['code' => 15022, 'msg' => '栏目名称和标识不能为空,请检查后重试....']);
                    if (!empty($v['setting'])) $v['setting'] = json_decode($v['setting'], 1);
                    if (!empty(trim($v['fields']))) {
                        $fields[$v['key']] = $v['fields'];
                    }
                    unset($column[$k]['fields']);
                }
                $key = array_column($column, 'key');
                if (!empty($key)) {
                    $data = db('column')->where('key', 'in', $key)->column('key');
                    $intersect = array_intersect($key, $data);
                    if (!empty($intersect)) return json(['code' => 15023, 'msg' => '栏目标识不能重复，请更改标识【' . join(',', $intersect) . '】']);
                }
                //写入栏目
                model('app\index\model\Column')->saveAll($column, false);
                //写入栏目自定义字段
                if (!empty($fields)) {
                    $column = db('column')->where('key', 'in', array_keys($fields))->column('id', 'key');
                    $fields_data = [];
                    foreach ($fields as $k => $v) {
                        $v = json_decode($v, 1);
                        foreach ($v as $kk => $vv) {
                            unset($v[$kk]['id']);
                            $v[$kk]['relation_id'] = $column[$k];
                            if (!empty($vv['value'])) $v[$kk]['value'] = json_encode($vv['value']);
                        }
                        $fields_data = array_merge($fields_data, $v);
                    }
                    model('app\index\model\Fields')->insertAll($fields_data);
                }
                \load_columns(0, 1);
                return json(['code' => 1, 'msg' => '栏目导入成功']);
            }
        }
    }

    /**
     * 返回配置项
     */
    function configs()
    {
        return json(['code' => 1, 'data' => [
            'search' => config('app.search'),
            'reply' => config('app.reply'),
            'feedback_status' => config('app.feedback_status'),
            'report' => config('app.report'),
            'fields_types' => config('app.fields')['types']]
        ]);
    }

    /**
     * 反馈数据
     * @param array $attr
     * @param int $return
     * @return array|null|\PDOStatement|string|\think\Model|\think\response\Json
     */
    function feedback($attr = [], $return = 1)
    {
        if (is_string($attr)) $attr = json_decode($attr, 1);
        $where = [];
        if (isset($attr['start_time']) && isset($attr['end_time'])) {
            $where[] = ['create_time', 'between', [strtotime($attr['start_time']), strtotime($attr['end_time'])]];
        } else {
            if (isset($attr['start_time'])) {
                $where[] = ['create_time', '>', strtotime($attr['start_time'])];
            }
            if (isset($attr['end_time'])) {
                $where[] = ['create_time', '<', strtotime($attr['start_time'])];
            }
        }
        if (isset($attr['status'])) {
            $where[] = ['status', '=', $attr['status']];
        }
        if (isset($attr['keyword'])) {
            $where[] = ['title', 'like', '%' . $attr['keyword'] . '%'];
        }
        $with = isset($attr['with']) ? $attr['with'] : '';
        $feedback = model('app\index\model\Feedback')->where($where)->order('create_time desc')->with($with);
        if (isset($attr['tags'])) {
            $feedback = $feedback->where('find_in_set(\'' . $attr['tags'] . '\',tags)');
        }
        $limit = isset($attr['limit']) ? intval($attr['limit']) : 20;
        $page = isset($attr['page']) ? intval($attr['page']) : 1;
        if (isset($attr['id'])) {
            $rs = $feedback->where('id', $attr['id'])->find();
        } else {
            $rs = $feedback->paginate($limit, false, ['page' => $page])->toArray();
        }
        $rs['tags'] = [];
        if ($page == 1 && !isset($attr['id'])) {
            $rs['tags'] = action('index/api/feedback_tags')->getData()['data'];
        }
        return $return ? json(['code' => 1, 'data' => $rs]) : $rs;
    }

    /**
     * @param string $id 数据编辑
     * @param string $key 栏目编辑
     * @param string $phone 根据电话搜索数据
     * @param string $keyword 根据关键词搜索数据
     * @return \think\response\Json
     */
    public function search($id = '', $key = '', $phone = '', $keyword = '')
    {
        if (!empty($id)) {
            $rs = $this->query(['id' => $id]);
            if (empty($rs)) return json(['code' => 15024, 'msg' => '未找到数据']);
            $rs['column'] = load_column($rs['column_id'], 0, '');
            $data = ['id' => $id, 'column_id' => $rs['column_id'], 'model' => ucfirst($rs['column']['model'])];
        } else if (!empty($key)) {
            $rs = load_column($key, 0, '');
            if (empty($rs)) return json(['code' => 15025, 'msg' => '未找到数据']);
            $data = ['id' => $rs['id']];
        } else {
            if (!empty($phone)) {
                $attr['where'][] = ['phone', '=', $phone];
                $attr['model'] = 'info';
                $data = $this->query($attr);
            }
            if (!empty($keyword)) {
                $attr['where'][] = ['name', 'like', '%' . $keyword . '%'];
                $data = $this->query($attr);
            }
            if (empty($data)) return json(['code' => 15026, 'msg' => '未找到数据']);
            $columns = load_columns(0, 0, '', '', '');
            foreach ($data as $k => $v) $data[$k]['model'] = isset($columns[$v['column_id']]) ? ucfirst($columns[$v['column_id']]['model']) : '';
        }
        return json(['code' => 1, 'data' => $data]);
    }

}
