package com.storlead.sales.service.impl.customer;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.common.result.Result;
import com.storlead.framework.mybatis.entity.SysBaseField;
import com.storlead.sales.pojo.dto.customer.CustomerFollowUpEmailsSearchDTO;
import com.storlead.sales.pojo.entity.customer.*;
import com.storlead.sales.pojo.vo.customer.CustomerFollowUpEmailsListVO;
import com.storlead.sales.enums.ResourceTypeEnum;
import com.storlead.sales.mapper.customer.CustomerFollowUpEmailsMapper;
import com.storlead.sales.service.customer.*;
import com.storlead.framework.mybatis.service.impl.MyBaseServiceImpl;
import com.storlead.mail.pojo.entity.EmailsEntity;
import com.storlead.mail.service.EmailsService;
import com.storlead.mail.service.MailAttachmentService;
import com.storlead.sales.service.CustomerMailRecordService;
import com.storlead.system.pojo.entity.SysDictDetailEntity;
import com.storlead.system.service.SysDictDetailService;
import io.micrometer.core.instrument.util.StringUtils;
import ma.glasnost.orika.impl.DefaultMapperFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

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

/**
 * <p>
 * VIEW 服务实现类
 * </p>
 *
 * @author YPZ
 * @since 2024-10-28
 */
@Service
public class CustomerFollowUpEmailsServiceImpl extends MyBaseServiceImpl<CustomerFollowUpEmailsMapper, CustomerFollowUpEmailsEntity> implements CustomerFollowUpEmailsService {

    @Resource
    private CustomerFollowUpService customerFollowUpService;
    @Resource
    private CustomerMailRecordService customerMailRecordService;
    @Resource
    private SysDictDetailService dictDetailService;
    @Resource
    private LiaisonService liaisonService;
    @Resource
    private EmailsService emailsService;
    @Resource
    private CustomerService customerService;
    @Resource
    private MailAttachmentService mailAttachmentService;
    @Resource
    private CustomerCompanyService customerCompanyService;
    @Resource
    private SysResourceService sysResourceService;
    @Override
    public Result selectListVO(CustomerFollowUpEmailsSearchDTO customerFollowUpEmailsSearchDTO) {
        IPage<CustomerFollowUpEmailsEntity> page = new Page<>(customerFollowUpEmailsSearchDTO.getPageIndex(), customerFollowUpEmailsSearchDTO.getPageSize());
        LambdaQueryWrapper<CustomerFollowUpEmailsEntity> wrapper = new LambdaQueryWrapper<>();
//        wrapper.eq(!ObjectUtils.isEmpty(customerFollowUpEmailsSearchDTO.getCustomerId()),CustomerFollowUpEmailsEntity::getCustomerId,customerFollowUpEmailsSearchDTO.getCustomerId());
        wrapper.eq(!ObjectUtils.isEmpty(customerFollowUpEmailsSearchDTO.getType()),CustomerFollowUpEmailsEntity::getType,customerFollowUpEmailsSearchDTO.getType());
        wrapper.eq(!ObjectUtils.isEmpty(customerFollowUpEmailsSearchDTO.getInOutMark()),CustomerFollowUpEmailsEntity::getInOutMark,customerFollowUpEmailsSearchDTO.getInOutMark());
        wrapper.eq(!ObjectUtils.isEmpty(customerFollowUpEmailsSearchDTO.getObjectiveValue()),CustomerFollowUpEmailsEntity::getObjectiveValue,customerFollowUpEmailsSearchDTO.getObjectiveValue());
        wrapper.eq(!ObjectUtils.isEmpty(customerFollowUpEmailsSearchDTO.getFollowStatus()),CustomerFollowUpEmailsEntity::getFollowStatus,customerFollowUpEmailsSearchDTO.getFollowStatus());
        wrapper.eq(!ObjectUtils.isEmpty(customerFollowUpEmailsSearchDTO.getResourceType()),CustomerFollowUpEmailsEntity::getResourceType,customerFollowUpEmailsSearchDTO.getResourceType());
        wrapper.eq(!ObjectUtils.isEmpty(customerFollowUpEmailsSearchDTO.getFollowUpTypeValue()),CustomerFollowUpEmailsEntity::getFollowUpTypeValue,customerFollowUpEmailsSearchDTO.getFollowUpTypeValue());
        wrapper.in(!CollectionUtils.isEmpty(customerFollowUpEmailsSearchDTO.getCreatedByList()),CustomerFollowUpEmailsEntity::getCreateBy,customerFollowUpEmailsSearchDTO.getCreatedByList());
        wrapper.like(!ObjectUtils.isEmpty(customerFollowUpEmailsSearchDTO.getSubject()),CustomerFollowUpEmailsEntity::getSubject,customerFollowUpEmailsSearchDTO.getSubject());
        wrapper.ge(!ObjectUtils.isEmpty(customerFollowUpEmailsSearchDTO.getFollowUpBeginTime()),CustomerFollowUpEmailsEntity::getSentDate,customerFollowUpEmailsSearchDTO.getFollowUpBeginTime());
        wrapper.le(!ObjectUtils.isEmpty(customerFollowUpEmailsSearchDTO.getFollowUpEndTime()),CustomerFollowUpEmailsEntity::getSentDate,customerFollowUpEmailsSearchDTO.getFollowUpEndTime());
        wrapper.eq(CustomerFollowUpEmailsEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
        if (!ObjectUtils.isEmpty(customerFollowUpEmailsSearchDTO.getBlurry())){
            wrapper.and(w -> w.like(CustomerFollowUpEmailsEntity::getSubject,customerFollowUpEmailsSearchDTO.getBlurry()).or().like(CustomerFollowUpEmailsEntity::getContent,customerFollowUpEmailsSearchDTO.getBlurry()));

        }
        if (!CollectionUtils.isEmpty(customerFollowUpEmailsSearchDTO.getLiaisonIdList())){
            String sql = "CONCAT(',',liaison_ids,',') REGEXP ',"+concatRegexp(customerFollowUpEmailsSearchDTO.getLiaisonIdList())+",'";
            wrapper.apply(sql);
        }
//        if(!ObjectUtils.isEmpty(customerFollowUpEmailsSearchDTO.getCustomerId())){
//            wrapper.apply("FIND_IN_SET({0}, customer_ids)", customerFollowUpEmailsSearchDTO.getCustomerId());
//        }
        wrapper.eq(!ObjectUtils.isEmpty(customerFollowUpEmailsSearchDTO.getCustomerId()),CustomerFollowUpEmailsEntity::getCustomerId,customerFollowUpEmailsSearchDTO.getCustomerId());
        wrapper.orderByDesc(CustomerFollowUpEmailsEntity::getFollowUpTime);

//        page = pageWithScope(page, wrapper,customerFollowUpEmailsSearchDTO,"");
        page = page(page, wrapper);
        if (CollectionUtils.isEmpty(page.getRecords())){
            return Result.result(page);
        }
        DefaultMapperFactory mapperFactory = new DefaultMapperFactory.Builder().build();
        List<CustomerFollowUpEmailsListVO> customerFollowUpEmailsListVO = mapperFactory.getMapperFacade().mapAsList(page.getRecords(),CustomerFollowUpEmailsListVO.class);
//        SysBaseField.dictFileds(customerFollowUpEmailsListVO);
        //获取有跟进的邮件list
        List<CustomerFollowUpEmailsListVO> customerEmailsListVO = customerFollowUpEmailsListVO.stream().filter(item -> item.getType().equals(ResourceTypeEnum.EMAIL.code) && !ObjectUtils.isEmpty(item.getFollowUpId()) && !item.getFollowUpId().equals(0L)).collect(Collectors.toList());
        //获取跟进map
//        List<Long> customerFollowUpIdList = customerEmailsListVO.stream().map(CustomerFollowUpEmailsListVO::getFollowUpId).collect(Collectors.toList());
//        Map<Long, CustomerFollowUpEntity> customerFollowUpMap = new HashMap<>();
//        if (!CollectionUtils.isEmpty(customerFollowUpIdList)){
//            customerFollowUpMap = customerFollowUpService.list(new LambdaQueryWrapper<CustomerFollowUpEntity>().in(CustomerFollowUpEntity::getId, customerFollowUpIdList)).stream().collect(Collectors.toMap(CustomerFollowUpEntity::getId, item -> item));
//
//        }
//        List<EmailsEntity> emailList = new ArrayList<>();
        Map<Long,EmailsEntity> emailMap = new HashMap<>();
        List<Long> mailIds = customerFollowUpEmailsListVO.stream().filter(e ->Objects.nonNull(e.getMailId())).map(CustomerFollowUpEmailsListVO::getMailId).collect(Collectors.toList());
        List<Long> followUpIdList = customerFollowUpEmailsListVO.stream().filter(e ->Objects.nonNull(e.getFollowUpId())).map(CustomerFollowUpEmailsListVO::getFollowUpId).collect(Collectors.toList());
        List<EmailsEntity> emailList = emailsService.listByIds(mailIds);
        emailMap = emailList.stream().collect(Collectors.toMap(EmailsEntity::getId, item -> item));
        CustomerCompanyEntity customerCompany = new CustomerCompanyEntity();
        if (!ObjectUtils.isEmpty(customerFollowUpEmailsSearchDTO.getCustomerId())) {
//        List<Long> customerIdList = customerEmailsListVO.stream().map(CustomerFollowUpEmailsListVO::getCustomerId).collect(Collectors.toList());
            LambdaQueryWrapper<CustomerCompanyEntity> customerCompanyEntityLambdaQueryWrapper = new LambdaQueryWrapper<>();
            customerCompanyEntityLambdaQueryWrapper.eq(CustomerCompanyEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
            customerCompanyEntityLambdaQueryWrapper.eq(CustomerCompanyEntity::getCustomerId, customerFollowUpEmailsSearchDTO.getCustomerId());
            customerCompanyEntityLambdaQueryWrapper.last("limit 1");
            customerCompany = customerCompanyService.getOne(customerCompanyEntityLambdaQueryWrapper);
        }
        if (!ObjectUtils.isEmpty(customerFollowUpEmailsSearchDTO.getCustomerId()) && !CollectionUtils.isEmpty(customerEmailsListVO)) {
            List<Long> mailIdList = customerEmailsListVO.stream().map(CustomerFollowUpEmailsListVO::getMailId).collect(Collectors.toList());

            Map<String, CustomerFollowUpEntity> customerFollowUpMap = new HashMap<>();
            customerFollowUpMap = customerFollowUpService.list(new LambdaQueryWrapper<CustomerFollowUpEntity>().eq(CustomerFollowUpEntity::getCustomerId, customerFollowUpEmailsSearchDTO.getCustomerId()).in(CustomerFollowUpEntity::getMailId, mailIdList)).stream().collect(Collectors.toMap(item->item.getCustomerId() + "-" + item.getMailId(), item -> item));
            //获取邮件idList
//            List<Long> mailIdList = customerEmailsListVO.stream().map(CustomerFollowUpEmailsListVO::getMailId).collect(Collectors.toList());
            for (CustomerFollowUpEmailsListVO item : customerEmailsListVO) {
                if (!CollectionUtils.isEmpty(customerFollowUpMap)) {
                    if (item.getType().equals(ResourceTypeEnum.EMAIL.code) && !ObjectUtils.isEmpty(item.getFollowUpId()) && !item.getFollowUpId().equals(0L)) {
                        CustomerFollowUpEntity customerFollowUp = customerFollowUpMap.get(customerFollowUpEmailsSearchDTO.getCustomerId()+"-"+ item.getMailId());
                        if (!ObjectUtils.isEmpty(customerFollowUp)) {
                            item.setFollowUpId(customerFollowUp.getId());
                            item.setObjectiveValue(customerFollowUp.getObjectiveValue());
                            item.setResourceType(customerFollowUp.getResourceType());
                            item.setResourceTypeId(customerFollowUp.getResourceTypeId());
                            item.setCreateBy(customerFollowUp.getCreateBy());
                            item.setContent(customerFollowUp.getContent());
//                            LocalDateTime followUpTime = LocalDateUtils.date2LocalDateTime(customerFollowUp.getCreateTime());
//                            item.setFollowUpTime(followUpTime);
//                    item.setFollowUpTypeValue(customerFollowUpMap.get(item.getFollowUpId()).getObjectiveValue());

                        }
                    }
                }

            }
        }
        for (CustomerFollowUpEmailsListVO item : customerFollowUpEmailsListVO){

            Map<String, SysDictDetailEntity> dictMap = dictDetailService.getDictDetailByCode("work_data_group");
            if (!CollectionUtils.isEmpty(dictMap)) {

                if (!ObjectUtils.isEmpty(item.getResourceType()) && !ObjectUtils.isEmpty(item.getResourceTypeId())) {
                    //返回资源类型名称
                    item.setResourceTypeName(ResourceTypeEnum.getDescByCode(item.getResourceType()));
                    String resourceName = customerFollowUpService.getResourceTyepName(item.getResourceType(), item.getResourceTypeId().toString());

                    item.setResourceName(resourceName);
                }
            }

            if (!ObjectUtils.isEmpty(item.getLiaisonIds())){
               List<Long> liaisonIds = Arrays.stream(item.getLiaisonIds().split(","))
                        .map(Long::parseLong)
                        .collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(liaisonIds)){
                    //写入收件人邮箱
                    List<LiaisonEntity> liaisonList = liaisonService.list(new LambdaQueryWrapper<LiaisonEntity>().in(LiaisonEntity::getId, liaisonIds).eq(!ObjectUtils.isEmpty(customerFollowUpEmailsSearchDTO.getCustomerId()),LiaisonEntity::getCustomerId, customerFollowUpEmailsSearchDTO.getCustomerId()));
                    if (!CollectionUtils.isEmpty(liaisonList)) {
                        Set<String> recipientls = liaisonList.stream().map(LiaisonEntity::getEmail).collect(Collectors.toSet());
                        Set<String> liaisonNames = liaisonList.stream().map(LiaisonEntity::getName).collect(Collectors.toSet());
                        item.setRecipientls(recipientls);
                        item.setLiaisonNames(liaisonNames);
                    }
                }
            }
            //如果没有主题，返回无主题
            item.setSubject(StringUtils.isEmpty(item.getSubject())?"无主题":item.getSubject());
        }

        for (CustomerFollowUpEmailsListVO item : customerFollowUpEmailsListVO) {
            if (CollectionUtils.isEmpty(item.getLiaisonNames())){
                if (!ObjectUtils.isEmpty(customerCompany)) {
                    EmailsEntity emails = emailMap.get(item.getMailId());
                    if (!ObjectUtils.isEmpty(emails)) {
                        String emailsString = emails.getFrom();
                        if (emails.getInOutMark()==2){
                            emailsString = emails.getRecipient();
                        }
                        if (!ObjectUtils.isEmpty(customerCompany.getEmail3()) && emailsString.equals(customerCompany.getEmail3())){
                            item.setLiaisonNames(Set.of("备用邮箱3"));
                        }
                        if (!ObjectUtils.isEmpty(customerCompany.getEmail2()) && emailsString.equals(customerCompany.getEmail2())){
                            item.setLiaisonNames(Set.of("备用邮箱2"));
                        }
                        if (!ObjectUtils.isEmpty(customerCompany.getEmail1()) && emailsString.equals(customerCompany.getEmail1())){
                            item.setLiaisonNames(Set.of("备用邮箱1"));
                        }
                        if (!ObjectUtils.isEmpty(customerCompany.getEmail()) && emailsString.equals(customerCompany.getEmail())){
                            item.setLiaisonNames(Set.of("企业邮箱"));
                        }

                    }
                }
            }
        }


        if (!CollectionUtils.isEmpty(followUpIdList) && !CollectionUtils.isEmpty(customerFollowUpEmailsListVO)) {
            QueryWrapper sysResourceEntityLambdaQueryWrapper = new QueryWrapper<>();
            sysResourceEntityLambdaQueryWrapper.eq("resource_type","90");
            sysResourceEntityLambdaQueryWrapper.eq("is_delete",0);
            sysResourceEntityLambdaQueryWrapper.in("resource_type_id",followUpIdList);
            sysResourceEntityLambdaQueryWrapper.select("resource_type_id as followUpId, COUNT(*) as fileNum").groupBy("resource_type_id");
            List<Map<Long, Object>> countMaps =  sysResourceService.listMaps(sysResourceEntityLambdaQueryWrapper);
            Map<Long, Integer> fileNumMap = new HashMap<>();
            for (Map<Long, Object> map : countMaps) {
                fileNumMap.put(Long.valueOf(map.get("followUpId").toString()), Integer.valueOf(map.get("fileNum").toString()));
            }
            customerFollowUpEmailsListVO.forEach(e -> {
                if (Objects.isNull(fileNumMap.get(e.getFollowUpId()))) {
                    e.setAttachmentNum(0);
                } else {
                    e.setAttachmentNum(fileNumMap.get(e.getFollowUpId()));
                }
            });
        }

        if (!CollectionUtils.isEmpty(mailIds) && !CollectionUtils.isEmpty(customerFollowUpEmailsListVO)) {

            QueryWrapper countAttachmentGroupWp = new QueryWrapper<>();
            countAttachmentGroupWp.in("email_id",mailIds);
            countAttachmentGroupWp.select("email_id as mailId, COUNT(*) as fileNum").groupBy("email_id");
            List<Map<Long, Object>> countMaps =  mailAttachmentService.listMaps(countAttachmentGroupWp);
            Map<Long, Integer> fileNumMap = new HashMap<>();
            for (Map<Long, Object> map : countMaps) {
                fileNumMap.put(Long.valueOf(map.get("mailId").toString()), Integer.valueOf(map.get("fileNum").toString()));
            }
            customerFollowUpEmailsListVO.forEach(e -> {
                if (Objects.nonNull(e.getMailId())) {
                    if (Objects.nonNull(fileNumMap.get(e.getMailId()))) {
                        e.setAttachmentNum(fileNumMap.get(e.getMailId()));
                    }
                }
            });
        }

        IPage<CustomerFollowUpEmailsListVO> pageVO =new Page<>(customerFollowUpEmailsSearchDTO.getPageIndex(), customerFollowUpEmailsSearchDTO.getPageSize());
        pageVO.setTotal(page.getTotal());
        pageVO.setPages(page.getPages());
        pageVO.setRecords(customerFollowUpEmailsListVO);
        pageVO.setCurrent(page.getCurrent());
        SysBaseField.orgFileds(pageVO.getRecords());
        SysBaseField.dictFileds(pageVO.getRecords());
        return Result.result(pageVO);
//        return null;
    }

    private String concatRegexp(List<Long> ids){
        if(ids.size()==0){
            return "-";
        }else {
            return ids.stream().map(String::valueOf).collect(Collectors.joining("|"));
        }
    }
}
