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.apache.commons.lang.StringUtils;
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.AdwebPublicBlackEmail;
import org.jeecg.modules.adweb.enquiry.service.IAdwebPublicBlackEmailService;
import org.springframework.beans.factory.annotation.Autowired;
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: 询盘公共邮箱黑名单
 * @Author: jeecg-boot
 * @Date: 2024-10-29
 * @Version: V1.0
 */
@Tag(name = "询盘公共邮箱黑名单")
@RestController
@RequestMapping("/adweb/enquiryPublicBlackEmail")
@Slf4j
public class AdwebPublicBlackEmailController
        extends JeecgController<AdwebPublicBlackEmail, IAdwebPublicBlackEmailService> {
    @Autowired private IAdwebPublicBlackEmailService adwebPublicBlackEmailService;

    @Resource private AdwebRedisUtil adwebRedisUtil;

    // Email Redis key
    private static final String EmailTenMinKey = "JUDGE_WASTE_ENQUIRY_EMAIL_BY_10_MIN::";
    private static final String EmailOneDayKey = "JUDGE_WASTE_ENQUIRY_EMAIL_BY_ONE_DAY::";
    private static final String BlackEmailKey = "BLACK_EMAIL_LIST";
    private static final String NotBlackEmailWasteEnquiryKey =
            "NOT_BLACK_EMAIL_WASTE_ENQUIRY_MAP::";
    private static final String WhiteEmailListKey = "WHITE_EMAIL_LIST";

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

    public IPage<AdwebPublicBlackEmail> getPageList(
            Page<AdwebPublicBlackEmail> page,
            AdwebPublicBlackEmail enquiryPublicBlackEmail,
            String column,
            String order) {
        IPage<AdwebPublicBlackEmail> pageList =
                adwebPublicBlackEmailService.pageList(
                        page,
                        enquiryPublicBlackEmail.getEmail(),
                        enquiryPublicBlackEmail.getBlackOrWhite(),
                        column,
                        order);
        return pageList;
    }

    /**
     * 添加
     *
     * @param enquiryPublicBlackEmail
     * @return
     */
    @AutoLog(value = "询盘公共邮箱黑名单-添加")
    @Operation(summary = "询盘公共邮箱黑名单-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody AdwebPublicBlackEmail enquiryPublicBlackEmail) {

        if (StringUtils.isBlank(enquiryPublicBlackEmail.getEmail())) {
            return Result.error("邮箱不能为空");
        }

        // 将邮箱转换为小写
        enquiryPublicBlackEmail.setEmail(enquiryPublicBlackEmail.getEmail().trim().toLowerCase());

        int count =
                (int)
                        adwebPublicBlackEmailService.count(
                                new LambdaQueryWrapper<AdwebPublicBlackEmail>()
                                        .ne(AdwebPublicBlackEmail::getStatus, 0)
                                        .eq(
                                                AdwebPublicBlackEmail::getEmail,
                                                enquiryPublicBlackEmail.getEmail()));

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

        enquiryPublicBlackEmail.setStatus(1);
        adwebPublicBlackEmailService.save(enquiryPublicBlackEmail);

        List<AdwebPublicBlackEmail> emailList =
                adwebPublicBlackEmailService.list(
                        new LambdaQueryWrapper<AdwebPublicBlackEmail>()
                                .ne(AdwebPublicBlackEmail::getStatus, 0)
                                .eq(AdwebPublicBlackEmail::getBlackOrWhite, 0));

        if (CollectionUtils.isNotEmpty(emailList)) {
            List<String> collect =
                    emailList.stream()
                            .map(AdwebPublicBlackEmail::getEmail)
                            .collect(Collectors.toList());
            adwebRedisUtil.set(BlackEmailKey, collect, 60 * 60 * 24);
        } else {
            adwebRedisUtil.del(BlackEmailKey);
        }
        List<AdwebPublicBlackEmail> whiteEmailList =
                adwebPublicBlackEmailService.list(
                        new LambdaQueryWrapper<AdwebPublicBlackEmail>()
                                .ne(AdwebPublicBlackEmail::getStatus, 0)
                                .eq(AdwebPublicBlackEmail::getBlackOrWhite, 1));

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

    /**
     * 编辑
     *
     * @param enquiryPublicBlackEmail
     * @return
     */
    @AutoLog(value = "询盘公共邮箱黑名单-编辑")
    @Operation(summary = "询盘公共邮箱黑名单-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody AdwebPublicBlackEmail enquiryPublicBlackEmail) {

        if (StringUtils.isBlank(enquiryPublicBlackEmail.getEmail())) {
            return Result.error("邮箱不能为空");
        }

        // 将邮箱转换为小写
        enquiryPublicBlackEmail.setEmail(enquiryPublicBlackEmail.getEmail().trim().toLowerCase());

        int count =
                (int)
                        adwebPublicBlackEmailService.count(
                                new LambdaQueryWrapper<AdwebPublicBlackEmail>()
                                        .ne(AdwebPublicBlackEmail::getStatus, 0)
                                        .eq(
                                                AdwebPublicBlackEmail::getEmail,
                                                enquiryPublicBlackEmail.getEmail())
                                        .ne(
                                                AdwebPublicBlackEmail::getId,
                                                enquiryPublicBlackEmail.getId()));

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

        adwebPublicBlackEmailService.updateById(enquiryPublicBlackEmail);

        List<AdwebPublicBlackEmail> emailList =
                adwebPublicBlackEmailService.list(
                        new LambdaQueryWrapper<AdwebPublicBlackEmail>()
                                .ne(AdwebPublicBlackEmail::getStatus, 0)
                                .eq(AdwebPublicBlackEmail::getBlackOrWhite, 0));

        if (CollectionUtils.isNotEmpty(emailList)) {
            List<String> collect =
                    emailList.stream()
                            .map(AdwebPublicBlackEmail::getEmail)
                            .collect(Collectors.toList());
            adwebRedisUtil.set(BlackEmailKey, collect, 60 * 60 * 24);
        } else {
            adwebRedisUtil.del(BlackEmailKey);
        }
        List<AdwebPublicBlackEmail> whiteEmailList =
                adwebPublicBlackEmailService.list(
                        new LambdaQueryWrapper<AdwebPublicBlackEmail>()
                                .ne(AdwebPublicBlackEmail::getStatus, 0)
                                .eq(AdwebPublicBlackEmail::getBlackOrWhite, 1));

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

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

        if (StringUtils.isBlank(id)) {
            return Result.error("参数不识别！");
        }

        AdwebPublicBlackEmail enquiryPublicBlackEmail = adwebPublicBlackEmailService.getById(id);

        if (enquiryPublicBlackEmail == null) {
            return Result.error("未找到对应数据");
        }

        enquiryPublicBlackEmail.setStatus(0);

        adwebPublicBlackEmailService.updateById(enquiryPublicBlackEmail);

        adwebRedisUtil.del(EmailTenMinKey + enquiryPublicBlackEmail.getEmail());
        adwebRedisUtil.del(EmailOneDayKey + enquiryPublicBlackEmail.getEmail());
        adwebRedisUtil.del(NotBlackEmailWasteEnquiryKey + enquiryPublicBlackEmail.getEmail());

        List<AdwebPublicBlackEmail> emailList =
                adwebPublicBlackEmailService.list(
                        new LambdaQueryWrapper<AdwebPublicBlackEmail>()
                                .ne(AdwebPublicBlackEmail::getStatus, 0)
                                .eq(AdwebPublicBlackEmail::getBlackOrWhite, 0));

        if (CollectionUtils.isNotEmpty(emailList)) {
            List<String> collect =
                    emailList.stream()
                            .map(AdwebPublicBlackEmail::getEmail)
                            .collect(Collectors.toList());
            adwebRedisUtil.set(BlackEmailKey, collect, 60 * 60 * 24);
        } else {
            adwebRedisUtil.del(BlackEmailKey);
        }
        List<AdwebPublicBlackEmail> whiteEmailList =
                adwebPublicBlackEmailService.list(
                        new LambdaQueryWrapper<AdwebPublicBlackEmail>()
                                .ne(AdwebPublicBlackEmail::getStatus, 0)
                                .eq(AdwebPublicBlackEmail::getBlackOrWhite, 1));

        if (CollectionUtils.isNotEmpty(whiteEmailList)) {
            List<String> collect =
                    whiteEmailList.stream()
                            .map(AdwebPublicBlackEmail::getEmail)
                            .collect(Collectors.toList());
            adwebRedisUtil.set(WhiteEmailListKey, collect, 60 * 60 * 24);
        } else {
            adwebRedisUtil.del(WhiteEmailListKey);
        }

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

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

        if (StringUtils.isBlank(ids)) {
            return Result.error("参数不识别！");
        }

        List<String> idList = Arrays.asList(ids.split(","));

        List<AdwebPublicBlackEmail> list =
                adwebPublicBlackEmailService.list(
                        new LambdaQueryWrapper<AdwebPublicBlackEmail>()
                                .in(AdwebPublicBlackEmail::getId, idList)
                                .ne(AdwebPublicBlackEmail::getStatus, 0));

        if (list.isEmpty()) {
            return Result.error("未找到对应数据");
        }

        boolean update =
                adwebPublicBlackEmailService.update(
                        new LambdaUpdateWrapper<AdwebPublicBlackEmail>()
                                .in(AdwebPublicBlackEmail::getId, idList)
                                .set(AdwebPublicBlackEmail::getStatus, 0));

        // 删除redis中的数据
        for (AdwebPublicBlackEmail enquiryPublicBlackEmail : list) {
            adwebRedisUtil.del(EmailTenMinKey + enquiryPublicBlackEmail.getEmail());
            adwebRedisUtil.del(EmailOneDayKey + enquiryPublicBlackEmail.getEmail());
            adwebRedisUtil.del(NotBlackEmailWasteEnquiryKey + enquiryPublicBlackEmail.getEmail());
        }
        List<AdwebPublicBlackEmail> emailList =
                adwebPublicBlackEmailService.list(
                        new LambdaQueryWrapper<AdwebPublicBlackEmail>()
                                .ne(AdwebPublicBlackEmail::getStatus, 0)
                                .eq(AdwebPublicBlackEmail::getBlackOrWhite, 0));

        if (emailList != null) {
            List<String> collect =
                    emailList.stream()
                            .map(AdwebPublicBlackEmail::getEmail)
                            .collect(Collectors.toList());
            adwebRedisUtil.set(BlackEmailKey, collect, 60 * 60 * 24);
        } else {
            adwebRedisUtil.del(BlackEmailKey);
        }
        List<AdwebPublicBlackEmail> whiteEmailList =
                adwebPublicBlackEmailService.list(
                        new LambdaQueryWrapper<AdwebPublicBlackEmail>()
                                .ne(AdwebPublicBlackEmail::getStatus, 0)
                                .eq(AdwebPublicBlackEmail::getBlackOrWhite, 1));

        if (whiteEmailList != null) {
            List<String> collect =
                    whiteEmailList.stream()
                            .map(AdwebPublicBlackEmail::getEmail)
                            .collect(Collectors.toList());
            adwebRedisUtil.set(WhiteEmailListKey, collect, 60 * 60 * 24);
        } else {
            adwebRedisUtil.del(WhiteEmailListKey);
        }

        return update ? Result.OK("删除成功!") : Result.error("删除失败!");
    }

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

        if (StringUtils.isBlank(id)) {
            return Result.error("参数不识别！");
        }
        AdwebPublicBlackEmail enquiryPublicBlackEmail = adwebPublicBlackEmailService.getById(id);

        if (enquiryPublicBlackEmail == null) {
            return Result.error("未找到对应数据");
        }

        return Result.OK(enquiryPublicBlackEmail);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param enquiryPublicBlackEmail
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(
            HttpServletRequest request, AdwebPublicBlackEmail enquiryPublicBlackEmail) {
        return super.exportXls(
                request, enquiryPublicBlackEmail, AdwebPublicBlackEmail.class, "询盘公共邮箱黑名单");
    }

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