<?php
declare (strict_types = 1);

namespace app\admin\controller\v1;

use app\admin\model\v1\LanguageModel;
use think\facade\Cookie;
use think\facade\Log;

/**
 * 语言管理控制器
 */
class Language
{
    // 语言列表
    public function list()
    {
        $language = LanguageModel::field([
                'id',
                'country_id',
                'name' => 'language_name',
                'code' => 'language_code',
                'icon' => 'language_icon',
            ])
            ->with('country')
            ->order(['sort' => 'desc', 'id' => 'asc'])
            ->hidden(['country_id', 'country'])
            ->select()
            ->bindAttr('country', ['country_name' => 'name']);
            
        return success('操作成功', $language);
    }

    // 语言切换
    public function cutover()
    {
        $id = request()->param('id');
        $language = LanguageModel::bypk($id)->find();
        if (is_null($language)) {
            return error('语言不存在');
        }

        try {
            Cookie::set('lang', $language->code);
        } catch (\Throwable $th) {
            Log::error($th->getMessage());
            return error('操作失败');
        }

        return success('操作成功');
    }
}
