package cn.iocoder.yudao.module.order.listener;


import cn.hutool.core.collection.CollectionUtil;
import cn.iocoder.yudao.framework.apollo.core.event.MemberRegEvent;
import cn.iocoder.yudao.framework.mybatis.core.dataobject.BaseDO;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.module.customer.dal.dataobject.customer.CustomerDO;
import cn.iocoder.yudao.module.customer.dal.dataobject.customerContacts.CustomerContactsDO;
import cn.iocoder.yudao.module.customer.service.customer.CustomerService;
import cn.iocoder.yudao.module.customer.service.customerContacts.CustomerContactsService;
import cn.iocoder.yudao.module.customer.service.customerOperateLog.CustomerOperateLogService;
import cn.iocoder.yudao.module.customer.vo.customerOperateLog.CustomerOperateLogCreateReqVO;
import cn.iocoder.yudao.module.ecw.enums.CustomerOperateTypeEnum;
import cn.iocoder.yudao.module.member.api.user.MemberUserApi;
import cn.iocoder.yudao.module.member.api.user.dto.UserRespDTO;
import cn.iocoder.yudao.module.order.dal.dataobject.orderConsignee.OrderConsigneeDO;
import cn.iocoder.yudao.module.order.dal.dataobject.orderConsignor.OrderConsignorDO;
import cn.iocoder.yudao.module.order.service.order.OrderConsigneeService;
import cn.iocoder.yudao.module.order.service.order.OrderConsignorService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 注册会员监听
 *
 * @author zhengYi
 */
@Component("MemberRegListener")
@AllArgsConstructor
@Slf4j
public class MemberRegListener {

    private final CustomerService customerService;

    private final CustomerOperateLogService customerOperateLogService;

    private final CustomerContactsService customerContactsService;

    private final MemberUserApi memberUserApi;

    private final OrderConsigneeService orderConsigneeService;

    private final OrderConsignorService orderConsignorService;

    /**
     * 收货人注册会员，创建客户。之后查一下手机号作为收货人且没有客户档案的数据，有则找到最早一张订单发货人的客户经理，设置为收货人客户档案的客户经理。进入待接收。
     * 	同时更新相同收货人的其他订单对应的收货人客户id。（因为同收货人可能有多张订单）
     *
     * @param event 订单号
     */
    @EventListener(MemberRegEvent.class)
    public void memberRegEvent(MemberRegEvent event) {

        Long userId = event.getUserId();
        log.info("注册会员监听接口 userId={}", userId);

        UserRespDTO user = memberUserApi.getUser(userId);

        if (user == null) {
            return;
        }

        String areaCode = user.getAreaCode();
        String mobile = user.getMobile();

        log.info("区号={} 手机号={}", areaCode, mobile);

        List<CustomerContactsDO> customerContactsDOList = customerContactsService.getByMemberUserId(userId);
        if (CollectionUtil.isNotEmpty(customerContactsDOList)) {

            CustomerContactsDO customerContactsDO = customerContactsDOList.stream()
                    .filter(t -> t.getAreaCode().equals(areaCode) && t.getPhoneNew().equals(mobile)).findFirst().orElse(null);

            if (customerContactsDO == null) {
                log.info("没有找到相同手机号的联系人");
                return;
            }

            Long customerId = customerContactsDO.getCustomerId();
            Long customerContactsDOId = customerContactsDO.getId();

            //并更新其他收货人
            List<OrderConsigneeDO> otherConsigneeDOList = orderConsigneeService.selectList(new LambdaQueryWrapperX<OrderConsigneeDO>()
                    .eq(OrderConsigneeDO::getCountryCode, areaCode)
                    .eq(OrderConsigneeDO::getPhone, mobile)
                    .apply("deleted = 0 and (customer_id is null or customer_id = 0 or customer_contacts_id is null or customer_contacts_id = 0)"));
            if (CollectionUtil.isNotEmpty(otherConsigneeDOList)) {
                for (OrderConsigneeDO consigneeDO : otherConsigneeDOList) {
                    consigneeDO.setCustomerId(customerId);
                    consigneeDO.setCustomerContactsId(customerContactsDOId);
                    orderConsigneeService.updateById(consigneeDO);
                }
            }

            CustomerDO orderConsigneeCustomer = customerService.getCustomer(customerId);
            if (orderConsigneeCustomer != null && orderConsigneeCustomer.getCustomerService() == null) {
                Set<Long> orderIdSet = new HashSet<>();

                //找到最早的订单的发货人对应的客户经理
                otherConsigneeDOList = otherConsigneeDOList.stream().sorted(Comparator.comparing(BaseDO::getCreateTime)).collect(Collectors.toList());
                for (OrderConsigneeDO consigneeDO : otherConsigneeDOList) {
                    Long orderId = consigneeDO.getOrderId();
                    if (orderIdSet.contains(orderId)) {
                        //此订单号处理过就不再处理
                        continue;
                    }
                    orderIdSet.add(orderId);

                    // 发货人不是代理或同行 并且客户存在
                    OrderConsignorDO orderConsignorByOrderId = orderConsignorService.getOrderConsignorByOrderId(orderId);
                    if (orderConsignorByOrderId != null && orderConsignorByOrderId.getCustomerId() != null) {
                        CustomerDO orderConsignorCustomer = customerService.getCustomer(orderConsignorByOrderId.getCustomerId());
                        if (orderConsignorCustomer != null &&  StringUtils.isNotEmpty(orderConsignorCustomer.getType())
                                && !orderConsignorCustomer.getType().contains("2") && !orderConsignorCustomer.getType().contains("3")) {
                            //设置为发货人的客户经理
                            orderConsigneeCustomer.setCustomerService(orderConsignorCustomer.getCustomerService());
                            orderConsigneeCustomer.setConsigneeFirstCustomerService(orderConsignorCustomer.getCustomerService());

                            customerService.updateById(orderConsigneeCustomer);

                            // 纪录日志
                            CustomerOperateLogCreateReqVO customerOperateLogCreateReqVO = new CustomerOperateLogCreateReqVO()
                                    .setOperator(null).setOperatorName(null)
                                    .setCustomerId(orderConsigneeCustomer.getId())
                                    .setNumber(orderConsigneeCustomer.getNumber())
                                    .setName(orderConsigneeCustomer.getName())
                                    .setOldCustomerService(null)
                                    .setNewCustomerService(orderConsigneeCustomer.getCustomerService())
                                    .setOldEstimateEnterOpenSeaTime(orderConsigneeCustomer.getEstimateEnterOpenSeaTime())
                                    .setOrderId(orderConsignorByOrderId.getOrderId()).setOrderNo(null)
                                    .setOperateType(CustomerOperateTypeEnum.ASSIGN.getValue())
                                    .setRemark("会员注册通过手机关联找到收货人，并设置收货人客户经理为发货人的客户经理");
                            customerOperateLogService.createOperateLog(customerOperateLogCreateReqVO);

                            //跳出
                            break;
                        }

                    }
                }

            }
        }
    }
}
