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.ISysConfigService;
import cn.estsh.i3plus.core.apiservice.util.MailUtil;
import cn.estsh.i3plus.platform.common.convert.ConvertBean;
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.ImppEnumUtil;
import cn.estsh.i3plus.pojo.base.enumutil.ResourceEnumUtil;
import cn.estsh.i3plus.pojo.platform.bean.MailConfig;
import cn.estsh.i3plus.pojo.platform.bean.SessionUser;
import cn.estsh.i3plus.pojo.platform.bean.SysConfig;
import cn.estsh.impp.framework.base.controller.CoreBaseController;
import cn.estsh.impp.framework.boot.auth.AuthUtil;
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 javax.mail.AuthenticationFailedException;
import javax.mail.MessagingException;
import java.util.List;

/**
 * @Description : 系统参数管理服务
 * @Reference :
 * @Author : yunhao
 * @Date : 2018-10-25 13:15
 * @Modify :
 **/
@RestController
@Api(description = "系统参数管理服务")
@RequestMapping(PlatformConstWords.BASE_URL +"/sys-config")
public class SysConfigController extends CoreBaseController {
    public static final Logger LOGGER = LoggerFactory.getLogger(SysConfigController.class);

    @Autowired
    private ISysConfigService sysConfigService;

    @Autowired
    private MailUtil mailUtil;

    @Autowired
    private ISystemInitService systemInitService;

    @PostMapping("/insert")
    @ApiOperation(value = "添加系统参数",notes = "添加系统参数")
    public ResultBean insertSysConfig(SysConfig sysConfig) {
        try {
            // 登录用户
            SessionUser user = AuthUtil.getSessionUser();

            // 条件验证
            ValidatorBean.beginValid(sysConfig)
                    .notNull("name",sysConfig.getName())
                    .notNull("configCode",sysConfig.getConfigCode())
                    .notNull("configType",sysConfig.getConfigType())
                    .notNull("configValue",sysConfig.getConfigValue());

            //修改初始化
            ConvertBean.modelInitialize(sysConfig,user);

            sysConfigService.insertSysConfig(sysConfig);
            systemInitService.loadSysConfig();
            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 deleteSysConfig(@PathVariable("id") String idStr) {
        try {
            // 条件验证
            ValidatorBean.checkNotNull(idStr,"id不能为空");
            if(sysConfigService.getSysConfigById(Long.parseLong(idStr)) == null){
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.CORE.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_NOT_EXIT.getCode())
                        .setErrorDetail("字典不存在")
                        .setErrorSolution("请重新输入字典id")
                        .build();
            }

            sysConfigService.deleteSysConfigById(Long.parseLong(idStr));
            systemInitService.loadSysConfig();
            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 updateSysConfig(SysConfig sysConfig){
        try {
            // 登录用户
            SessionUser user = AuthUtil.getSessionUser();

            // 条件验证
            ValidatorBean.beginValid(sysConfig)
                    .notNull("name",sysConfig.getName())
                    .notNull("configCode",sysConfig.getConfigCode())
                    .notNull("configType",sysConfig.getConfigType())
                    .notNull("configValue",sysConfig.getConfigValue());

            //添加初始化
            ConvertBean.modelUpdate(sysConfig,user);

            sysConfigService.updateSysConfig(sysConfig);
            systemInitService.loadSysConfig();
            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 findSysConfigAll(){
        try {
            List<SysConfig> sysConfigList = sysConfigService.ListSysConfig();
            return  ResultBean.success("操作成功")
                                .setResultList(sysConfigList)
                                .setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @GetMapping(value = "/get/{id}")
    @ApiOperation(value = "根据id查询系统参数",notes = "根据id查询系统参数")
    public ResultBean getSysConfigById(@PathVariable("id") String id){
        try {
            ValidatorBean.checkNotNull(id,"id不能为空");

            SysConfig sysConfig = sysConfigService.getSysConfigById(Long.parseLong(id));
            if (sysConfig != null) {
                return ResultBean.success("操作成功")
                        .setResultObject(sysConfig).setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
            }else {
                return ResultBean.fail("数据不存在").setCode(ResourceEnumUtil.MESSAGE.EMPTY.getCode());
            }
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @GetMapping("/query")
    @ApiOperation(value = "系统参数复杂查询，分页，排序",notes = "系统参数复杂查询，分页，排序")
    public ResultBean querySysConfigByPager(SysConfig sysConfig,Pager pager) {
        try {
            ListPager sysConfigListPager = sysConfigService.querySysConfigByPager(sysConfig,pager);
            return  ResultBean.success("操作成功").setListPager(sysConfigListPager).setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @GetMapping(value = "/get-code/{code}")
    @ApiOperation(value = "根据代码获取系统配置")
    public ResultBean getSysConfigByCode(@PathVariable("code") String code){
        try {
            ValidatorBean.checkNotNull(code,"配置项代码不能为空");

            SysConfig sysConfig = sysConfigService.getSysConfigByCode(code);
            if(sysConfig == null){
                return ResultBean.fail("数据不存在").setCode(ResourceEnumUtil.MESSAGE.EMPTY.getCode());
            } else{
                return  ResultBean.success("操作成功").setResultObject(sysConfig).setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
            }
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @GetMapping("/find-mail")
    @ApiOperation(value = "查询邮件配置")
    public ResultBean findMailSysConfig(){
        try {
            List sysConfig = sysConfigService.findMailConfig();
            if(sysConfig == null){
                return ResultBean.fail("数据不存在").setCode(ResourceEnumUtil.MESSAGE.EMPTY.getCode());
            } else{
                return  ResultBean.success("操作成功").setResultList(sysConfig).setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
            }
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @PostMapping("/update-code/{code}/{value}")
    @ApiOperation(value = "根据code修改系统配置")
    public ResultBean updateSysConfigByCode(@PathVariable("code") String code,@PathVariable("value") String value){
        try{
            ValidatorBean.checkNotNull(code,"配置项代码不能为空");
            ValidatorBean.checkNotNull(value,"值不能为空");

            sysConfigService.updateSysConfigByCode(code,value);
            systemInitService.loadSysConfig();
            return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @GetMapping("/send-test-mail")
    @ApiOperation(value = "邮件测试")
    public ResultBean sendTestMail(MailConfig mailConfig){
        try {
            ValidatorBean.beginValid(mailConfig)
                    .notNull("mailHost",mailConfig.getMailHost())
                    .notNull("mailPort",mailConfig.getMailPort())
                    .notNull("mailUser",mailConfig.getMailUser())
                    .notNull("mailPassword",mailConfig.getMailPassword())
                    .notNull("mailNick",mailConfig.getMailNick())
                    .notNull("testTo",mailConfig.getTestTo());

            mailUtil.init(mailConfig);
            mailUtil.setSubject("测试邮件");
            mailUtil.setContentType(ImppEnumUtil.MESSAGE_TYPE_CONTENT.HTML.getDescription());
            mailUtil.setBody("测试邮件");
            mailUtil.setTo(mailConfig.getTestTo());
            mailUtil.send();
            return ResultBean.success("测试邮件已发送").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        }catch(MessagingException messageExcep){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(messageExcep);
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @GetMapping("/find-group/{group}")
    @ApiOperation(value = "根据参数组查询系统参数")
    public ResultBean findSysConfigByGroup(@PathVariable("group") Integer group){
        try {
            ValidatorBean.checkNotNull(group,"参数组不能为空");
            List<SysConfig> sysConfigList = sysConfigService.findSysConfigByGroup(group);
            return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode()).setResultList(sysConfigList);
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }
}
