<?php

require_once __DIR__ . '/core.php';

// 取出请求参数
$lang = $con->request->get('lang');

if ($con->request->isAjax()) {
    $action = $con->request->post('action');
    switch ($action) {
        case 'list':
            // 获取分页
            $limit = $con->request->post(['page', 'limit'], FILTER_VALIDATE_INT);
            // 查询数据
            $data = $con->db->table('media')->find('id, m_cate, m_name, m_type, m_cont, m_on, m_sort')
                ->where('m_lang = ?', [$lang])->order('m_sort ASC')
                ->limit(($limit['page'] - 1) * $limit['limit'], $limit['limit'])->all();
            // 处理数据
            $medias = [];
            foreach ($data as $index => $media) {
                $medias[$index]['seq'] = $index + 1;
                $medias[$index]['id'] = $media['id'];
                $medias[$index]['name'] = $media['m_name'];
                $medias[$index]['cate'] = $media['m_cate'];
                switch ($media['m_type']) {
                    case 'F':
                        $medias[$index]['type'] = '文件';
                        $medias[$index]['cont'] = '<a href="'.$hel->to($media['m_cont']).'" title="点击下载文件">'.ltrim(strrchr($media['m_cont'], '/'), '/').'</a>';
                        break;
                    case 'V':
                        $medias[$index]['type'] = '视频';
                        $medias[$index]['cont'] = '<span title="点击查看完整内容" style="overflow: hidden;text-overflow: ellipsis">'.htmlentities($media['m_cont']).'</span>';
                        break;
                    case 'I':
                    default:
                        $medias[$index]['type'] = '图片';
                        $medias[$index]['cont'] = '<img src="'.loadImage($media['m_cont'], $hel).'" alt="图片" height="27" download="1.2">';
                        break;
                }
                $medias[$index]['on'] = '<input class="layui-form-switch" type="checkbox" value="显示" lay-skin="primary" '.(1 == $media['m_on'] ? 'checked' : '').'>';
                $medias[$index]['sort'] = $media['m_sort'];
            }
            unset($data);
            // 统计总数
            $count = $con->db->table('media')->count();
            // 返回数据
            $data = [
                'msg'   => '',
                'code'  => 0,
                'count' => $count,
                'data'  => $medias
            ];
            $con->json($data);
            break;
        case 'edit':
            // 获取唯一标识
            $unique = $con->request->post('unique');
            // 取出数据
            $data = $con->request->post(['cate', 'name', 'type', 'cont', 'on', 'sort']);
            // 处理数据
            $media = verify_data($data);
            unset($data);
            if (!is_array($media)) {
                $con->json(['code' => false, 'err' => $media]);
                break;
            }
            $media['m_time'] = date('Y-m-d H:i:s');
            // 更新数据库
            $row = $con->db->table('media')->update($media, 'id = ?', [$unique])->row();
            if (1 === $row) {
                $con->json(['code' => true]);
            } else {
                $con->json(['code' => false, 'err' => '修改失败']);
            }
            break;
        case 'drop':
            // 获取唯一标识
            $unique = $con->request->post('unique');
            // 删除数据
            $row = $con->db->table('media')->delete('id = ?', [$unique])->row();
            $code = 1 === $row;
            $con->json(['code' => $code]);
            break;
        case 'insert':
            // 取出数据
            $data = $con->request->post(['cate', 'name', 'type', 'cont', 'on', 'sort']);
            // 处理数据
            $media = verify_data($data);
            unset($data);
            if (!is_array($media)) {
                $con->json(['code' => false, 'err' => $media]);
                break;
            }
            $media['m_lang'] = $lang;
            $media['m_time'] = date('Y-m-d H:i:s');
            // 插入数据库
            $row = $con->db->table('media')->insert($media)->row();
            if (1 === $row) {
                $con->json(['code' => true]);
            } else {
                $con->json(['code' => false, 'err' => '添加失败']);
            }
            break;
        case 'delete':
            // 获取唯一标识
            $unique = $con->request->post('unique');
            // 删除数据
            $row = $con->db->table('media')->delete('id IN ('.$unique.')')->row();
            $code = is_numeric($row);
            $con->json(['code' => $code]);
            break;
        case 'cate':
            $categories = $con->db->table('cate')->find('id, pid, c_name')->where('c_lang = ? AND c_on = ?', [$lang, 1])->order('c_sort ASC')->all();
            $categories = $hel->listTree($categories, 3);
            $con->json(['html' => generate_select($categories, 'cate')]);
            break;
        case 'select':
            break;
        case 'upload':
            // 获取唯一标识
            $unique = $con->request->post('unique');
            $custom = $con->request->post('custom');
            if ($custom != null) {
                $name = $custom;
            } else {
                $name = null;
            }
            // 保存上传文件
            $file = new \sc\Upload();
            if ($type == 'image') {
                $path = $file->save('file/image/'.date('YmdH'), $name);

                // 处理图片
                if ($path != false) {
                    $conf = $con->db->table('conf')->find('c_image, c_img_w, c_img_h, c_texts, c_txt_c, c_place, c_s_way')->where('id = ?', ['sem-cms'])->one();
                    if ($conf != false) {
                        $file->handle(PATH.'/'.$path, $conf);
                    }
                }
            } else {
                $path = $file->save('file/file', $name);
            }
            if (!$path) {
                $con->json(['code' => false, 'err' => '保存失败']);
            } else {
                $con->json(['code' => true, 'path' => $path]);
            }
            break;
        case 'on':
            // 获取唯一标识
            $unique = $con->request->post('unique');
            // 查询开启状态
            $on = $con->db->table('media')->find('m_on')->where('id = ?', [$unique])->one();
            if (!$on) {
                break;
            }
            if (1 == $on['m_on']) {
                $row = $con->db->table('media')->update(['m_on' => 0], 'id = ?', [$unique])->row();
                if (1 == $row) {
                    $con->json(['code' => true, 'stat' => false]);
                } else {
                    $con->json(['code' => false, 'stat' => true, 'err' => '关闭失败']);
                }
            } else {
                $row = $con->db->table('media')->update(['m_on' => 1], 'id = ?', [$unique])->row();
                if (1 == $row) {
                    $con->json(['code' => true, 'stat' => true]);
                } else {
                    $con->json(['code' => false, 'stat' => false, 'err' => '开启失败']);
                }
            }
            break;
        default:break;
    }
} else {
    $con->render('media', [
        'crumb' => $breadcrumb,
        'host'  => $hel->url(),
        'path'  => $hel->path(),
        'lang'  => $lang
    ]);
}

function generate_name($level)
{
    $name = '';
    while ($level--) {
        if ($level > 0) {
            $name .= '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
        } else {
            $name .= '&nbsp;&nbsp;&nbsp;&nbsp;|__&nbsp;&nbsp;';
        }
    }
    return $name;
}

function generate_select($categories, $name)
{
    $html = '<select name="'.$name.'" lay-filter="'.$name.'">';
    foreach ($categories as $category) {
        $html .= '<option value="'.$category['id'].'">'.generate_name($category['level']).$category['c_name'].'</option>';
    }
    return $html.'</select>';
}

/**
 * 数据验证方法
 *
 * @param array $data
 *
 * @return string|array
 */
function verify_data($data) {
	if ('' == $data['cate']) {
		// 未选择分类
		return '请选择文件分类';
	}
	$media['m_cate'] = $data['cate'];
    if ('' == $data['name']) {
        // 标题为空
        return '文件标题不能为空';
    }
    $media['m_name'] = $data['name'];
    // 检查文件类型
    switch ($data['type']) {
        case 'F':$media['m_type'] = 'F';break;
        case 'V':$media['m_type'] = 'V';break;
        case 'I':
        default:$media['m_type'] = 'I';break;
    }
    $media['m_cont'] = $data['cont'];
    if (null == $data['on']) {
        $media['m_on'] = 0;
    } else {
        $media['m_on'] = 1;
    }
    if ($data['sort'] < 0) {
        // 排序小于0
        return '文件排序不能小于0';
    }
    $media['m_sort'] = $data['sort'];

    return $media;
}
