<?php

require_once __DIR__ . '/core.php';

// 判断请求方法
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('lang')->find('l_word, l_name, l_title, l_flag, l_host, l_main, l_on, l_sort')
                ->order('l_sort ASC')->limit(($limit['page'] - 1) * $limit['limit'], $limit['limit'])->all();
            // 处理数据
            $langs = [];
            foreach ($data as $index => $lang) {
                $langs[$index]['seq'] = $index + 1;
                foreach (['word', 'name', 'title', 'host', 'sort'] as $key) {
                    $langs[$index][$key] = $lang['l_'.$key];
                }
                $langs[$index]['flag'] = '<img src="'.loadImage($lang['l_flag'], $hel).'" alt="国旗" height="27">';
                $langs[$index]['main'] = '<input class="layui-form-switch" type="checkbox" value="主目录" lay-skin="primary" '.(1 == $lang['l_main'] ? 'checked' : '').'>';
	            $langs[$index]['on'] = '<input class="layui-form-switch" type="checkbox" value="显示" lay-skin="primary" '.(1 == $lang['l_on'] ? 'checked' : '').'>';
            }
            unset($data);
            // 统计总数
            $count = $con->db->table('lang')->count('l_word != ?', [''], 'l_word');
            // 返回数据
            $data = [
                'msg'   => '',
                'code'  => 0,
                'count' => $count,
                'data'  => $langs
            ];
            $con->json($data);
            break;
        case 'upload':
            // 获取唯一标识
            $unique = $con->request->post('unique');
            // 取出图片名称
            $name = null;
            // 保存图片
            $flag = new \sc\Upload();
            if ($flag->isImage()) {
                $path = $flag->save('file/lang', $name);
                if (!$path) {
                    $con->json(['code' => false, 'err' => '保存失败']);
                } else {
                    $con->json(['code' => true, 'path' => $path]);
                }
            } else {
                $con->json(['code' => false, 'err' => '请上传图片文件']);
            }
            break;
        case 'edit':
            // 获取唯一标识
            $unique = $con->request->post('unique');
            // 取出数据
            $data = $con->request->post(['word', 'name', 'title', 'flag', 'host', 'main', 'sort']);
            // 处理数据
            $lang = verify_data($data);
            unset($data);
            if (!is_array($lang)) {
                $con->json(['code' => false, 'err' => $lang]);
                break;
            }
            // 取出原数据
            $old_lang = $con->db->table('lang')->find('l_word, l_name')->where('l_word = ?', [$unique])->one();
            // 更新主目录
            if (1 == $lang['l_main']) {
                $con->db->table('lang')->update(['l_main' => 0], 'l_main = ?', [1])->row();
            }
            // 更新数据
            $row = $con->db->table('lang')->update($lang, 'l_word = ?', [$unique])->row();
            if (is_numeric($row)) {
                $con->json(['code' => true]);
                // 更新角色表
                $roles = $con->db->table('role')->find('id, r_url, r_name, r_prompt')->where('r_url LIKE \'%?lang='.$old_lang['l_word'].'%\'')->all();
                if ($old_lang['l_word'] != $lang['l_word']) {
                    foreach ($roles as $role) {
                        $con->db->table('role')->update(['r_url' => str_replace('?lang='.$old_lang['l_word'], '?lang='.$lang['l_word'], $role['r_url'])], 'id = ?', [$role['id']])->row();
                    }
                }
                if ($old_lang['l_name'] != $lang['l_name']) {
                    foreach ($roles as $role) {
                        $con->db->table('role')->update([
                            'r_name' => str_replace($old_lang['l_name'], $lang['l_name'], $role['r_name']),
                            'r_prompt' => str_replace($old_lang['l_name'], $lang['l_name'], $role['r_prompt']),
                        ], 'id = ?', [$role['id']])->row();
                    }
                }
                unset($roles);
            } else {
                $con->json(['code' => false, 'err' => '修改失败']);
            }
            break;
        case 'main':
            // 取出唯一标识
            $unique = $con->request->post('unique');
            // 查询开启状态
            $main = $con->db->table('lang')->find('l_main')->where('l_word = ?', [$unique])->one();
            if (!$main) {
                break;
            }
            if (1 == $main['l_main']) {
                $row = $con->db->table('lang')->update(['l_main' => 0], 'l_word = ?', [$unique])->row();
                if (1 == $row) {
                    $con->json(['code' => true]);
                } else {
                    $con->json(['code' => false, 'err' => '关闭失败']);
                }
            } else {
                $row = $con->db->table('lang')->update(['l_main' => 0], 'l_main = ?', [1])->row();
                if (is_numeric($row)) {
                    $row = $con->db->table('lang')->update(['l_main' => 1], 'l_word = ?', [$unique])->row();
                }
                if (1 == $row) {
                    $con->json(['code' => true]);
                } else {
                    $con->json(['code' => false, 'err' => '开启失败']);
                }
            }
            break;
	    case 'on':
		    // 取出唯一标识
		    $unique = $con->request->post('unique');
		    // 查询开启状态
		    $on = $con->db->table('lang')->find('l_on')->where('l_word = ?', [$unique])->one();
		    if (!$on) {
			    break;
		    }
		    if (1 == $on['l_on']) {
			    $row = $con->db->table('lang')->update(['l_on' => 0], 'l_word = ?', [$unique])->row();
			    if (1 == $row) {
				    $con->json(['code' => true, 'stat' => false]);
			    } else {
				    $con->json(['code' => false, 'stat' => true, 'err' => '关闭失败']);
			    }
		    } else {
			    $row = $con->db->table('lang')->update(['l_on' => 1], 'l_word = ?', [$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('lang', ['host' => $hel->url(), 'path' => $hel->path(), 'crumb' => $breadcrumb]);
}

/**
 * 数据验证方法
 *
 * @param array $data
 *
 * @return string|array
 */
function verify_data($data)
{
    if ('' == $data['name']) {
        return '语言名称不能为空';
    }
    $lang['l_name'] = $data['name'];
    if ('' == $data['word']) {
        return '国家缩写不能为空';
    }
    $lang['l_word'] = $data['word'];
    if ((int)$data['sort'] < 0) {
        return '语言排序必须大于0';
    }
    $lang['l_sort'] = $data['sort'];
    if ('' != $data['main']) {
        $lang['l_main'] = 1;
    } else {
        $lang['l_main'] = 0;
    }
    if ('' != $data['on']) {
    	$lang['l_on'] = 1;
    } else {
	    $lang['l_on'] = 0;
    }
    foreach (['host', 'flag', 'title'] as $index) {
        $lang['l_'.$index] = $data[$index];
    }
    return $lang;
}