package com.qmth.themis.admin.api;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qmth.themis.business.constant.SystemConstant;
import com.qmth.themis.business.entity.TSBlackList;
import com.qmth.themis.business.enums.FieldUniqueEnum;
import com.qmth.themis.business.service.TSBlackListService;
import com.qmth.themis.business.service.ThemisCacheService;
import com.qmth.themis.common.exception.BusinessException;
import com.qmth.themis.common.util.Result;
import com.qmth.themis.common.util.ResultUtil;
import io.swagger.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import java.util.Optional;

/**
 * <p>
 * 黑名单表 前端控制器
 * </p>
 *
 * @author wangliang
 * @since 2023-01-31
 */
@Api(tags = "黑名单信息Controller")
@RestController
@RequestMapping(SystemConstant.PREFIX_URL_ADMIN + "/black/list")
@Validated
public class TSBlackListController {
    private final static Logger log = LoggerFactory.getLogger(TSBlackListController.class);

    @Resource
    TSBlackListService tsBlackListService;

    @Resource
    ThemisCacheService themisCacheService;

    @ApiOperation(value = "黑名单查询接口")
    @RequestMapping(value = "/select", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "黑名单信息", response = TSBlackList.class)})
    public Result select(@ApiParam(value = "分页页码", required = true) @RequestParam @Min(SystemConstant.PAGE_NUMBER_MIN) int pageNumber,
                         @ApiParam(value = "分页数", required = true) @RequestParam @Min(SystemConstant.PAGE_SIZE_MIN) @Max(SystemConstant.PAGE_SIZE_MAX) int pageSize) {
        return ResultUtil.ok(tsBlackListService.select(new Page<>(pageNumber, pageSize)));
    }

    @ApiOperation(value = "黑名单保存接口")
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "常规信息", response = Result.class)})
    @Transactional
    public Result save(@Validated @ApiParam(value = "黑名单信息", required = true) @RequestBody TSBlackList tsBlackList, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultUtil.error(bindingResult.getAllErrors().get(0).getDefaultMessage());
        }
        try {
            tsBlackListService.saveOrUpdate(tsBlackList);
            themisCacheService.removeBlackListCache();
        } catch (Exception e) {
            log.error(SystemConstant.LOG_ERROR, e);
            if (e instanceof DuplicateKeyException) {
                String errorColumn = e.getCause().toString();
                String columnStr = errorColumn.substring(errorColumn.lastIndexOf("key") + 3, errorColumn.length()).replaceAll("'", "");
                throw new BusinessException(FieldUniqueEnum.convertToCode(columnStr) + "数据不允许重复插入");
            } else if (e instanceof BusinessException) {
                throw new BusinessException(e.getMessage());
            } else {
                throw new RuntimeException(e);
            }
        }
        return ResultUtil.ok(true);
    }

    @ApiOperation(value = "黑名单删除接口")
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "常规信息", response = Result.class)})
    @Transactional
    public Result delete(@ApiParam(value = "黑名单id", required = true) @RequestParam Long id) {
        tsBlackListService.removeById(id);
        themisCacheService.removeBlackListCache();
        return ResultUtil.ok(true);
    }
}
