<?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);
            // 查询数据
            $cate = $con->request->get('cate', FILTER_VALIDATE_INT);
            $keyword = $con->request->get('keyword');
            if (null != $cate && null != $keyword) {
                $data = $con->db->table('info')->find('id, i_cate, i_name, i_time, i_on, i_sort')
                    ->where('i_lang = ? AND i_cate = ? AND i_name LIKE \'%'.$keyword.'%\'', [$lang, $cate])->order('i_sort ASC')
                    ->limit(($limit['page'] - 1) * $limit['limit'], $limit['limit'])->all();
                $count = $con->db->table('info')->count('i_lang = ? AND i_cate = ? AND i_name LIKE \'%'.$keyword.'%\'', [$lang, $cate]);
            } else if (null != $cate) {
                $data = $con->db->table('info')->find('id, i_cate, i_name, i_time, i_on, i_sort')
                    ->where('i_lang = ? AND i_cate = ?', [$lang, $cate])->order('i_sort ASC')
                    ->limit(($limit['page'] - 1) * $limit['limit'], $limit['limit'])->all();
                $count = $con->db->table('info')->count('i_lang = ? AND i_cate = ?', [$lang, $cate]);
            } else if (null != $keyword) {
                $data = $con->db->table('info')->find('id, i_cate, i_name, i_time, i_on, i_sort')
                    ->where('i_lang = ? AND i_name LIKE \'%'.$keyword.'%\'', [$lang])->order('i_sort ASC')
                    ->limit(($limit['page'] - 1) * $limit['limit'], $limit['limit'])->all();
                $count = $con->db->table('info')->count('i_lang = ? AND i_name LIKE \'%'.$keyword.'%\'', [$lang]);
            } else {
                $data = $con->db->table('info')->find('id, i_cate, i_name, i_time, i_on, i_sort')
                    ->where('i_lang = ?', [$lang])->order('i_sort ASC')
                    ->limit(($limit['page'] - 1) * $limit['limit'], $limit['limit'])->all();
                $count = $con->db->table('info')->count('i_lang = ?', [$lang]);
            }
            // 处理数据
            $infos = [];
            foreach ($data as $index => $info) {
                $infos[$index]['seq'] = $index + 1;
                $infos[$index]['id'] = $info['id'];
                foreach (['name', 'time', 'sort'] as $key) {
                    $infos[$index][$key] = $info['i_'.$key];
                }
                $infos[$index]['on'] = '<input class="layui-form-switch" type="checkbox" value="显示" lay-skin="primary" '.(1 == $info['i_on'] ? 'checked' : '').'>';
            }
            unset($data);
            // 返回数据
            $data = [
                'msg'   => '',
                'code'  => 0,
                'count' => $count,
                'data'  => $infos
            ];
            $con->json($data);
            break;
        case 'drop':
            // 获取唯一标识
            $unique = $con->request->post('unique');
            // 删除数据
            $row = $con->db->table('info')->delete('id = ?', [$unique])->row();
            $code = 1 === $row;
            $con->json(['code' => $code]);
            break;
        case 'edit':
            // 获取唯一标识
            $unique = $con->request->post('unique');
            // 取出数据
            $data = $con->request->post(['cate', 'name', 'url', 'kwd', 'des', 'img', 'details', 'auth', 'on', 'sort']);
            // 处理数据
            $info = verify_data($data);
            unset($data);
            if (!is_array($info)) {
                $con->json(['code' => false, 'err' => $info]);
                break;
            }
            // 修改数据
            $row = $con->db->table('info')->update($info, 'id = ?', [$unique])->row();
            $code = 1 === $row;
            $url = $hel->path() . '/info.php?lang='.$lang;
            if ($code) {
                $con->json(['code' => $code, 'path' => $url]);
            } else {
                $err = 23000 === $row ? '自定义URL重复，请尝试其他URL' : '修改失败';
                $con->json(['code' => $code, 'err' => $err]);
            }
            break;
        case 'insert':
            // 取出数据
            $data = $con->request->post(['cate', 'name', 'url', 'kwd', 'des', 'img', 'details', 'auth', 'on', 'sort']);
            // 处理数据
            $info = verify_data($data);
            unset($data);
            if (!is_array($info)) {
                $con->json(['code' => false, 'err' => $info]);
                break;
            }
            $info['i_lang'] = $lang;
            // 修改数据
            $row = $con->db->table('info')->insert($info)->row();
            $code = 1 === $row;
            $url = $hel->path() . '/info.php?lang='.$lang;
            if ($code) {
                $con->json(['code' => $code, 'path' => $url]);
            } else {
                $err = 23000 === $row ? '自定义URL重复，请尝试其他URL' : '添加失败';
                $con->json(['code' => $code, 'err' => $err]);
            }
            break;
        case 'delete':
            // 获取唯一标识
            $unique = $con->request->post('unique');
            // 删除数据
            $row = $con->db->table('info')->delete('id IN ('.$unique.')')->row();
            $code = is_numeric($row);
            $con->json(['code' => $code]);
            break;
        case 'upload':
            // 取出文件名
            $unique = $con->request->post('unique');
            $name = null;
            $image = new \sc\Upload();
            if ($image->isImage()) {
                $path = $image->save('file/information', $name);
                if (!$path) {
                    $con->json(['code' => false, 'err' => '保存失败']);
                } else {
                    $con->json(['code' => true, 'path' => $path]);
                }
            } else {
                $con->json(['code' => false, 'err' => '请上传图片文件']);
            }
            break;
        case 'on':
            // 取出唯一标识
            $unique = $con->request->post('unique');
            // 查询开启状态
            $on = $con->db->table('info')->find('i_on')->where('id = ?', [$unique])->one();
            if (!$on) {
                break;
            }
            if (1 == $on['i_on']) {
                $row = $con->db->table('info')->update(['i_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('info')->update(['i_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 {
    $action = $con->request->get('action');
    // 获取分类
    $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, 2);
    $extends  = $con->db->table('cate')->find('id, pid, c_name')->where('id IN (4,5,6)')->all();
    foreach ($extends as $index => $extend) {
        $extends[$index]['level'] = 0;
    }
    $categories = array_merge($extends, $categories);
    if ('edit' == $action) {
        // 获取唯一标识
        $unique = $con->request->get('unique');
        // 查询数据
        $data = $con->db->table('info')->find('*')->where('id = ?', [$unique])->one();
        $info = [];
        $info['id'] = $data['id'];
        $info['cate'] = $data['i_cate'];
        $info['img'] = loadImage($data['i_img'], $hel, false);
        foreach (['name', 'url', 'kwd', 'des', 'details', 'auth', 'time', 'on', 'sort'] as $index) {
            $info[$index] = $data['i_'.$index];
        }
        unset($data);
        $con->render('info-edit', [
            'hel'    => $hel,
            'crumb'  => $breadcrumb,
            'select' => generate_select($categories, 'cate', $info['cate']),
            'info'   => $info,
            'host'   => $hel->url(),
            'path'   => $hel->path(),
            'lang'   => $lang
        ]);
    } else if ('insert' == $action) {
        $data = false;
        $con->render('info-edit', [
            'hel'    => $hel,
            'crumb'  => $breadcrumb,
            'select' => generate_select($categories, 'cate', 0),
            'info'   => $data,
            'host'   => $hel->url(),
            'path'   => $hel->path(),
            'lang'   => $lang
        ]);
    } else {
        $con->render('info', [
            'crumb'  => $breadcrumb,
            'select' => generate_select($categories, 'cate', 0),
            '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, $cate)
{
    $html = '<select name="'.$name.'" lay-filter="'.$name.'">';
    foreach ($categories as $category) {
        $html .= '<option value="'.$category['id'].'" '.($category['id'] == $cate ? 'selected' : '').'>'.generate_name($category['level']).$category['c_name'].'</option>';
    }
    return $html.'</select>';
}

/**
 * 数据验证方法
 *
 * @param array $data
 *
 * @return string|array
 */
function verify_data($data)
{
    if ('' == $data['name']) {
        // 标题为空
        return '信息标题不能为空';
    }
    $info['i_name'] = $data['name'];
    if ('' != $data['url']) {
        // URL不为空
        if (is_numeric($data['url'])) {
            return 'URL不能为纯数字';
        }
        $info['i_url'] = $data['url'];
    }
    foreach (['cate', 'kwd', 'des', 'img', 'details', 'auth'] as $index) {
        $info['i_'.$index] = $data[$index];
    }
    if ((int)$data['sort'] < 0) {
        // 排序小于0
        return '信息排序必须大于0';
    }
    $info['i_sort'] = $data['sort'];
    if (null != $data['on']) {
        $info['i_on'] = 1;
    } else {
        $info['i_on'] = 0;
    }
    $info['i_time'] = date('Y-m-d H:i:s');

    return $info;
}