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

import cn.estsh.i3plus.core.api.iservice.base.ISystemInitService;
import cn.estsh.i3plus.core.api.iservice.busi.ISysLocaleLanguageService;
import cn.estsh.i3plus.platform.common.tool.StringTool;
import cn.estsh.i3plus.platform.common.util.CommonConstWords;
import cn.estsh.i3plus.platform.common.util.PlatformConstWords;
import cn.estsh.i3plus.pojo.base.bean.ListPager;
import cn.estsh.i3plus.pojo.base.common.Pager;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.i3plus.pojo.base.enumutil.ResourceEnumUtil;
import cn.estsh.i3plus.pojo.platform.bean.SysLocaleLanguage;
import cn.estsh.i3plus.pojo.platform.bean.SysLocaleResource;
import cn.estsh.impp.framework.base.controller.CoreBaseController;
import cn.estsh.impp.framework.boot.exception.ImppBusiException;
import cn.estsh.impp.framework.boot.exception.ImppExceptionBuilder;
import cn.estsh.impp.framework.boot.exception.ImppExceptionEnum;
import cn.estsh.impp.framework.boot.util.ResultBean;
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.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;

/**
 * @Description : 系统语言服务
 * @Reference :
 * @Author : yunhao
 * @CreateDate : 2018-11-12 15:15
 * @Modify:
 **/
@RestController
@Api(description = "系统语言服务")
@RequestMapping(PlatformConstWords.BASE_URL + "/sys-locale-language")
public class SysLocaleLanguageController extends CoreBaseController {
    public static final Logger LOGGER = LoggerFactory.getLogger(SysFileController.class);

    @Autowired
    private ISysLocaleLanguageService sysLocaleLanguageService;

    @Autowired
    private ISystemInitService systemInitService;

    @PostMapping(value = "/insert")
    @ApiOperation(value = "添加系统语言",notes = "添加系统语言")
    public ResultBean insertSysLocaleLanguage(SysLocaleLanguage sysLocaleLanguage){
        try {
            //条件验证
            ValidatorBean.beginValid(sysLocaleLanguage)
                    .notNull("languageName", sysLocaleLanguage.getLanguageName())
                    .notNull("languageCode", sysLocaleLanguage.getLanguageCode());

            //新增初始化
            sysLocaleLanguage.setIsDefault(CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue());
            sysLocaleLanguage.setLanguageStatus(CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue());

            sysLocaleLanguageService.insertSysLocaleLanguage(sysLocaleLanguage);

            redisCore.putHashMap(CommonConstWords.REDIS_PREFIX_CACHE_LANGUAGE + sysLocaleLanguage.getLanguageCode(),new HashMap<>());
            return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @PutMapping(value = "/update")
    @ApiOperation(value = "修改系统语言",notes = "修改系统语言")
    public ResultBean updateSysLocaleLanguage(SysLocaleLanguage sysLocaleLanguage){
        try {
            //条件验证
            ValidatorBean.beginValid(sysLocaleLanguage)
                    .checkNotZero("id",sysLocaleLanguage.getId())
                    .notNull("languageName", sysLocaleLanguage.getLanguageName())
                    .notNull("languageCode", sysLocaleLanguage.getLanguageCode());

            sysLocaleLanguageService.updateSysLocaleLanguage(sysLocaleLanguage);

            // 重新加载资源
            systemInitService.loadSysLocaleLanguage();
            return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @DeleteMapping(value = "/delete/{id}")
    @ApiOperation(value = "根据id删除系统语言",notes = "根据id删除系统语言")
    public ResultBean deleteSysLocaleLanguageById(@PathVariable("id") String idStr){
        try {
            //条件验证
            ValidatorBean.checkNotNull(idStr,"id不能为空");
            SysLocaleLanguage sysLocaleLanguage =sysLocaleLanguageService.getSysLocaleLanguageById(Long.parseLong(idStr));
            if(sysLocaleLanguage == null){
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.CORE.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                        .setErrorDetail("语言不存在")
                        .build();
            }

            sysLocaleLanguageService.deleteSysLocaleLanguageById(Long.parseLong(idStr));

            // 移出缓存
            redisCore.deleteKey(CommonConstWords.REDIS_PREFIX_CACHE_LANGUAGE + sysLocaleLanguage.getLanguageCode());
            return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @GetMapping(value = "/list")
    @ApiOperation(value = "查询全部系统语言",notes = "查询全部系统语言")
    public ResultBean listSysLocaleLanguage(){
        try {
            List sysLocaleLanguageList = sysLocaleLanguageService.listSysLocaleLanguage();
            return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode()).setResultList(sysLocaleLanguageList);
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @GetMapping(value = "/query")
    @ApiOperation(value = "系统语言复杂查询，分页，排序",notes = "系统语言复杂查询，分页，排序")
    public ResultBean querySysLocaleLanguageByPager(SysLocaleLanguage sysLocaleLanguage, Pager pager){
        try {
            ListPager sysLocaleLanguageListPager = sysLocaleLanguageService.querySysLocaleLanguageByPager(sysLocaleLanguage,pager);
            return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode()).setListPager(sysLocaleLanguageListPager);
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @PutMapping("/default/{id}")
    @ApiOperation(value = "设置默认语言",notes = "设置默认语言")
    public ResultBean updateSysLocaleLanguageDefaultById(@PathVariable("id") String idStr){
        try {
            //条件验证
            ValidatorBean.checkNotNull(idStr,"id不能为空");

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

    @DeleteMapping("/batch-delete")
    @ApiOperation(value = "根据id批量删除")
    public ResultBean deleteSysLocaleLanguageByIds(String[] idsStr){
        try {
            if(idsStr == null || idsStr.length == 0){
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.CORE.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                        .setErrorDetail("请选择需要删除的资源。")
                        .build();
            }

            sysLocaleLanguageService.deleteSysLocaleLanguageByIds(StringTool.getArrayLong(idsStr));

            // 重新加载语言资源
            systemInitService.loadSysLocaleLanguage();
            return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @PostMapping(value = "/status/{id}/{status}")
    @ApiOperation(value = "根据id修改语言状态")
    public ResultBean updateSysLocaleLanguageStatusById(@PathVariable("id") String idStr,@PathVariable("status") Integer status){
        try {
            //条件校验
            ValidatorBean.checkNotNull(idStr,"id不能为空");
            ValidatorBean.checkIsNumber(status,"状态不能为空");

            sysLocaleLanguageService.updateSysLocaleLanguageStatusById(Long.parseLong(idStr),status);
            return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @PostMapping(value = "/batch-status")
    @ApiOperation(value = "根据批量修改语言状态")
    public ResultBean updateSysLocaleLanguageStatusByIds(String[] idsStr,Integer status){
        try {
            if(idsStr == null || idsStr.length == 0){
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.CORE.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                        .setErrorDetail("请选择需要删除的资源。")
                        .build();
            }
            ValidatorBean.checkNotZero(status,"状态不能为0");

            sysLocaleLanguageService.updateSysLocaleLanguageStatusByIds(StringTool.getArrayLong(idsStr),status);
            return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }
}
