package cn.estsh.i3plus.core.apiservice.controller;

import cn.estsh.i3plus.core.api.iservice.busi.ISysUserInfoService;
import cn.estsh.i3plus.core.api.iservice.busi.ISysUserService;
import cn.estsh.i3plus.core.api.iservice.busi.ISystemResourceService;
import cn.estsh.i3plus.platform.common.convert.ConvertBean;
import cn.estsh.i3plus.platform.common.tool.StringTool;
import cn.estsh.i3plus.platform.common.util.PlatformConstWords;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.i3plus.pojo.base.enumutil.ResourceEnumUtil;
import cn.estsh.i3plus.pojo.base.bean.ListPager;
import cn.estsh.i3plus.pojo.platform.bean.*;
import cn.estsh.impp.framework.base.controller.CoreBaseController;
import cn.estsh.impp.framework.boot.auth.AuthUtil;
import cn.estsh.impp.framework.boot.exception.ImppExceptionBuilder;
import cn.estsh.impp.framework.boot.util.ResultBean;
import cn.estsh.i3plus.pojo.base.common.Pager;
import cn.estsh.impp.framework.boot.exception.ImppBusiException;
import cn.estsh.impp.framework.boot.exception.ImppExceptionEnum;
import cn.estsh.impp.framework.boot.util.ImppRedis;
import cn.estsh.impp.framework.boot.util.ValidatorBean;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Locale;

/**
 * @Description : 系统资源服务demo
 * @Reference :
 * @Author : alwaysfrin
 * @CreateDate : 2018-09-26 10:34
 * @Modify:
 **/
@RestController
@Api(description="系统服务demo")
@RequestMapping(PlatformConstWords.BASE_URL + "/demo-system-service")
public class DemoResourceController extends CoreBaseController {
    private static final Logger LOGGER = LoggerFactory.getLogger(DemoResourceController.class);

    /**
     * 缓存
     */
    @Resource(name="redisCore")
    private ImppRedis redisCore;

    /**
     * rabbitMQ队列
     */
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private ISystemResourceService systemResourceService;

    @PutMapping(value="/language/insert")
    @ApiOperation(value="添加语言",notes = "添加系统语言，可用于国际化")
    public ResultBean insertLanguage(SysLocaleLanguage lang) {
        try {
            //登陆用户
            SessionUser user = AuthUtil.getSessionUser();

            //条件验证
            ValidatorBean.beginValid(lang)
                    .notNull("languageName",lang.getLanguageName())
                    .notNull("languageCode",lang.getLanguageCode());

            //新增初始化
            ConvertBean.modelInitialize(lang,user);

            systemResourceService.insertSysLocaleLanguage(lang);
            return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep).build();
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    /**
     * 修改系统语言，可用于国际化
     * @param lang 国际化语言
     * @return
     */
    @PutMapping(value="/language/update")
    @ApiOperation(value="修改语言",notes = "修改系统语言，可用于国际化")
    public ResultBean updateLanguage(SysLocaleLanguage lang) {
        try {
            //登陆用户
            SessionUser user = AuthUtil.getSessionUser();

            //条件验证
            ValidatorBean.beginValid(lang)
                    .notNull("languageName",lang.getLanguageName())
                    .notNull("languageCode",lang.getLanguageCode());

            //修改条件
            ConvertBean.modelUpdate(lang,user);
            systemResourceService.updateSysLocaleLanguage(lang);
            return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep).build();
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @PutMapping(value="/language/query")
    @ApiOperation(value="查询语言",notes = "添加系统语言，可用于国际化")
    public ResultBean queryLanguage(SysLocaleLanguage lang,Pager pager) {
        try {
            ListPager listPager = systemResourceService.listSysLocaleLanguageByPager(lang,pager);
            return ResultBean.success("操作成功").setListPager(listPager).setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @PutMapping(value="/resource/insert")
    @ApiOperation(value="添加资源",notes = "添加系统语言，可用于国际化")
    public ResultBean insertResource(SysLocaleResource res) {
        try {
            //登陆用户
            SessionUser user = AuthUtil.getSessionUser();

            //条件验证
            ValidatorBean.beginValid(res)
                    .notNull("resourceKey",res.getResourceKey())
                    .notNull("resourceValue",res.getResourceValue());

            //新增初始化
            ConvertBean.modelInitialize(res,user);
            systemResourceService.insertSysLocaleResource(res);
            return ResultBean.success("操作成功").setResultObject(res).setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @PutMapping(value="/resource/query")
    @ApiOperation(value="查询资源",notes = "分页查询系统资源")
    public ResultBean queryResource(SysLocaleResource res,Pager pager) {
        try{
            ListPager listPager = systemResourceService.listSysLocaleResourceByPager(res,pager);
            return ResultBean.success("操作成功").setListPager(listPager).setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @GetMapping(value="/locale-resource/get")
    @ApiOperation(value="语言资源匹配",notes="资源配置文件及国际化")
    public ResultBean getLocaleResource(int resourceType,String langCode,String resKey) {
        try {
            ValidatorBean.checkNotZero(resourceType,"请选择资源类型。");
            ValidatorBean.checkNotNull(langCode,"请输入语言编码");
            ValidatorBean.checkNotNull(resKey,"请输入资源编码");
            Locale locale = LocaleContextHolder.getLocale();
            LOGGER.info("当前语言：" + locale.getLanguage() + "，国家：" + locale.getCountry());

            SysLocaleResource res = systemResourceService.getSysLocaleResourceByLanguage(resourceType, langCode, resKey);
            LOGGER.info("获取的资源：" + res);

            return ResultBean.success("操作成功")
                                .setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode())
                                .setResultObject(res);
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @DeleteMapping  (value="/locale-resource/delete")
    @ApiOperation(value="删除资源",notes="批量删除资源")
    public ResultBean deleteLocaleResource(String[] resourceIds) {
        try {
            if(resourceIds.length == 0){
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.IMPP.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                        .setErrorDetail("请选择需要删除的资源。")
                        .build();
            }
            systemResourceService.deleteSysLocaleResourceByIds(StringTool.getArrayLong(resourceIds));

            return ResultBean.success().setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }


    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysUserInfoService userInfoServicer;


    @GetMapping(value="/dup-id1")
    @ApiOperation(value="测试重复ID1",notes="测试重复ID1")
    public ResultBean testDuplicatedIdOne(long key) {
        try {
            LOGGER.info("获取：{}",key);

            SysUser user = userService.getSysUserById(key);
            System.out.println("1==="+user.toString());

            return ResultBean.success("操作成功");
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }



    @GetMapping(value="/dup-id2")
    @ApiOperation(value="测试重复ID2",notes="测试重复ID2")
    public ResultBean testDuplicatedIdTwo(long key) {
        try {
            LOGGER.info("获取：{}",key);

            SysUserInfo userInfo = userInfoServicer.getSysUserInfoById(key);
            System.out.println("2==="+userInfo.toString());

            return ResultBean.success("操作成功");
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @GetMapping(value="/dup-id")
    @ApiOperation(value="测试重复ID",notes="测试重复ID")
    public ResultBean testDuplicatedId(long key) {
        try {
            LOGGER.info("获取：{}",key);
//            SysUser u1 = new SysUser();
//            u1.setId(key);
//            SysUserInfo u2 = new SysUserInfo();
//            u2.setId(key);
//            System.out.println(u1.equals(u2));
//            System.out.println("1====" + u1.hashCode());
//            System.out.println("2====" + u2.hashCode());

//            SysUser user = userService.getSysUserById(key);
//            System.out.println("1==="+user);
//            SysUserInfo userInfo = userInfoServicer.getSysUserInfoById(key);
//            System.out.println("2==="+userInfo);

            return ResultBean.success("操作成功");
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }
}
