package org.jeecg.modules.adweb.enquiry.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.collections4.CollectionUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.modules.adweb.common.util.AdwebRedisUtil;
import org.jeecg.modules.adweb.enquiry.entity.AdwebPublicBlackIp;
import org.jeecg.modules.adweb.enquiry.service.IAdwebPublicBlackIpService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: IP黑名单
 * @Author: jeecg-boot
 * @Date: 2023-02-20
 * @Version: V1.0
 */
@Tag(name = "IP黑名单")
@RestController
@RequestMapping("/blackip/adwebBlackIp")
@Slf4j
public class AdwebPublicBlackIpController
        extends JeecgController<AdwebPublicBlackIp, IAdwebPublicBlackIpService> {

    @Resource private IAdwebPublicBlackIpService adwebBlackIpService;

    @Resource private AdwebRedisUtil adwebRedisUtil;

    private static final String IpTenMinKey = "JUDGE_WASTE_ENQUIRY_IP_BY_10_MIN::";
    private static final String IpOneDayKey = "JUDGE_WASTE_ENQUIRY_IP_BY_ONE_DAY::";
    private static final String BlackIpKey = "BLACK_IP_LIST";
    private static final String NotBlackIpWasteEnquiryKey = "NOT_BLACK_IP_WASTE_ENQUIRY_MAP::";
    private static final String WhiteIpListKey = "WHITE_IP_LIST";

    /**
     * 分页列表查询
     *
     * @param adwebBlackIp
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "IP黑名单-分页列表查询")
    @Operation(summary = "IP黑名单-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(
            AdwebPublicBlackIp adwebBlackIp,
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
            HttpServletRequest req) {
        Page<AdwebPublicBlackIp> page = new Page<AdwebPublicBlackIp>(pageNo, pageSize);
        String column = req.getParameter("column");
        String order = req.getParameter("order");
        IPage<AdwebPublicBlackIp> pageList =
                adwebBlackIpService.pageList(
                        page, adwebBlackIp.getIp(), adwebBlackIp.getBlackOrWhite(), column, order);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param adwebBlackIp
     * @return
     */
    @AutoLog(value = "IP黑名单-添加")
    @Operation(summary = "IP黑名单-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody AdwebPublicBlackIp adwebBlackIp) {

        if (adwebBlackIp.getIp() == null || "".equals(adwebBlackIp.getIp())) {
            return Result.error("IP不能为空");
        }
        if (adwebBlackIp.getIp().length() > 15) {
            return Result.error("IP长度不能超过15");
        }

        int count =
                (int)
                        adwebBlackIpService.count(
                                new LambdaQueryWrapper<AdwebPublicBlackIp>()
                                        .eq(AdwebPublicBlackIp::getIp, adwebBlackIp.getIp())
                                        .eq(AdwebPublicBlackIp::getStatus, 1));

        if (count > 0) {
            return Result.error("该IP已存在");
        }

        adwebBlackIp.setStatus(1);
        adwebBlackIpService.save(adwebBlackIp);
        List<AdwebPublicBlackIp> blackIpList =
                adwebBlackIpService.list(
                        new LambdaQueryWrapper<AdwebPublicBlackIp>()
                                .eq(AdwebPublicBlackIp::getStatus, 1)
                                .eq(AdwebPublicBlackIp::getBlackOrWhite, 0));

        if (CollectionUtils.isNotEmpty(blackIpList)) {
            List<String> collect =
                    blackIpList.stream()
                            .map(AdwebPublicBlackIp::getIp)
                            .collect(Collectors.toList());
            adwebRedisUtil.set(BlackIpKey, collect, 60 * 60 * 24);
        } else {
            adwebRedisUtil.del(BlackIpKey);
        }

        List<AdwebPublicBlackIp> whiteIpList =
                adwebBlackIpService.list(
                        new LambdaQueryWrapper<AdwebPublicBlackIp>()
                                .eq(AdwebPublicBlackIp::getStatus, 1)
                                .eq(AdwebPublicBlackIp::getBlackOrWhite, 1));

        if (CollectionUtils.isNotEmpty(whiteIpList)) {
            List<String> collect =
                    whiteIpList.stream()
                            .map(AdwebPublicBlackIp::getIp)
                            .collect(Collectors.toList());
            adwebRedisUtil.set(WhiteIpListKey, collect, 60 * 60 * 24);
        } else {
            adwebRedisUtil.del(WhiteIpListKey);
        }
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param adwebBlackIp
     * @return
     */
    @AutoLog(value = "IP黑名单-编辑")
    @Operation(summary = "IP黑名单-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody AdwebPublicBlackIp adwebBlackIp) {

        if (adwebBlackIp.getIp() == null || "".equals(adwebBlackIp.getIp())) {
            return Result.error("IP不能为空");
        }
        if (adwebBlackIp.getIp().length() > 15) {
            return Result.error("IP长度不能超过15");
        }

        int count =
                (int)
                        adwebBlackIpService.count(
                                new LambdaQueryWrapper<AdwebPublicBlackIp>()
                                        .eq(AdwebPublicBlackIp::getIp, adwebBlackIp.getIp())
                                        .eq(AdwebPublicBlackIp::getStatus, 1)
                                        .ne(AdwebPublicBlackIp::getId, adwebBlackIp.getId()));

        if (count > 0) {
            return Result.error("该IP已存在");
        }

        adwebBlackIpService.updateById(adwebBlackIp);

        List<AdwebPublicBlackIp> blackIpList =
                adwebBlackIpService.list(
                        new LambdaQueryWrapper<AdwebPublicBlackIp>()
                                .eq(AdwebPublicBlackIp::getStatus, 1)
                                .eq(AdwebPublicBlackIp::getBlackOrWhite, 0));

        if (CollectionUtils.isNotEmpty(blackIpList)) {
            List<String> collect =
                    blackIpList.stream()
                            .map(AdwebPublicBlackIp::getIp)
                            .collect(Collectors.toList());
            adwebRedisUtil.set(BlackIpKey, collect, 60 * 60 * 24);
        } else {
            adwebRedisUtil.del(BlackIpKey);
        }

        List<AdwebPublicBlackIp> whiteIpList =
                adwebBlackIpService.list(
                        new LambdaQueryWrapper<AdwebPublicBlackIp>()
                                .eq(AdwebPublicBlackIp::getStatus, 1)
                                .eq(AdwebPublicBlackIp::getBlackOrWhite, 1));

        if (CollectionUtils.isNotEmpty(whiteIpList)) {
            List<String> collect =
                    whiteIpList.stream()
                            .map(AdwebPublicBlackIp::getIp)
                            .collect(Collectors.toList());
            adwebRedisUtil.set(WhiteIpListKey, collect, 60 * 60 * 24);
        } else {
            adwebRedisUtil.del(WhiteIpListKey);
        }
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "IP黑名单-通过id删除")
    @Operation(summary = "IP黑名单-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {

        if (id == null || "".equals(id)) {
            return Result.error("ID不能为空");
        }

        List<AdwebPublicBlackIp> list =
                adwebBlackIpService.list(
                        new LambdaQueryWrapper<AdwebPublicBlackIp>()
                                .eq(AdwebPublicBlackIp::getId, id)
                                .eq(AdwebPublicBlackIp::getStatus, 1));

        if (list.size() == 0) {
            return Result.error("该IP不存在");
        }

        AdwebPublicBlackIp adwebBlackIp = list.get(0);
        adwebBlackIp.setStatus(0);

        adwebBlackIpService.updateById(adwebBlackIp);

        adwebRedisUtil.del(IpTenMinKey + adwebBlackIp.getIp());
        adwebRedisUtil.del(IpOneDayKey + adwebBlackIp.getIp());
        adwebRedisUtil.del(NotBlackIpWasteEnquiryKey + adwebBlackIp.getIp());

        List<AdwebPublicBlackIp> blackIpList =
                adwebBlackIpService.list(
                        new LambdaQueryWrapper<AdwebPublicBlackIp>()
                                .eq(AdwebPublicBlackIp::getStatus, 1)
                                .eq(AdwebPublicBlackIp::getBlackOrWhite, 0));

        if (CollectionUtils.isNotEmpty(blackIpList)) {
            List<String> collect =
                    blackIpList.stream()
                            .map(AdwebPublicBlackIp::getIp)
                            .collect(Collectors.toList());
            adwebRedisUtil.set(BlackIpKey, collect, 60 * 60 * 24);
        } else {
            adwebRedisUtil.del(BlackIpKey);
        }

        List<AdwebPublicBlackIp> whiteIpList =
                adwebBlackIpService.list(
                        new LambdaQueryWrapper<AdwebPublicBlackIp>()
                                .eq(AdwebPublicBlackIp::getStatus, 1)
                                .eq(AdwebPublicBlackIp::getBlackOrWhite, 1));

        if (CollectionUtils.isNotEmpty(whiteIpList)) {
            List<String> collect =
                    whiteIpList.stream()
                            .map(AdwebPublicBlackIp::getIp)
                            .collect(Collectors.toList());
            adwebRedisUtil.set(WhiteIpListKey, collect, 60 * 60 * 24);
        } else {
            adwebRedisUtil.del(WhiteIpListKey);
        }

        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "IP黑名单-批量删除")
    @Operation(summary = "IP黑名单-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {

        if (ids == null || "".equals(ids.trim())) {
            return Result.error("ID不能为空");
        }
        List<String> idList = Arrays.asList(ids.split(","));

        List<AdwebPublicBlackIp> list =
                adwebBlackIpService.list(
                        new LambdaQueryWrapper<AdwebPublicBlackIp>()
                                .eq(AdwebPublicBlackIp::getStatus, 1)
                                .in(AdwebPublicBlackIp::getId, idList));

        if (list.size() == 0) {
            return Result.error("该IP不存在");
        }

        adwebBlackIpService.update(
                new LambdaUpdateWrapper<AdwebPublicBlackIp>()
                        .in(AdwebPublicBlackIp::getId, idList)
                        .set(AdwebPublicBlackIp::getStatus, 0));

        for (AdwebPublicBlackIp adwebBlackIp : list) {
            adwebRedisUtil.del(IpTenMinKey + adwebBlackIp.getIp());
            adwebRedisUtil.del(IpOneDayKey + adwebBlackIp.getIp());
            adwebRedisUtil.del(NotBlackIpWasteEnquiryKey + adwebBlackIp.getIp());
        }

        List<AdwebPublicBlackIp> blackIpList =
                adwebBlackIpService.list(
                        new LambdaQueryWrapper<AdwebPublicBlackIp>()
                                .eq(AdwebPublicBlackIp::getStatus, 1)
                                .eq(AdwebPublicBlackIp::getBlackOrWhite, 0));

        if (CollectionUtils.isNotEmpty(blackIpList)) {
            List<String> collect =
                    blackIpList.stream()
                            .map(AdwebPublicBlackIp::getIp)
                            .collect(Collectors.toList());
            adwebRedisUtil.set(BlackIpKey, collect, 60 * 60 * 24);
        } else {
            adwebRedisUtil.del(BlackIpKey);
        }

        List<AdwebPublicBlackIp> whiteIpList =
                adwebBlackIpService.list(
                        new LambdaQueryWrapper<AdwebPublicBlackIp>()
                                .eq(AdwebPublicBlackIp::getStatus, 1)
                                .eq(AdwebPublicBlackIp::getBlackOrWhite, 1));

        if (CollectionUtils.isNotEmpty(whiteIpList)) {
            List<String> collect =
                    whiteIpList.stream()
                            .map(AdwebPublicBlackIp::getIp)
                            .collect(Collectors.toList());
            adwebRedisUtil.set(WhiteIpListKey, collect, 60 * 60 * 24);
        } else {
            adwebRedisUtil.del(WhiteIpListKey);
        }

        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "IP黑名单-通过id查询")
    @Operation(summary = "IP黑名单-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {

        if (id == null || "".equals(id)) {
            return Result.error("ID不能为空");
        }

        List<AdwebPublicBlackIp> list =
                adwebBlackIpService.list(
                        new LambdaQueryWrapper<AdwebPublicBlackIp>()
                                .eq(AdwebPublicBlackIp::getId, id)
                                .eq(AdwebPublicBlackIp::getStatus, 1));

        if (list.size() == 0) {
            return Result.error("该IP不存在");
        }

        return Result.OK(list.get(0));
    }

    /**
     * 导出excel
     *
     * @param request
     * @param adwebBlackIp
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, AdwebPublicBlackIp adwebBlackIp) {
        return super.exportXls(request, adwebBlackIp, AdwebPublicBlackIp.class, "IP黑名单");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, AdwebPublicBlackIp.class);
    }
}
