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.ISysLocaleResourceService;
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.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.ImppRedis;
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 javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

    @Resource(name="redisRes")
    private ImppRedis redisRes;

    @Autowired
    private ISysLocaleResourceService sysLocaleResourceService;

    @Autowired
    private ISystemInitService systemInitService;

    @PostMapping(value = "/insert")
    @ApiOperation(value = "新增语言资源",notes = "新增语言资源")
    public ResultBean insertSysLocaleResource(SysLocaleResource sysLocaleResource){
        try {
            //条件验证
            ValidatorBean.beginValid(sysLocaleResource)
                    .notNull("resourceKey",sysLocaleResource.getResourceKey())
                    .notNull("languageCode",sysLocaleResource.getLanguageCode())
                    .checkNotZero("resourceType",sysLocaleResource.getResourceType())
                    .notNull("resourceValue",sysLocaleResource.getResourceValue());

            //新增初始化
            sysLocaleResource.setIsSystem(CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue());

            sysLocaleResourceService.insertSysLocaleResource(sysLocaleResource);

            // 更新缓存信息
            updateResourceCache(sysLocaleResource,false);
            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 updateSysLocaleResource(SysLocaleResource sysLocaleResource){
        try {
            //条件验证
            ValidatorBean.beginValid(sysLocaleResource)
                    .checkNotZero("id",sysLocaleResource.getId())
                    .notNull("resourceKey",sysLocaleResource.getResourceKey())
                    .notNull("languageCode",sysLocaleResource.getLanguageCode())
                    .checkNotZero("resourceType",sysLocaleResource.getResourceType())
                    .notNull("resourceValue",sysLocaleResource.getResourceValue());

            sysLocaleResourceService.updateSysLocaleResource(sysLocaleResource);

            // 更新缓存信息
            updateResourceCache(sysLocaleResource,false);
            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 deleteSysLocaleResourceById(@PathVariable("id") String idStr){
        try {
            //条件验证
            ValidatorBean.checkNotNull(idStr,"id不能为空");
            SysLocaleResource sysLocaleResource =sysLocaleResourceService.getSysLocaleResourceById(Long.parseLong(idStr));
            if(sysLocaleResource == null){
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.CORE.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                        .setErrorDetail("资源不存在")
                        .build();
            }

            sysLocaleResourceService.deleteSysLocaleResourceById(Long.parseLong(idStr));

            updateResourceCache(sysLocaleResource,false);
            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 listSysLocaleResource(){
        try {
            List sysLocaleLanguageList = sysLocaleResourceService.listSysLocaleResource();
            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 querySysLocaleResourceByPager(SysLocaleResource sysLocaleResource, Pager pager){
        try {
            ListPager sysLocaleLanguageListPager = sysLocaleResourceService.querySysLocaleResourceByPager(sysLocaleResource,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);
        }
    }

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

            sysLocaleResourceService.deleteSysLocaleResourceByIds(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);
        }
    }

    @PutMapping(value = "/batch-insert")
    @ApiOperation(value = "批量添加系统资源")
    public ResultBean insertSysLocaleResourceList(@RequestBody List<SysLocaleResource> sysLocaleResourcesList){
        try {
            if(sysLocaleResourcesList.size() == 0){
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.CORE.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                        .setErrorDetail("请选择需要删除的资源。")
                        .build();
            }

            sysLocaleResourceService.insertSysLocaleResourceList(sysLocaleResourcesList);

            // 重新加载资源
            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);
        }
    }

    /**
     * 更新缓存信息
     * @param sysLocaleResource
     * @param isDelete
     */
    private void updateResourceCache(SysLocaleResource sysLocaleResource,boolean isDelete){
        // 判断是否为删除资源
        if(isDelete){
            Map<Object, Object> langMap = redisRes.getHashMap(CommonConstWords.REDIS_PREFIX_CACHE_LANGUAGE + sysLocaleResource.getLanguageCode());
            if (langMap != null && langMap.size() != 0) {
                langMap.remove(sysLocaleResource.getResourceKey());
                redisRes.putHashMap(CommonConstWords.REDIS_PREFIX_CACHE_LANGUAGE + sysLocaleResource.getLanguageCode(), langMap);
            }

            redisRes.deleteKey(CommonConstWords.REDIS_PREFIX_CACHE_LANGUAGE  + sysLocaleResource.getResourceKey());
        }else {
            Map<Object, Object> langMap = redisRes.getHashMap(CommonConstWords.REDIS_PREFIX_CACHE_LANGUAGE + sysLocaleResource.getLanguageCode());
            if (langMap != null && langMap.size() != 0) {
                langMap.put(sysLocaleResource.getResourceKey(), sysLocaleResource.getResourceValue());
                redisRes.putHashMap(CommonConstWords.REDIS_PREFIX_CACHE_LANGUAGE + sysLocaleResource.getLanguageCode(), langMap);
            }

            HashMap<String, String> resource = new HashMap<String, String>();
            resource.put(sysLocaleResource.getLanguageCode(), sysLocaleResource.getResourceValue());
            redisRes.putHashMap(CommonConstWords.REDIS_PREFIX_CACHE_LANGUAGE + sysLocaleResource.getResourceKey(), resource, 0);
        }
    }
}
