package com.storlead.mail.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 com.storlead.framework.common.constant.CommonConstant;
import com.storlead.framework.util.LoginUserUtil;
import com.storlead.framework.common.result.Result;
import com.storlead.mail.pojo.entity.EmailFolderRuleEntity;
import com.storlead.mail.pojo.entity.EmailsEntity;
import com.storlead.mail.pojo.entity.SmtpPopSettingsEntity;
import com.storlead.mail.enums.EmailFolderlRuleEnum;
import com.storlead.mail.pojo.dto.EmailTemplatesDTO;
import com.storlead.mail.pojo.dto.FolderRuleDTO;
import com.storlead.mail.service.EmailFolderRuleService;
import com.storlead.mail.service.EmailsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.extern.log4j.Log4j2;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 * 用户邮件文件夹出入规则 前端控制器
 * </p>
 *
 * @author chenkq
 * @since 2024-11-12
 */
@RestController
@Log4j2
@RequestMapping("/email/folder/rule")
@Api(tags = "邮件: 邮件自定义入站规则")
public class EmailFolderRuleApiController {

    @Resource
    private EmailFolderRuleService folderRuleService;

    @Resource
    private EmailsService emailsService;

    @PostMapping(value = "/get_folder_rule")
    @ApiOperation(value = "获取规则" )
    public Result<?> getFolderRule() {
        List<EmailFolderlRuleEnum>  ls = Arrays.asList(EmailFolderlRuleEnum.values());
        List<Map>  enumls = new ArrayList<>();
        for (EmailFolderlRuleEnum e : ls) {
            Map<String,String> stringMap = new HashMap<>();
            stringMap.put("code",e.getCode());
            stringMap.put("desc",e.getDesc());
            enumls.add(stringMap);
        }
        return Result.result(enumls);
    }


    @PostMapping(value = "/page_list")
    @ApiOperation(value = "获取文件夹入站规则配置(分页)" )
    @ApiResponses({
            @ApiResponse(code = 200, message = "", response = SmtpPopSettingsEntity.class)
    })
    public Result<?> pageList(EmailTemplatesDTO dto) {

        Long currentUserId = LoginUserUtil.getCurrentUserId();
        Page<EmailFolderRuleEntity> page = new Page<>(dto.getPageIndex(),dto.getPageSize());
        LambdaQueryWrapper<EmailFolderRuleEntity> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(EmailFolderRuleEntity::getOwnerBy,currentUserId);
        queryWrapper.eq(EmailFolderRuleEntity::getIsDelete,Integer.valueOf(0));
        IPage<EmailFolderRuleEntity> pageList = folderRuleService.page(page,queryWrapper);
        return Result.result(pageList);
    }

    @PostMapping(value = "/list")
    @ApiOperation(value = "获取文件夹入站规则" )
    @ApiResponses({
            @ApiResponse(code = 200, message = "", response = SmtpPopSettingsEntity.class)
    })
    public Result<?> list() {
        Long currentUserId = LoginUserUtil.getCurrentUserId();
        List<EmailFolderRuleEntity> list = folderRuleService.getUserFolderRules(currentUserId);
        return Result.result(list);
    }

    @PostMapping(value = "/save")
    @ApiOperation(value = "保存用户规则配置" )
    @ApiResponses({
            @ApiResponse(code = 200, message = "", response = SmtpPopSettingsEntity.class)
    })
    public Result<?> save(EmailFolderRuleEntity entity) {
        Long currentUserId = LoginUserUtil.getCurrentUserId();
        LambdaQueryWrapper<EmailFolderRuleEntity> w = new LambdaQueryWrapper<>();
        w.eq(EmailFolderRuleEntity::getFolderRuleCode,entity.getFolderRuleCode());
        w.eq(EmailFolderRuleEntity::getCompareContent,entity.getCompareContent());
        w.eq(EmailFolderRuleEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
        w.eq(EmailFolderRuleEntity::getOwnerBy,currentUserId);
        if (Objects.isNull(entity.getId())) {
            Integer exit = folderRuleService.count(w);
            if (exit > 0) {
                return Result.error("已存在同样的规则,不能新增同样的入站规则!");
            }
        } else {

            EmailFolderRuleEntity oldFolder = folderRuleService.getOne(w);
            if (Objects.nonNull(oldFolder)) {
                if (!oldFolder.getId().equals(entity.getId())) {
                    return Result.error("已存在同样的入站规则,无法修改!");
                }
            }
        }

        folderRuleService.saveOrUpdate(entity);
        return Result.ok();
    }

    @PostMapping(value = "/saveBatch")
    @ApiOperation(value = "保存用户规则配置" )
    @ApiResponses({
            @ApiResponse(code = 200, message = "", response = SmtpPopSettingsEntity.class)
    })
    public Result<?> save(@RequestBody FolderRuleDTO dto) {
        Long currentUserId = LoginUserUtil.getCurrentUserId();
        if (CollectionUtils.isEmpty(dto.getFolderRules())) {
            return Result.error("参数错误");
        }
        LambdaQueryWrapper<EmailFolderRuleEntity> deleteW = new LambdaQueryWrapper<>();
        deleteW.eq(EmailFolderRuleEntity::getOwnerBy,currentUserId);
        folderRuleService.remove(deleteW);
        folderRuleService.saveOrUpdateBatch(dto.getFolderRules());
        return Result.ok();
    }

    @ApiOperation(value = "删除")
    @PostMapping("deleteIds")
    public Result delete(Long [] ids) {
        if(Objects.isNull(ids)) {
            return Result.error("参数错误");
        }
        folderRuleService.lgDelete(Arrays.asList(ids));

        LambdaUpdateWrapper<EmailsEntity> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.in(EmailsEntity::getCustomFolderId,Arrays.asList(ids));
        updateWrapper.set(EmailsEntity::getCustomFolderId,null);
        emailsService.update(updateWrapper);
        return Result.ok();
    }




    @ApiOperation("禁用或启用")
    @PostMapping("enabled")
    public Result enabled(Long id,Boolean enable) {
        LambdaUpdateWrapper<EmailFolderRuleEntity> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(EmailFolderRuleEntity::getEnabled,enable);
        updateWrapper.eq(EmailFolderRuleEntity::getId,id);
        folderRuleService.update(updateWrapper);
        return Result.ok();
    }
}
