package com.fjhx.common.controller.multilingual;

import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fjhx.common.constant.SourceConstant;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.SysConfig;
import com.ruoyi.system.service.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/open/multilingual")
public class MultilingualController {

    @Autowired
    private ISysConfigService sysConfigService;

    @GetMapping("/getJson")
    public String getJson() {
        DynamicDataSourceContextHolder.push(SourceConstant.BASE);
        SysConfig config = sysConfigService.getOne(Wrappers.<SysConfig>lambdaQuery().eq(SysConfig::getConfigKey, "multilingualJson"));
        if (config == null) {
            config = new SysConfig();
            config.setConfigName("多语言json");
            config.setConfigKey("multilingualJson");
            config.setConfigValue("");
            config.setConfigType("Y");
            config.setRemark("多语言json");
            sysConfigService.save(config);
        }
        DynamicDataSourceContextHolder.poll();
        return config.getConfigValue();
    }

    @PostMapping("/setJson")
    public void setJson(@RequestBody SysConfig sysConfig) {
        DynamicDataSourceContextHolder.push(SourceConstant.BASE);
        LoginUser loginUser;
        try {
            loginUser = SecurityUtils.getLoginUser();
        } catch (Exception e) {
            throw new ServiceException("无操作权限");
        }
        if (loginUser == null) {
            throw new ServiceException("无操作权限");
        }

        sysConfigService.update(Wrappers.<SysConfig>lambdaUpdate()
                .eq(SysConfig::getConfigKey, "multilingualJson")
                .set(SysConfig::getConfigValue, sysConfig.getConfigValue())
        );
        DynamicDataSourceContextHolder.poll();
    }

}
