package com.storlead.sales.controller.mail;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.storlead.framework.common.result.Result;
import com.storlead.sales.pojo.dto.customer.CustomerMailDTO;
import com.storlead.mail.pojo.entity.EmailsEntity;
import com.storlead.mail.pojo.entity.MailAttachmentEntity;
import com.storlead.mail.pojo.entity.SmtpPopSettingsEntity;
import com.storlead.mail.service.EmailsService;
import com.storlead.mail.service.MailAttachmentService;
import com.storlead.mail.util.FileHelper;
import com.storlead.sales.pojo.entity.mail.CustomerMailRecordEntity;
import com.storlead.sales.service.CustomerMailRecordService;
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.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.Lock;
import java.util.stream.Collectors;

/**
 * <p>
 * 客户联系人关联邮箱 前端控制器
 * </p>
 *
 * @author chenkq
 * @since 2024-08-29
 */
@RestController
@RequestMapping("/customer/mail")
@Log4j2
public class CustomerMailRecordController {

    @Resource
    private CustomerMailRecordService customerMailRecordService;

    @Resource
    private MailAttachmentService mailAttachmentService;

    @Resource
    private EmailsService emailsService;

    private final ConcurrentHashMap<String, Lock> bindEmailLocks = new ConcurrentHashMap<>();


    @PostMapping(value = "/page_list")
    @ApiOperation(value = "获取邮件" )
    @ApiResponses({
            @ApiResponse(code = 200, message = "", response = SmtpPopSettingsEntity.class)
    })
    public Result<?> pageList(CustomerMailDTO dto) {
        if (Objects.isNull(dto.getCustomerId()) && Objects.isNull(dto.getLiaisonId())) {
            return Result.error("参数错误");
        }
        /**
         * 异步关联数据
         */
        bindCustomerMail(dto);
        Page<CustomerMailRecordEntity> page = new Page<>(dto.getPageIndex(),dto.getPageSize());
        LambdaQueryWrapper<CustomerMailRecordEntity> queryWrapper = new LambdaQueryWrapper();
        if (Objects.nonNull(dto.getCustomerId())) {
            queryWrapper.eq(CustomerMailRecordEntity::getCustomerId,dto.getCustomerId());
        }
        if (Objects.nonNull(dto.getLiaisonId())) {
            queryWrapper.eq(CustomerMailRecordEntity::getLiaisonId,dto.getLiaisonId());
        }
        queryWrapper.ge(!ObjectUtils.isEmpty(dto.getBeginTime()), CustomerMailRecordEntity::getRecipientDate, dto.getBeginTime());
        queryWrapper.le(!ObjectUtils.isEmpty(dto.getEndTime()), CustomerMailRecordEntity::getRecipientDate, dto.getEndTime());
        if (StrUtil.isNotBlank(dto.getBlurry())) {
            queryWrapper.and(e -> e.like(CustomerMailRecordEntity::getSubject,dto.getBlurry()).or().like(CustomerMailRecordEntity::getContent,dto.getBlurry()));
        }
        queryWrapper.eq(CustomerMailRecordEntity::getIsDelete,Integer.valueOf(0));
        queryWrapper.orderByDesc(CustomerMailRecordEntity::getRecipientDate);

        IPage<CustomerMailRecordEntity> pageList = customerMailRecordService.page(page,queryWrapper);

        if (!CollectionUtils.isEmpty(pageList.getRecords())) {
            List<CustomerMailRecordEntity> entities = pageList.getRecords();
            List<Long> mIds = entities.stream().map(CustomerMailRecordEntity::getMailId).collect(Collectors.toList());
            List<EmailsEntity> emailsls = emailsService.list(new LambdaQueryWrapper<EmailsEntity>().eq(EmailsEntity::getId,mIds));
            Map<Long, EmailsEntity> emailMap = emailsls.stream().collect(Collectors.toMap(EmailsEntity::getId, e -> e));
            pageList.getRecords().forEach(m ->{
                EmailsEntity entity = emailMap.get(m.getMailId());
                if (Objects.nonNull(entity)) {
                    m.setInOutMark(entity.getInOutMark());
                    m.setFollowUpId(entity.getFollowUpId());
                }
            });
            List<MailAttachmentEntity> attachments = mailAttachmentService.list(new LambdaQueryWrapper<MailAttachmentEntity>().in(MailAttachmentEntity::getEmailId,mIds));
            if (!CollectionUtils.isEmpty(attachments)) {
                attachments.forEach(e -> {
                    e.setFileSizeName(FileHelper.formatFileSize(e.getFileSize()));
                });
                Map<Long,List<MailAttachmentEntity>> attachmentsMap = attachments.stream().collect(Collectors.groupingBy(MailAttachmentEntity::getEmailId));
                pageList.getRecords().forEach(m ->{
                    m.setAttachments(attachmentsMap.get(m.getMailId()));
                });
            }
        }

        return Result.result(pageList);
    }

    public void bindCustomerMail(CustomerMailDTO dto) {
//        if (Objects.nonNull(dto.getCustomerId()) && Objects.nonNull(dto.getLiaisonId())) {
//            customerMailRecordService.mateBindCustomerMail(dto.getCustomerId(),dto.getLiaisonId());
//        }  else if (Objects.nonNull(dto.getCustomerId())) {
//            customerMailRecordService.mateBindCustomerLiaisonMail(dto.getCustomerId());
//        }
    }
}
