<?php
/**
 * +------------------------------------------------------------
 * | 附件 管理
 * +------------------------------------------------------------
 * | @author: zhx (10630650@qq.com)
 * | @create_time: 2018-03-09 22:57:49
 * +------------------------------------------------------------
 * | @copyright: CIM信息聚合系统 (https://cimxx.com)
 * +------------------------------------------------------------
 * | @last_modified_by: zhx
 * | @last_modified_time: 2018-03-09 22:57:49
 * +------------------------------------------------------------
 * | @todo:
 * +------------------------------------------------------------
 */

namespace app\files\controller;

use app\files\model\Files;

class Admin extends Module
{

    protected static $columns = [];

    /**
     * 附件管理
     * @return type
     */
    function index()
    {
        self::$columns = load_columns(0, 0, '', '', '');
        $param = input('param.');
        $data = model('app\files\model\Files');
        if (!empty($param['start_time']) && !empty($param['end_time'])) {
            $start_time = strtotime($param['start_time']);
            $end_time = strtotime($param['end_time']);
            $data = $data->where('create_time', 'between', [$start_time, $end_time]);
        } else {
            if (!empty($param['start_time'])) {
                $data = $data->where('create_time', 'gt', strtotime($param['end_time']));
            }
            if (!empty($param['end_time'])) {
                $data = $data->where('create_time', 'lt', strtotime($param['end_time']));
            }
        }
        $data = $data->order('create_time desc')->paginate(20)->toArray();
        $data['data'] = $this->_init_data($data['data']);
        return json(['code' => 1, 'data' => $data]);
    }

    /**
     * 清除冗余
     * @return type
     */
    function clear_useless()
    {
        $data = Files::where('extend', 'eq', null)->select();
        foreach ($data as $v) {
            if (file_exists($v['file_url'])) {
                @unlink($v['file_url']);
            }
            if (file_exists($v['thumb_url'])) {
                @unlink($v['thumb_url']);
            }
        }
        Files::where('extend', 'eq', NULL)->delete(true);
        action('user/Api/log', ['清理冗余文件']);
        return json(['code' => 1, 'msg' => '清除冗余文件成功']);
    }

    /**
     * 数据概览
     * @return type
     */
    function overview()
    {
        $count = [];
        $count['files'] = Files::count();
        $count['useless_files'] = Files::where('extend', 'eq', null)->count();
        $count['use_files'] = Files::where('extend', 'neq', null)->count();
        $count['week_uploads'] = Files::where('create_time', 'gt', time() - 60 * 60 * 24 * 7)->count();
        $count['month_uploads'] = Files::where('create_time', 'lt', time() - 60 * 60 * 24 * 30)->count();
        $count['files_size'] = $this->size(Files::sum('size'));
        //图表
        $rs = array_column(db('files')->where("`create_time`>UNIX_TIMESTAMP(DATE_SUB(CURDATE(), INTERVAL 7 DAY))")->group("day")->field("count(*) as count,FROM_UNIXTIME(create_time, '%m-%d') as day")->select(), null, 'day');
        for ($i = 7; $i > 0; $i--) {
            $day = date("m-d", strtotime("-" . $i . " day"));
            $data[] = ['day' => $day, '数量' => empty($rs[$day]['count']) ? 0 : $rs[$day]['count']];
        }
        $data = [
            'count' => $count,
            'chart' => [
                'data' => $data,
                'fields' => ['数量']
            ]
        ];
        return json(['code' => 1, 'data' => $data]);
    }

    /**
     * 附件删除
     * @param type $module
     * @param type $id
     * @param type $field
     * @return type
     */
    function delete($path)
    {
        $rs = Files::where('path', '=', urldecode($path))->find();
        if (empty($rs)) return json(['code' => 55001, 'msg' => '未找到附件']);
        if (file_exists($rs['file_url'])) @unlink($rs['file_url']);
        if (file_exists($rs['thumb_url'])) @unlink($rs['thumb_url']);
        Files::where('path', $rs['path'])->delete(true);
        action('user/Api/log', ['删除附件', urldecode($path)]);
        return json(['code' => 1, 'msg' => '文件删除成功']);
    }

    /**
     * 大小转换
     * @param type $value
     * @return type
     */
    private function size($value)
    {
        $size = $value / 1024 / 1024;
        if ($size < 1) {
            $size = $value / 1024;
            return substr($size, 0, strpos($size, '.')) . 'KB';
        }
        return substr($size, 0, strpos($size, '.')) . 'MB';
    }

    /**
     *  初始化数据
     */
    function _init_data($data = [])
    {
        if (!empty($data)) {
            foreach ($data as $k => $v) {
                $data[$k]['path'] = urlencode($v['path']);
                $data[$k]['download'] = action('files/api/_init_thumb', [$v['path'], 1, 1]);
                $size = $v['size'] / 1024 / 1024;
                if ($size < 1) {
                    $size = $v['size'] / 1024;
                    $data[$k]['size'] = substr($size, 0, strpos($size, '.') + 3) . 'KB';
                } else {
                    $data[$k]['size'] = substr($size, 0, strpos($size, '.') + 3) . 'MB';
                }
            }
        }
        return $data;
    }

    /**
     * 附件详情
     * todo
     */
    function view($md5 = '', $refresh = 1)
    {
        if ($md5) {
            if ($refresh) cache($md5, null);
            if (!empty(cache($md5))) return json(['code' => 1, 'data' => cache($md5)]);
            $data = model('app\files\model\Files')->where('md5', '=', $md5)->find();
            if (!empty($data['extend'])) {
                $res = [];
                $data['extend'] = object_to_array($data['extend']);
                foreach ($data['extend'] as $k => $v) {
                    switch ($k) {
                        //数据模块
                        case 'index':
                            $data_id = [];
                            foreach ($v as $kk => $vv) $data_id = array_merge($data_id, $vv);
                            $result = db('data')->where('id', 'in', $data_id)->field('id,column_id,name,create_time')->select();
                            $columns = load_columns(0, 0, '', '', '');
                            foreach ($result as $rk => $rv) {
                                $result[$rk]['url'] = url('index/index/view', ['key' => $columns[$rv['column_id']]['key'] ?: $rv['column_id'], 'id' => $rv['id']], true, true);
                                $result[$rk]['create_time'] = date('m-d H:i', $rv['create_time']);
                            }
                            $res[] = [
                                'data' => $result,
                                'name' => '数据'
                            ];
                            break;
                        //区块模块
                        case 'block':
                            list($table, $field) = explode('|', array_keys($v)[0]);
                            $result = db($table)->where('id', 'in', $v[array_keys($v)[0]])->field('id,name,url,create_time')->select();
                            foreach ($result as $rk => $rv) $result[$rk]['create_time'] = date('m-d H:i', $rv['create_time']);
                            $res[] = [
                                'data' => $result,
                                'name' => '区块'
                            ];
                            break;
                        case 'user':
                            $user_id = [];
                            foreach ($v as $kk => $vv) $user_id = array_merge($user_id, $vv);
                            $result = db('user')->where('id', 'in', $user_id)->field('name,id')->select();
                            foreach ($result as $rk => $rv) $result[$rk]['url'] = url('user/index/index', ['id' => $rv['id']], true, true);
                            $res[] = [
                                'data' => $result,
                                'name' => '用户'
                            ];
                            break;
                    }
                }
                if (!empty($res)) {
                    cache($md5, $res);
                    return json(['code' => 1, 'data' => $res]);
                }
            }
        }
        return json(['code' => 55002, 'msg' => '暂无数据']);
    }

}
