package com.wms.controller;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wms.annotation.MyLog;
import com.wms.constants.enums.ResponseCode;
import com.wms.entity.app.ResponseEntity;
import com.wms.entity.app.dto.PageDto;
import com.wms.entity.app.request.ConfigQuery;
import com.wms.entity.app.vo.ConfigVo;
import com.wms.entity.table.Config;
import com.wms.service.ConfigService;
import com.wms.system_service.ISystemService;
import com.wms.utils.HttpUtils;
import com.wms.utils.StringUtils;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import static com.wms.utils.StringUtils.convertJsonString;

/**
 * WMS系统配置控制类
 *
 * @author 梁州
 * &#064;date  2023/3/23
 */
@Controller
@CrossOrigin
@RequestMapping(value = "/wms/config")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class ConfigController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    /**
     * 系统配置服务
     */
    private final ConfigService configService;
    /**
     * 请求头部信息
     */
    private final HttpServletRequest servletRequest;
    /**
     * 系统服务
     */
    private final ISystemService systemService;

    /**
     * 查找所有配置
     *
     * @return 配置
     */
    @GetMapping("/getConfigs")
    @ResponseBody
    public List<Config> getConfigs() {
        logger.info("查询系统配置，查询ip：{}", HttpUtils.getIpAddr(servletRequest));
        return configService.selectConfigs("");
    }

    /**
     * 查询系统配置
     *
     * @param configQuery 配置
     * @return 结果
     */
    @PostMapping("/getConfigsByPage")
    @ResponseBody
    @Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED)
    @MyLog(logTitle = "查询系统配置", logMethod = "getConfigsByPage")
    public String getConfigsByPage(@RequestBody ConfigQuery configQuery) {
        logger.info("查询系统配置，{}，请求ip：{}", convertJsonString(configQuery), HttpUtils.getIpAddr(servletRequest));
        // 创建响应信息
        ResponseEntity response = new ResponseEntity();
        try {
            Page<Config> page = configQuery.toMpPage();
            Page<Config> configPage = configService.page(page, new LambdaQueryWrapper<Config>()
                    .like(StringUtils.isNotEmpty(configQuery.getConfigName()), Config::getConfigName, configQuery.getConfigName())
                    .like(StringUtils.isNotEmpty(configQuery.getConfigKey()), Config::getConfigKey, configQuery.getConfigKey())
                    .eq(StringUtils.isNotEmpty(configQuery.getConfigType()), Config::getConfigType, configQuery.getConfigType()));

            PageDto<ConfigVo> pageDto = PageDto.of(configPage, config -> BeanUtil.copyProperties(config, ConfigVo.class));
            response.setCode(ResponseCode.OK.getCode());
            response.setMessage("查询系统配置成功。");
            response.setReturnData(pageDto);
            return convertJsonString(response);
        } catch (Exception e) {
            // 回滚事务
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            logger.error("查询系统配置发生异常。");
            response.setCode(ResponseCode.ERROR.getCode());
            response.setMessage("查询系统配置发生异常。");
            return convertJsonString(response);
        }
    }

    /**
     * 更新系统配置
     *
     * @param configQuery 配置
     * @return 结果
     */
    @PostMapping("/updateConfig")
    @ResponseBody
    @Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED)
    @MyLog(logTitle = "更新配置", logMethod = "updateConfig")
    public String updateConfig(@RequestBody ConfigQuery configQuery) {
        logger.info("更新系统配置，{}，请求ip：{}", convertJsonString(configQuery), HttpUtils.getIpAddr(servletRequest));
        // 创建响应信息
        ResponseEntity rsp = new ResponseEntity();
        try {
            if (configQuery == null || configQuery.getConfigId() == null) {
                logger.info("更新系统配置时配置id为必须项");
                // 返回其他异常
                rsp.setCode(ResponseCode.ERROR.getCode());
                rsp.setMessage("更新系统配置时配置id为必须项");
                return JSON.toJSONString(rsp);
            }
            // 更新配置
            configService.update(new LambdaUpdateWrapper<Config>()
                    .set(StringUtils.isNotEmpty(configQuery.getConfigKey()), Config::getConfigKey, configQuery.getConfigKey())
                    .set(StringUtils.isNotEmpty(configQuery.getConfigType()), Config::getConfigType, configQuery.getConfigType())
                    .set(StringUtils.isNotEmpty(configQuery.getConfigValue()), Config::getConfigValue, configQuery.getConfigValue())
                    .set(StringUtils.isNotEmpty(configQuery.getConfigName()), Config::getConfigName, configQuery.getConfigName())
                    .eq(Config::getConfigId, configQuery.getConfigId()));
            // 更新Map
            try {
                systemService.reloadConfig();
                // 返回成功
                rsp.setCode(ResponseCode.OK.getCode());
                rsp.setMessage("更新系统配置成功！");
            } catch (Exception e) {
                // 返回成功
                rsp.setCode(ResponseCode.OK.getCode());
                rsp.setMessage("重载系统配置错误，请手动重载配置。");
            }
            // 返回成功
            rsp.setCode(ResponseCode.OK.getCode());
            rsp.setMessage("更新系统配置成功！");
            return JSON.toJSONString(rsp);
        } catch (Exception e) {
            // 回滚事务
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            logger.info("更新系统配置错误：{}", e.getMessage());
            // 返回其他异常
            rsp.setCode(ResponseCode.ERROR.getCode());
            rsp.setMessage("更新系统配置错误。");
            return JSON.toJSONString(rsp);
        }
    }
}
