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

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
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.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.adweb.enquiry.entity.AdwebSiteBlackIp;
import org.jeecg.modules.adweb.enquiry.service.IAdwebSiteBlackIpService;
import org.jeecg.modules.adweb.site.entity.AdwebSite;
import org.jeecg.modules.adweb.site.service.IAdwebSiteService;
import org.jeecg.modules.adweb.site.service.ISiteUserPermissionService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: adweb_site_black_ip
 * @Author: jeecg-boot
 * @Date: 2023-08-31
 * @Version: V1.0
 */
@Tag(name = "adweb_site_black_ip")
@RestController
@RequestMapping("/adweb/adwebSiteBlackIp")
@Slf4j
public class AdwebSiteBlackIpController extends JeecgController<AdwebSiteBlackIp, IAdwebSiteBlackIpService> {
    @Resource
    private IAdwebSiteBlackIpService adwebSiteBlackIpService;
    @Resource
    private IAdwebSiteService adwebSiteService;
    @Resource
    private ISiteUserPermissionService siteUserPermissionService;
    @Resource
    private ISysBaseAPI sysBaseAPI;

    @Resource
    private RedisUtil redisUtil;

    private static final String SiteIpTenMinKey = "JUDGE_WASTE_ENQUIRY_SITE_IP_BY_10_MIN::";
    private static final String SiteIpOneDayKey = "JUDGE_WASTE_ENQUIRY_SITE_IP_BY_ONE_DAY::";
    private static final String NotSiteBlackIpWasteEnquiryKey = "NOT_SITE_BLACK_IP_WASTE_ENQUIRY_MAP::";
    private static final String SiteBlackIpKey = "SITE_BLACK_IP_LIST";
    private static final String SiteWhiteIpListKey = "SITE_WHITE_IP_LIST";

    /**
     * 分页列表查询
     *
     * @param adwebSiteBlackIp
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "adweb_site_black_ip-分页列表查询")
    @Operation(summary = "adweb_site_black_ip-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(AdwebSiteBlackIp adwebSiteBlackIp,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {

        Page<AdwebSiteBlackIp> page = new Page<AdwebSiteBlackIp>(pageNo, pageSize);

        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        List<String> codeList = null;
        List<String> uidList = null;
        if (sysBaseAPI.isAdmin()) {

        } else if (sysBaseAPI.isOem()) {
            uidList = sysBaseAPI.getOemGroupUids();
        } else {
            uidList = new ArrayList<>();
            uidList.add(sysUser.getId());
        }
        List<String> siteCodeList = null;
        if (CollectionUtils.isNotEmpty(uidList)) {
            siteCodeList = siteUserPermissionService.getSiteCodeListByUids(uidList);
        }

        if (adwebSiteBlackIp.getSiteId() != null) {
            String siteCode = adwebSiteService.getSiteCodeById(adwebSiteBlackIp.getSiteId());
            if (StringUtils.isNotBlank(siteCode)) {
                QueryWrapper<AdwebSite> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("id", adwebSiteBlackIp.getSiteId()).or().eq("parent_group_code", siteCode);
                queryWrapper.ne("status", 0);
                queryWrapper.in(!sysBaseAPI.isAdmin(), "code", siteCodeList);
                codeList = adwebSiteService.list(queryWrapper).stream().map(AdwebSite::getCode).collect(Collectors.toList());
            }
        } else {
            codeList = siteCodeList;
        }

        String column = req.getParameter("column");
        String order = req.getParameter("order");
        IPage<AdwebSiteBlackIp> pageList = adwebSiteBlackIpService.pageList(page, adwebSiteBlackIp, codeList, column, order);
        List<AdwebSiteBlackIp> record = pageList.getRecords();

        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param adwebSiteBlackIp
     * @return
     */
    @AutoLog(value = "adweb_site_black_ip-添加")
    @Operation(summary = "adweb_site_black_ip-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody AdwebSiteBlackIp adwebSiteBlackIp) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        int count = (int) adwebSiteBlackIpService.count(new QueryWrapper<AdwebSiteBlackIp>().ne("status", 0).eq("ip", adwebSiteBlackIp.getIp())
                .eq("site_id", adwebSiteBlackIp.getSiteId()));

        if (count > 0) {
            return Result.error("当前站点已存在此ip");
        }
        adwebSiteBlackIp.setStatus(1);
        adwebSiteBlackIp.setCreateTime(new Date());
        adwebSiteBlackIpService.save(adwebSiteBlackIp);

        List<AdwebSiteBlackIp> siteBlackIpList = adwebSiteBlackIpService.list(new QueryWrapper<AdwebSiteBlackIp>().eq("status", 1).eq("site_id", adwebSiteBlackIp.getSiteId()));

        if (CollectionUtils.isEmpty(siteBlackIpList)) {
            redisUtil.del(SiteBlackIpKey + "::" + adwebSiteBlackIp.getSiteId());
            redisUtil.del(SiteWhiteIpListKey + "::" + adwebSiteBlackIp.getSiteId());
            return Result.OK("编辑成功!");
        }

        List<String> blackIpList = siteBlackIpList.stream().filter(siteBlackIp -> siteBlackIp.getBlackOrWhite().equals(0)).map(AdwebSiteBlackIp::getIp).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(blackIpList)) {
            redisUtil.set(SiteBlackIpKey + "::" + adwebSiteBlackIp.getSiteId(), blackIpList, 60 * 60 * 24);
        } else {
            redisUtil.del(SiteBlackIpKey + "::" + adwebSiteBlackIp.getSiteId());
        }

        List<String> whiteIpList = siteBlackIpList.stream().filter(siteBlackIp -> siteBlackIp.getBlackOrWhite().equals(1)).map(AdwebSiteBlackIp::getIp).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(whiteIpList)) {
            redisUtil.set(SiteWhiteIpListKey + "::" + adwebSiteBlackIp.getSiteId(), whiteIpList, 60 * 60 * 24);
        } else {
            redisUtil.del(SiteWhiteIpListKey + "::" + adwebSiteBlackIp.getSiteId());
        }
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param adwebSiteBlackIp
     * @return
     */
    @AutoLog(value = "adweb_site_black_ip-编辑")
    @Operation(summary = "adweb_site_black_ip-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody AdwebSiteBlackIp adwebSiteBlackIp) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        int count = (int) adwebSiteBlackIpService.count(new QueryWrapper<AdwebSiteBlackIp>().ne("status", 0).eq("ip", adwebSiteBlackIp.getIp())
                .eq("site_id", adwebSiteBlackIp.getSiteId()).ne("id", adwebSiteBlackIp.getId()));

        if (count > 0) {
            return Result.error("当前站点已存在此ip");
        }
        AdwebSiteBlackIp oldSiteBlackIp = adwebSiteBlackIpService.getById(adwebSiteBlackIp.getId());
        if (!oldSiteBlackIp.getSiteId().equals(adwebSiteBlackIp.getSiteId())) {
            redisUtil.del(SiteBlackIpKey + "::" + oldSiteBlackIp.getSiteId());
            redisUtil.del(SiteWhiteIpListKey + "::" + oldSiteBlackIp.getSiteId());
        }
        adwebSiteBlackIpService.updateById(adwebSiteBlackIp);

        List<AdwebSiteBlackIp> siteBlackIpList = adwebSiteBlackIpService.list(new QueryWrapper<AdwebSiteBlackIp>().eq("status", 1).eq("site_id", adwebSiteBlackIp.getSiteId()));

        if (CollectionUtils.isEmpty(siteBlackIpList)) {
            redisUtil.del(SiteBlackIpKey + "::" + adwebSiteBlackIp.getSiteId());
            redisUtil.del(SiteWhiteIpListKey + "::" + adwebSiteBlackIp.getSiteId());
            return Result.OK("编辑成功!");
        }

        List<String> blackIpList = siteBlackIpList.stream().filter(siteBlackIp -> siteBlackIp.getBlackOrWhite().equals(0)).map(AdwebSiteBlackIp::getIp).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(blackIpList)) {
            redisUtil.set(SiteBlackIpKey + "::" + adwebSiteBlackIp.getSiteId(), blackIpList, 60 * 60 * 24);
        } else {
            redisUtil.del(SiteBlackIpKey + "::" + adwebSiteBlackIp.getSiteId());
        }

        List<String> whiteIpList = siteBlackIpList.stream().filter(siteBlackIp -> siteBlackIp.getBlackOrWhite().equals(1)).map(AdwebSiteBlackIp::getIp).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(whiteIpList)) {
            redisUtil.set(SiteWhiteIpListKey + "::" + adwebSiteBlackIp.getSiteId(), whiteIpList, 60 * 60 * 24);
        } else {
            redisUtil.del(SiteWhiteIpListKey + "::" + adwebSiteBlackIp.getSiteId());
        }
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "adweb_site_black_ip-通过id删除")
    @Operation(summary = "adweb_site_black_ip-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

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

        List<AdwebSiteBlackIp> list = adwebSiteBlackIpService.list(new QueryWrapper<AdwebSiteBlackIp>().eq("id", id).eq("status", 1));

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

        AdwebSiteBlackIp adwebSiteBlackIp = list.get(0);
        adwebSiteBlackIp.setStatus(0);
        adwebSiteBlackIpService.updateById(adwebSiteBlackIp);

        redisUtil.del(SiteIpTenMinKey + adwebSiteBlackIp.getSiteId() + "::" + adwebSiteBlackIp.getIp());
        redisUtil.del(SiteIpOneDayKey + adwebSiteBlackIp.getSiteId() + "::" + adwebSiteBlackIp.getIp());
        redisUtil.del(NotSiteBlackIpWasteEnquiryKey + adwebSiteBlackIp.getSiteId() + "::" + adwebSiteBlackIp.getIp());

        List<AdwebSiteBlackIp> siteBlackIpList = adwebSiteBlackIpService.list(new QueryWrapper<AdwebSiteBlackIp>().eq("status", 1).eq("site_id", adwebSiteBlackIp.getSiteId()));

        if (CollectionUtils.isEmpty(siteBlackIpList)) {
            redisUtil.del(SiteBlackIpKey + "::" + adwebSiteBlackIp.getSiteId());
            redisUtil.del(SiteWhiteIpListKey + "::" + adwebSiteBlackIp.getSiteId());
            return Result.OK("编辑成功!");
        }

        List<String> blackIpList = siteBlackIpList.stream().filter(siteBlackIp -> siteBlackIp.getBlackOrWhite().equals(0)).map(AdwebSiteBlackIp::getIp).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(blackIpList)) {
            redisUtil.set(SiteBlackIpKey + "::" + adwebSiteBlackIp.getSiteId(), blackIpList, 60 * 60 * 24);
        } else {
            redisUtil.del(SiteBlackIpKey + "::" + adwebSiteBlackIp.getSiteId());
        }

        List<String> whiteIpList = siteBlackIpList.stream().filter(siteBlackIp -> siteBlackIp.getBlackOrWhite().equals(1)).map(AdwebSiteBlackIp::getIp).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(whiteIpList)) {
            redisUtil.set(SiteWhiteIpListKey + "::" + adwebSiteBlackIp.getSiteId(), whiteIpList, 60 * 60 * 24);
        } else {
            redisUtil.del(SiteWhiteIpListKey + "::" + adwebSiteBlackIp.getSiteId());
        }

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

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "adweb_site_black_ip-批量删除")
    @Operation(summary = "adweb_site_black_ip-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

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

        List<AdwebSiteBlackIp> list = adwebSiteBlackIpService.list(new QueryWrapper<AdwebSiteBlackIp>().eq("status", 1).in("id", idList));

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

        UpdateWrapper<AdwebSiteBlackIp> adwebSiteBlackIpUpdateWrapper = new UpdateWrapper<>();
        adwebSiteBlackIpUpdateWrapper.in("id", idList);
        adwebSiteBlackIpUpdateWrapper.set("status", 0);
        adwebSiteBlackIpService.update(adwebSiteBlackIpUpdateWrapper);

        HashSet<Integer> siteIdHashSet = new HashSet<Integer>();
        for (AdwebSiteBlackIp adwebSiteBlackIp : list) {
            redisUtil.del(SiteIpTenMinKey + adwebSiteBlackIp.getSiteId() + "::" + adwebSiteBlackIp.getIp());
            redisUtil.del(SiteIpOneDayKey + adwebSiteBlackIp.getSiteId() + "::" + adwebSiteBlackIp.getIp());
            redisUtil.del(NotSiteBlackIpWasteEnquiryKey + adwebSiteBlackIp.getSiteId() + "::" + adwebSiteBlackIp.getIp());
            siteIdHashSet.add(adwebSiteBlackIp.getSiteId());
        }

        for (Integer siteId : siteIdHashSet) {
            List<AdwebSiteBlackIp> siteBlackIpList = adwebSiteBlackIpService.list(new QueryWrapper<AdwebSiteBlackIp>().eq("status", 1).eq("site_id", siteId));

            if (CollectionUtils.isEmpty(siteBlackIpList)) {
                redisUtil.del(SiteBlackIpKey + "::" + siteId);
                redisUtil.del(SiteWhiteIpListKey + "::" + siteId);
                return Result.OK("编辑成功!");
            }

            List<String> blackIpList = siteBlackIpList.stream().filter(siteBlackIp -> siteBlackIp.getBlackOrWhite().equals(0)).map(AdwebSiteBlackIp::getIp).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(blackIpList)) {
                redisUtil.set(SiteBlackIpKey + "::" + siteId, blackIpList, 60 * 60 * 24);
            } else {
                redisUtil.del(SiteBlackIpKey + "::" + siteId);
            }

            List<String> whiteIpList = siteBlackIpList.stream().filter(siteBlackIp -> siteBlackIp.getBlackOrWhite().equals(1)).map(AdwebSiteBlackIp::getIp).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(whiteIpList)) {
                redisUtil.set(SiteWhiteIpListKey + "::" + siteId, whiteIpList, 60 * 60 * 24);
            } else {
                redisUtil.del(SiteWhiteIpListKey + "::" + siteId);
            }
        }

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

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "adweb_site_black_ip-通过id查询")
    @Operation(summary = "adweb_site_black_ip-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        AdwebSiteBlackIp adwebSiteBlackIp = adwebSiteBlackIpService.getById(id);
        if (adwebSiteBlackIp == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(adwebSiteBlackIp);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param adwebSiteBlackIp
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, AdwebSiteBlackIp adwebSiteBlackIp) {
        return super.exportXls(request, adwebSiteBlackIp, AdwebSiteBlackIp.class, "adweb_site_black_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, AdwebSiteBlackIp.class);
    }

}
