package com.jiayue.ssi.controller;

import cn.hutool.core.util.NumberUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jiayue.ssi.annotation.InterfaceLimit;
import com.jiayue.ssi.annotation.OperateLog;
import com.jiayue.ssi.annotation.PreventReplay;
import com.jiayue.ssi.backenum.AuditType;
import com.jiayue.ssi.backenum.BusinessType;
import com.jiayue.ssi.constant.CacheConstants;
import com.jiayue.ssi.constant.CustomException;
import com.jiayue.ssi.entity.SysParameter;
import com.jiayue.ssi.service.SysParameterService;
import com.jiayue.ssi.util.ResponseVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import lombok.extern.slf4j.Slf4j;

/**
 * 系统参数接口
 *
 * @author xsl
 * @since 2023/03/20
 */
@RestController
@RequestMapping(value = "/sysParameterController")
@Slf4j
public class SysParameterController {
    @Autowired
    SysParameterService sysParameterService;

    /**
     * 新增系统参数
     *
     * @param sysParameter 参数
     * @return 执行结果
     */
    @PostMapping(value = "/addParameter")
    @OperateLog(title = "参数管理", businessType = BusinessType.INSERT, auditType = AuditType.SYS)
    @PreAuthorize("@ss.hasPermi('system:config:add')")
    @PreventReplay
    public ResponseVO addParameter(@RequestBody SysParameter sysParameter) throws CustomException {
        try {
            if (StringUtils.isEmpty(sysParameter.getSysKey())) {
                return ResponseVO.fail("参数名不能为空!");
            } else if (!"null".equals(sysParameterService.queryByKey(sysParameter.getSysKey(), "null"))) {
                return ResponseVO.fail(sysParameter.getSysKey() + "参数名已存在！");
            } else if (sysParameter.getSysKey().length() > 50) {
                return ResponseVO.fail("参数名长度不能超过50个字符！");
            }

            if (StringUtils.isEmpty(sysParameter.getSysValue())) {
                return ResponseVO.fail("参数值不能为空!");
            } else if (sysParameter.getSysValue().length() > 50) {
                return ResponseVO.fail("参数值长度不能超过50个字符！");
            }

            if (StringUtils.isEmpty(sysParameter.getSysDescribe())) {
                return ResponseVO.fail("参数描述不能为空!");
            } else if (sysParameter.getSysDescribe().length() > 200) {
                return ResponseVO.fail("参数描述长度不能超过200个字符！");
            }
            boolean bo = sysParameterService.save(sysParameter);
            if (bo) {
                if ("useSendMail".equals(sysParameter.getSysKey())) {
                    CacheConstants.use_send_mail = Boolean.parseBoolean(sysParameter.getSysValue());
                }
                return ResponseVO.success("添加参数信息成功");
            } else {
                log.error("添加参数信息失败");
                return ResponseVO.fail("添加参数信息失败");
            }
        } catch (Exception e) {
            throw new CustomException("添加参数信息异常", e);
        }
    }

    /**
     * 更新系统参数
     *
     * @param sysParameter 参数
     * @return 执行结果
     */
    @PostMapping(value = "/updateParameter")
    @OperateLog(title = "参数管理", businessType = BusinessType.UPDATE, auditType = AuditType.SYS)
    @PreAuthorize("@ss.hasPermi('system:config:edit')")
    @PreventReplay
    public ResponseVO updateParameter(@RequestBody SysParameter sysParameter) throws CustomException {
        try {
            SysParameter existSysParameter = sysParameterService.getById(sysParameter.getId());
            if (existSysParameter == null) {
                return ResponseVO.fail("非法访问不能修改!");
            }

            if (StringUtils.isEmpty(sysParameter.getSysKey())) {
                return ResponseVO.fail("参数名不能为空!");
            } else if (sysParameter.getSysKey().length() > 50) {
                return ResponseVO.fail("参数名长度不能超过50个字符！");
            } else if (!existSysParameter.getSysKey().equals(sysParameter.getSysKey())) {
                if (!"null".equals(sysParameterService.queryByKey(sysParameter.getSysKey(), "null"))) {
                    return ResponseVO.fail(sysParameter.getSysKey() + "参数名已存在！");
                }
            }

            if (StringUtils.isEmpty(sysParameter.getSysValue())) {
                return ResponseVO.fail("参数值不能为空!");
            } else if (sysParameter.getSysValue().length() > 50) {
                return ResponseVO.fail("参数值长度不能超过50个字符！");
            }

            if (StringUtils.isEmpty(sysParameter.getSysDescribe())) {
                return ResponseVO.fail("参数描述不能为空!");
            } else if (sysParameter.getSysDescribe().length() > 200) {
                return ResponseVO.fail("参数描述长度不能超过200个字符！");
            }
            boolean bo = sysParameterService.updateById(sysParameter);
            if (bo) {
                if ("useSendMail".equals(sysParameter.getSysKey())) {
                    CacheConstants.use_send_mail = Boolean.parseBoolean(sysParameter.getSysValue());
                }
                return ResponseVO.success("修改参数信息成功");
            } else {
                log.error("修改参数信息失败");
                return ResponseVO.fail("修改参数信息失败");
            }
        } catch (Exception e) {
            throw new CustomException("修改参数信息异常", e);
        }
    }

    /**
     * 删除用户信息
     */
    @PostMapping(value = "/deleteParameter")
    @OperateLog(title = "参数管理", businessType = BusinessType.DELETE, auditType = AuditType.SYS)
    @PreAuthorize("@ss.hasPermi('system:config:remove')")
    @PreventReplay
    public ResponseVO deleteParameter(String id) throws CustomException {
        try {
            if (StringUtils.isEmpty(id)) {
                return ResponseVO.fail("id不能为空!");
            }
            SysParameter sysParameter = sysParameterService.getById(Integer.parseInt(id));
            if ("useSendMail".equals(sysParameter.getSysKey())) {
                CacheConstants.use_send_mail = true;
            }
            boolean bo = sysParameterService.removeById(Integer.parseInt(id));
            if (bo) {
                return ResponseVO.success("删除参数信息成功");
            } else {
                log.error("删除用户信息失败");
                return ResponseVO.fail("删除参数信息失败");
            }
        } catch (Exception e) {
            throw new CustomException("删除参数信息异常", e);
        }
    }

    /**
     * 获取参数分页信息
     *
     * @return 参数信息
     */
    @GetMapping(value = "/getAll")
    @PreAuthorize("@ss.hasPermi('system:config:list')")
    @PreventReplay
    public ResponseVO getAll(String currentPage, String pageSize, String keywords) throws CustomException {
        try {
            Integer cp;
            if (StringUtils.isNotEmpty(currentPage)) {
                if (NumberUtil.isInteger(currentPage)){
                    cp = Integer.parseInt(currentPage);
                }
                else{
                    return ResponseVO.fail("currentPage不是整数！");
                }
            }
            else{
                return ResponseVO.fail("currentPage不能是空！");
            }

            Integer ps;
            if (StringUtils.isNotEmpty(pageSize)) {
                if (NumberUtil.isInteger(pageSize)){
                    ps = Integer.parseInt(pageSize);
                }
                else{
                    return ResponseVO.fail("pageSize不是整数！");
                }
            }
            else{
                return ResponseVO.fail("pageSize不能是空！");
            }
            if (StringUtils.isNotEmpty(keywords)) {
                if (keywords.length() > 200) {
                    return ResponseVO.fail("参数描述长度不能超过200个字符！");
                }
            }
            QueryWrapper<SysParameter> wrapper = new QueryWrapper<>();
            if (StringUtils.isNotEmpty(keywords)) {
                wrapper.like("sys_describe", keywords);
            }
            Page<SysParameter> result = sysParameterService.page(new Page<>(cp, ps), wrapper);
            return ResponseVO.success(result);
        } catch (Exception e) {
            throw new CustomException("获取参数异常", e);
        }
    }

    /**
     * 获取是否邮箱口令参数
     *
     * @return 邮箱口令
     */
    @GetMapping(value = "/getUseSendMail")
    @InterfaceLimit(value = 2, time = 1000)
    public ResponseVO getUseSendMail() throws CustomException {
        try {
            String useSendMail = sysParameterService.queryByKey("useSendMail", "true");
            return ResponseVO.success(useSendMail);
        } catch (Exception e) {
            throw new CustomException("获取邮箱口令参数异常", e);
        }
    }
}
