package com.storlead.sales.service.impl;

import com.storlead.sales.service.customer.CustomerCompanyService;
import com.storlead.sales.service.customer.CustomerService;
import com.storlead.sales.service.customer.LiaisonService;
import com.storlead.mail.service.EmailsService;
import com.storlead.sales.pojo.entity.mail.CustomerMailRecordEntity;
import com.storlead.sales.mapper.mail.CustomerMailRecordMapper;
import com.storlead.sales.service.CustomerMailBingMarkService;
import com.storlead.sales.service.CustomerMailRecordService;
import com.storlead.framework.mybatis.service.impl.MyBaseServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * <p>
 * 客户联系人关联邮箱 服务实现类
 * </p>
 *
 * @author chenkq
 * @since 2024-08-29
 */
@Service
public class CustomerMailRecordServiceImpl extends MyBaseServiceImpl<CustomerMailRecordMapper, CustomerMailRecordEntity> implements CustomerMailRecordService {

    @Resource
    private LiaisonService liaisonService;
    @Resource
    private CustomerService customerService;
    @Resource
    private CustomerCompanyService companyService;
    @Resource
    private EmailsService emailsService;
    @Resource
    private CustomerMailRecordService mailRecordService;
    @Resource
    private CustomerMailBingMarkService mailBingMarkService;

//    @Override
//    public void mateBindCustomerLiaisonMail(Long customerId) {

//        if (Objects.isNull(customerId)) {
//            return;
//        }
//        // 获取客户的最新的邮件的id
//        CustomerEntity customer = customerService.getById(customerId);
//        if (Objects.isNull(customer)) {
//            return;
//        }
//        QueryWrapper queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("customer_id",customerId);
//        queryWrapper.eq("liaison_id",0);
//        queryWrapper.select("id,max(max_mail_id) as max_mail_id");
//        CustomerMailBingMarkEntity custormerBind  = mailBingMarkService.getOne(queryWrapper);
//        CustomerCompanyEntity customerCompany = companyService.getByCustomerId(customerId);
//        if (Objects.nonNull(customerCompany) && StrUtil.isNotBlank(customerCompany.getEmail())) {
//            String email = customerCompany.getEmail();
//            LambdaQueryWrapper<EmailsEntity> mailWp = new LambdaQueryWrapper<>();
//            mailWp.eq(EmailsEntity::getIsDelete,Integer.valueOf(0));
//            if (Objects.nonNull(custormerBind)) {
//                mailWp.gt(EmailsEntity::getId,custormerBind.getMaxMailId());
//            }
//            mailWp.and(w -> w.apply("CONCAT(',', recipient, ',') like {0}", "%," + email + ",%")
//                    .or()
//                    .apply("CONCAT(',', recipient_cc, ',') like {0}", "%," + email + ",%")
//                    .or()
//                    .apply("CONCAT(',', recipient_cc, ',') like {0}", "%," + email + ",%")
//                    .or()
//                    .apply("CONCAT(',', `from`, ',') like {0}", "%," + email + ",%"));
//            List<EmailsEntity> emails = emailsService.list(mailWp);
//            List<CustomerMailRecordEntity> bindRecoreds = new ArrayList<>();
//            if (!CollectionUtils.isEmpty(emails)) {
//                emails.forEach(e -> {
//                    CustomerMailRecordEntity customerMail = new CustomerMailRecordEntity();
//                    BeanUtils.copyProperties(e,customerMail);
//                    customerMail.setMailId(e.getId());
//                    customerMail.setCustomerId(customerCompany.getCustomerId());
//                    customerMail.setId(null);
//                    bindRecoreds.add(customerMail);
//                });
//            }
//            if (!CollectionUtils.isEmpty(bindRecoreds)) {
//                mailRecordService.saveOrUpdateBatch(bindRecoreds);
//                Optional<EmailsEntity> maxIdEmail = emails.stream()
//                        .max((e1, e2) -> Long.compare(e1.getId(), e2.getId()));
//                EmailsEntity entity = maxIdEmail.get();
//                if (Objects.isNull(custormerBind)) {
//                    custormerBind = new CustomerMailBingMarkEntity();
//                    custormerBind.setCustomerId(customerId);
//                    custormerBind.setLiaisonId(Long.valueOf(0));
//                    custormerBind.setMaxMailId(entity.getId());
//                    mailBingMarkService.save(custormerBind);
//                } else {
//                    custormerBind.setMaxMailId(entity.getId());
//                    mailBingMarkService.updateById(custormerBind);
//                }
//            }
//        }
//
//        List<LiaisonEntity> liaisons = liaisonService.getLiaisonByCustomerId(customerId);
//        if (!CollectionUtils.isEmpty(liaisons)) {
//            for (LiaisonEntity liaison : liaisons) {
//                if (liaison.getIsDelete().equals(1) || StrUtil.isBlank(liaison.getEmail())) {
//                    continue;
//                }
//                mateBindCustomerMail(customerId,liaison);
//            }
//        }
//    }

//    public void mateBindCustomerMail(Long customerId, LiaisonEntity liaison) {
//
//        QueryWrapper queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("customer_id",customerId);
//        queryWrapper.eq("liaison_id",liaison.getId());
//        queryWrapper.select("id,max(max_mail_id) as max_mail_id");
//        CustomerMailBingMarkEntity custormerBind  = mailBingMarkService.getOne(queryWrapper);
//        if (Objects.isNull(liaison) || StrUtil.isBlank(liaison.getEmail())) {
//            return;
//        }
//        // 获取所有邮件
//        if (StrUtil.isNotBlank(liaison.getEmail())) {
//            String email = liaison.getEmail();
//            LambdaQueryWrapper<EmailsEntity> mailWp = new LambdaQueryWrapper<>();
//            mailWp.eq(EmailsEntity::getIsDelete,Integer.valueOf(0));
//            if (Objects.nonNull(custormerBind)) {
//                mailWp.gt(EmailsEntity::getId,custormerBind.getMaxMailId());
//            }
//            mailWp.and(w -> w.apply("CONCAT(',', recipient, ',') like {0}", "%," + email + ",%")
//                    .or()
//                    .apply("CONCAT(',', recipient_cc, ',') like {0}", "%," + email + ",%")
//                    .or()
//                    .apply("CONCAT(',', recipient_cc, ',') like {0}", "%," + email + ",%")
//                    .or()
//                    .apply("CONCAT(',', `from`, ',') like {0}", "%," + email + ",%"));
//
//            List<EmailsEntity> emails = emailsService.list(mailWp);
//            if (CollectionUtils.isEmpty(emails)) {
//                return;
//            }
//            List<CustomerMailRecordEntity> bindRecoreds = new ArrayList<>();
//            if (!CollectionUtils.isEmpty(emails)) {
//
//                emails.forEach(e -> {
//                    CustomerMailRecordEntity customerMail = new CustomerMailRecordEntity();
//                    BeanUtils.copyProperties(e,customerMail);
//                    customerMail.setMailId(e.getId());
//                    customerMail.setCustomerId(customerId);
//                    customerMail.setLiaisonId(liaison.getId());
//                    customerMail.setId(null);
//                    bindRecoreds.add(customerMail);
//                });
//            }
//            if (!CollectionUtils.isEmpty(bindRecoreds)) {
//                mailRecordService.saveOrUpdateBatch(bindRecoreds);
//                Optional<EmailsEntity> maxIdEmail = emails.stream()
//                        .max((e1, e2) -> Long.compare(e1.getId(), e2.getId()));
//                EmailsEntity entity = maxIdEmail.get();
//                if (Objects.isNull(custormerBind)) {
//                    custormerBind = new CustomerMailBingMarkEntity();
//                    custormerBind.setCustomerId(customerId);
//                    custormerBind.setLiaisonId(liaison.getId());
//                    custormerBind.setMaxMailId(entity.getId());
//                    mailBingMarkService.save(custormerBind);
//                } else {
//                    custormerBind.setMaxMailId(entity.getId());
//                    mailBingMarkService.updateById(custormerBind);
//                }
//            }
//        }
//    }

//    @Override
//    public void mateBindCustomerLiaisonFromMail(Long mailId,Long ownerBy,String fromMailAddress) {
//
//        LambdaQueryWrapper<LiaisonEntity> l = new LambdaQueryWrapper<>();
//        l.eq(LiaisonEntity::getEmail,fromMailAddress);
//        l.eq(LiaisonEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
//        l.last("limit 1");
//        LiaisonEntity liaison = liaisonService.getOne(l);
//        if (Objects.nonNull(liaison)) {
//            CustomerMailBingMarkEntity entity = new CustomerMailBingMarkEntity();
//            entity.setCustomerId(liaison.getCustomerId());
//            entity.setLiaisonId(liaison.getId());
//            entity.setMailId(mailId);
//            mailBingMarkService.saveOrUpdate(entity);
//        } else {
//            LambdaQueryWrapper<CustomerCompanyEntity> companyMp = new LambdaQueryWrapper<>();
//            companyMp.eq(CustomerCompanyEntity::getIsDelete,Integer.valueOf(0));
//            companyMp.eq(CustomerCompanyEntity::getEmail,fromMailAddress);
//            l.last("limit 1");
//            CustomerCompanyEntity company = companyService.getOne(companyMp);
//            if (Objects.isNull(company)) {
//                CustomerMailBingMarkEntity entity = new CustomerMailBingMarkEntity();
//                entity.setCustomerId(liaison.getCustomerId());
//                entity.setMailId(mailId);
//                mailBingMarkService.saveOrUpdate(entity);
//            }
//        }
//    }
//
//    @Override
//    public void mateBindCustomerLiaisonRecipientMail(Long mailId,Long ownerBy,String recipientMailAddress) {
//
//        List<CustomerMailBingMarkEntity> mkeList = new ArrayList<>();
//        List<String> mails = Arrays.asList(recipientMailAddress.split(","));
//
//        LambdaQueryWrapper<CustomerCompanyEntity> lw = new LambdaQueryWrapper<>();
//        lw.in(CustomerCompanyEntity::getEmail,mails);
//        lw.eq(CustomerCompanyEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
//        List<CustomerCompanyEntity> companys = companyService.list(lw);
//        if (!CollectionUtils.isEmpty(companys)) {
//            for (CustomerCompanyEntity company : companys) {
//                CustomerMailBingMarkEntity entity = new CustomerMailBingMarkEntity();
//                entity.setCustomerId(company.getCustomerId());
//                entity.setMailId(mailId);
//                mkeList.add(entity);
//            }
//        }
//        Map<Long,CustomerMailBingMarkEntity> mbMap = mkeList.stream().collect(Collectors.toMap(CustomerMailBingMarkEntity::getCustomerId, a -> a));
//
//        LambdaQueryWrapper<LiaisonEntity> l = new LambdaQueryWrapper<>();
//        l.in(LiaisonEntity::getEmail,mails);
//        l.eq(LiaisonEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
//        List<LiaisonEntity> liaisons = liaisonService.list(l);
//        if (!CollectionUtils.isEmpty(liaisons)) {
//            for (LiaisonEntity liaison : liaisons) {
//                CustomerMailBingMarkEntity entity = new CustomerMailBingMarkEntity();
//                if (Objects.nonNull(mbMap.get(liaison.getCustomerId()))) {
//                    entity = mbMap.get(liaison.getCustomerId());
//                } else {
//                    entity.setCustomerId(liaison.getCustomerId());
//                }
//                entity.setLiaisonId(liaison.getId());
//                entity.setMailId(mailId);
//                mkeList.add(entity);
//            }
//        }
//        if (!CollectionUtils.isEmpty(mkeList)) {
//            mailBingMarkService.saveOrUpdateBatch(mkeList);
//        }
//    }
//
//    @Override
//    public void mateBindCustomerMail(Long customerId, Long liaisonId) {
////        LiaisonEntity liaison = liaisonService.getById(liaisonId);
////        mateBindCustomerMail(customerId,liaison);
//    }
}
