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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.google.gson.Gson;
import com.storlead.framework.common.result.Result;
import com.storlead.sales.pojo.dto.customer.CustomerTransferDTO;
import com.storlead.sales.pojo.dto.customer.CustomerTransferDTO;
import com.storlead.sales.pojo.entity.customer.*;
import com.storlead.sales.pojo.vo.customer.CustomerAllVO;
import com.storlead.sales.enums.ResourceTypeEnum;
import com.storlead.sales.pojo.entity.systemrule.SystemRuleModuleConfigEntity;
import com.storlead.sales.pojo.entity.task.TaskEntity;
import com.storlead.sales.mapper.customer.CustomerTransferMapper;
import com.storlead.sales.service.customer.*;
import com.storlead.framework.mybatis.service.impl.MyBaseServiceImpl;
import com.storlead.sales.service.systemrule.SystemRuleModuleConfigService;
import com.storlead.sales.service.task.TaskService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

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

/**
 * <p>
 * 客户转移表 服务实现类
 * </p>
 *
 * @author YPZ
 * @since 2024-06-03
 */
@Service
public class CustomerTransferServiceImpl extends MyBaseServiceImpl<CustomerTransferMapper, CustomerTransferEntity> implements CustomerTransferService {

    @Resource
    private CustomerService customerService;
    @Resource
    private OrderFormService orderFormService;
    @Resource
    private BusinessService businessService;
    @Resource
    private MessageAssembleService assembleService;
    @Resource
    private CustomerCompanyService customerCompanyService;
    @Resource
    private CustomerOwnerRecordService customerOwnerService;
    @Resource
    private LiaisonService liaisonService;
    @Resource
    private SystemRuleModuleConfigService systemRuleModuleConfigService;
    @Resource
    private TaskService taskService;
    @Override
    public Result<?> transfer(CustomerTransferDTO customerTransferDTO) {

        if(customerTransferDTO.getIdList().isEmpty()){
            return Result.error("转移客户不能为空");
        }
        if(customerTransferDTO.getResourceType().isEmpty()){
            return Result.error("转移类型不能为空");
        }

//        String types = "";
//        if(!CollectionUtils.isEmpty(customerTransferDTO.getTypeList())){
//            types = String.join(",", customerTransferDTO.getTypeList().stream()
//                    .map(Object::toString) // 将Long转换为String
//                    .collect(Collectors.toList())); // 收集为List<String>
//        }
        List<CustomerTransferEntity> customerTransferList = new ArrayList<>();
        /*
        * 1、线索：线索
        * 2、客户：客户、商机、订单、费用、回款、退款、发票、工单
        * 3、商机：商机、订单、费用、回款、退款、发票、工单
        * 4、订单：订单、费用、回款、退款、发票、工单
        *
        * */
//        List<Long> keyIds = new ArrayList<>();
//        Long ownerBy = 0l;
        if (customerTransferDTO.getResourceType().equals(ResourceTypeEnum.CLUS.code)){
            Map<Long, CustomerEntity> customerOldMap = customerService.getCustomerMap(new HashSet<>(customerTransferDTO.getIdList()));
            //线索转移
                //更新线索负责人
                LambdaUpdateWrapper<CustomerEntity> wrapper = new LambdaUpdateWrapper<>();
                wrapper.in(CustomerEntity::getId,customerTransferDTO.getIdList())
//                        .set(CustomerEntity::getFormerOwnerBy,customerTransferDTO.getNewOwnerBy())
                        .setSql("former_owner_by=owner_by")
                        .set(CustomerEntity::getOwnerBy,customerTransferDTO.getNewOwnerBy())
                        .set(CustomerEntity::getHasPublicCustomer,false)
                        .set(CustomerEntity::getHasGarbageCustomer,false)
                        .set(CustomerEntity::getLastFollowUpTime, LocalDateTime.now())
                        .set(CustomerEntity::getOwnerTime,LocalDateTime.now())
                        .set(CustomerEntity::getHasGarbageCustomer,false)
                        //将置公时间置空
                        .set(CustomerEntity::getPublicDate,null)
                        .set(CustomerEntity::getPublicRemindDate,null)
                        .set(CustomerEntity::getGarbageDate,null)
                        .set(CustomerEntity::getGarbageRemindDate,null)
                        .set(CustomerEntity::getDeleteDate,null)
                        .set(CustomerEntity::getDeleteRemindDate,null);


                customerService.update(wrapper);

            LambdaUpdateWrapper<CustomerCompanyEntity> ccWrapper = new LambdaUpdateWrapper<>();
            ccWrapper.in(CustomerCompanyEntity::getCustomerId,customerTransferDTO.getIdList())
                    .set(CustomerCompanyEntity::getOwnerBy,customerTransferDTO.getNewOwnerBy());
            customerCompanyService.update(ccWrapper);

//            Map<Long, CustomerEntity> customerMap = customerService.getCustomerMap(new HashSet<>(customerTransferDTO.getIdList()));
            for (Long customerId : customerTransferDTO.getIdList()){
                CustomerTransferEntity customerTransferEntity = new CustomerTransferEntity();
                customerTransferEntity.setResourceType(customerTransferDTO.getResourceType());
                customerTransferEntity.setResourceTypeId(customerId);
                customerTransferEntity.setOldOwnerBy(customerOldMap.get(customerId).getOwnerBy());
                customerTransferEntity.setNewOwnerBy(customerTransferDTO.getNewOwnerBy());
                customerTransferEntity.setRemark(customerTransferDTO.getRemark());
                customerTransferList.add(customerTransferEntity);

                CustomerEntity customerNow = customerService.getById(customerId);
                //添加归属记录
                CustomerOwnerRecordEntity customerOwnerRecord = new CustomerOwnerRecordEntity();
                customerOwnerRecord.setCustomerId(customerNow.getId());
                customerOwnerRecord.setOldOwnerBy(customerOldMap.get(customerId).getOwnerBy());
                customerOwnerRecord.setNowOwnerBy(customerNow.getOwnerBy());
                if (!ObjectUtils.isEmpty(customerTransferDTO.getOperatingType())){
                    customerOwnerRecord.setOperatingType(customerTransferDTO.getOperatingType());
                }else {
                    customerOwnerRecord.setOperatingType(2);
                }
                try {
                    // 创建 Gson 实例
                    Gson gson = new Gson();
                    CustomerAllVO customerAllVO =new CustomerAllVO();
                    BeanUtils.copyProperties(customerNow,customerAllVO);
                    customerAllVO.setCustomerCompany(customerCompanyService.getByCustomerId(customerNow.getId()));
                    // 将 CustomerEntity 对象转换为 JSON 字符串
                    String jsonString = gson.toJson(customerAllVO);

                    customerOwnerRecord.setCustomerDetail(jsonString);
                    customerOwnerService.save(customerOwnerRecord);
                }catch (Exception e){
                    return Result.error("客户数据更新异常");
                }
            }

            LambdaUpdateWrapper<LiaisonEntity> liaisonLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            liaisonLambdaUpdateWrapper.in(LiaisonEntity::getCustomerId,customerTransferDTO.getIdList())
                    .set(LiaisonEntity::getOwnerBy,customerTransferDTO.getNewOwnerBy());
            liaisonService.update(liaisonLambdaUpdateWrapper);

            //转移未完成的任务
            LambdaQueryWrapper<TaskEntity> taskWrapper = new LambdaQueryWrapper<>();
            taskWrapper.in(TaskEntity::getCustomerId,customerTransferDTO.getIdList());
            taskWrapper.in(TaskEntity::getTaskStatus, Arrays.asList(0,3,4));
            List<TaskEntity> taskList = taskService.list(taskWrapper);
            if (!CollectionUtils.isEmpty(taskList)){
                List<Long> taskIds = taskList.stream().map(TaskEntity::getId).collect(Collectors.toList());
                baseMapper.updateOwnerBy(ResourceTypeEnum.TASK_CANCELED.tableName,customerTransferDTO.getNewOwnerBy(),taskIds);
            }

        }
        if (customerTransferDTO.getResourceType().equals(ResourceTypeEnum.CUSTOMER.code)){
            //客户转移
            Integer num = customerTransferDTO.getIdList().size();
            //判断用户线索上限
            Boolean hasExceed = customerService.maxMemberNum(num, customerTransferDTO.getNewOwnerBy(),ResourceTypeEnum.CUSTOMER.code);
            if (hasExceed){
                return Result.error("客户数量超过上限");
            }
            Map<Long, CustomerEntity> customerOldMap = customerService.getCustomerMap(new HashSet<>(customerTransferDTO.getIdList()));

            //更新客户负责人
            LambdaUpdateWrapper<CustomerEntity> wrapper = new LambdaUpdateWrapper<>();
            wrapper.in(CustomerEntity::getId,customerTransferDTO.getIdList())
                    .setSql("former_owner_by=owner_by")
                    .set(CustomerEntity::getOwnerBy,customerTransferDTO.getNewOwnerBy())
                    .set(CustomerEntity::getHasPublicCustomer,false)
                    .set(CustomerEntity::getHasGarbageCustomer,false)
                    .set(CustomerEntity::getLastFollowUpTime, LocalDateTime.now())
                    .set(CustomerEntity::getOwnerTime,LocalDateTime.now())
                    .set(CustomerEntity::getHasGarbageCustomer,false)
                    //将置公时间置空
                    .set(CustomerEntity::getPublicDate,null)
                    .set(CustomerEntity::getPublicRemindDate,null)
                    .set(CustomerEntity::getGarbageDate,null)
                    .set(CustomerEntity::getGarbageRemindDate,null)
                    .set(CustomerEntity::getDeleteDate,null)
                    .set(CustomerEntity::getDeleteRemindDate,null);
            customerService.update(wrapper);

            LambdaUpdateWrapper<CustomerCompanyEntity> ccWrapper = new LambdaUpdateWrapper<>();
            ccWrapper.in(CustomerCompanyEntity::getCustomerId,customerTransferDTO.getIdList())
                    .set(CustomerCompanyEntity::getOwnerBy,customerTransferDTO.getNewOwnerBy());
            customerCompanyService.update(ccWrapper);

            Map<Long, CustomerEntity> customerMap = customerService.getCustomerMap(new HashSet<>(customerTransferDTO.getIdList()));
            for (Long id : customerTransferDTO.getIdList()){
                CustomerTransferEntity customerTransferEntity = new CustomerTransferEntity();
                customerTransferEntity.setResourceType(customerTransferDTO.getResourceType());
                customerTransferEntity.setResourceTypeId(id);
                customerTransferEntity.setOldOwnerBy(customerOldMap.get(id).getOwnerBy());
                customerTransferEntity.setNewOwnerBy(customerTransferDTO.getNewOwnerBy());
                customerTransferEntity.setRemark(customerTransferDTO.getRemark());
                customerTransferList.add(customerTransferEntity);

                CustomerEntity customerNow = customerService.getById(id);
                //添加归属记录
                CustomerOwnerRecordEntity customerOwnerRecord = new CustomerOwnerRecordEntity();
                customerOwnerRecord.setCustomerId(customerNow.getId());
                customerOwnerRecord.setOldOwnerBy(customerOldMap.get(id).getOwnerBy());
                customerOwnerRecord.setNowOwnerBy(customerNow.getOwnerBy());
                if (!ObjectUtils.isEmpty(customerTransferDTO.getOperatingType())){
                    customerOwnerRecord.setOperatingType(customerTransferDTO.getOperatingType());
                }else {
                    customerOwnerRecord.setOperatingType(2);
                }
                try {
                    // 创建 Gson 实例
                    Gson gson = new Gson();
                    CustomerAllVO customerAllVO =new CustomerAllVO();
                    BeanUtils.copyProperties(customerNow,customerAllVO);
                    customerAllVO.setCustomerCompany(customerCompanyService.getByCustomerId(customerNow.getId()));
                    // 将 CustomerEntity 对象转换为 JSON 字符串
                    String jsonString = gson.toJson(customerAllVO);

                    customerOwnerRecord.setCustomerDetail(jsonString);
                    customerOwnerService.save(customerOwnerRecord);
                }catch (Exception e){
                    return Result.error("客户数据更新异常");
                }

                //转移未成交的商机
                LambdaQueryWrapper<BusinessEntity> businessWrapper = new LambdaQueryWrapper<>();
                businessWrapper.eq(BusinessEntity::getCustomerId,id);
                businessWrapper.ne(BusinessEntity::getStage,4);
//                businessWrapper.eq(BusinessEntity::getOwnerBy,customerMap.get(id).getOwnerBy());
                List<BusinessEntity> businessList = businessService.list(businessWrapper);
                if (!CollectionUtils.isEmpty(businessList)){
                List<Long> businessIds = businessList.stream().map(BusinessEntity::getId).collect(Collectors.toList());
                    baseMapper.updateOwnerBy(ResourceTypeEnum.BUSINESS.tableName,customerTransferDTO.getNewOwnerBy(),businessIds);
                }

                //转移未完成的任务
                LambdaQueryWrapper<TaskEntity> taskWrapper = new LambdaQueryWrapper<>();
                taskWrapper.eq(TaskEntity::getCustomerId,id);
                taskWrapper.in(TaskEntity::getTaskStatus, Arrays.asList(0,3,4));
//                taskWrapper.eq(TaskEntity::getOwnerBy,customerMap.get(id).getOwnerBy());
                List<TaskEntity> taskList = taskService.list(taskWrapper);
                if (!CollectionUtils.isEmpty(taskList)){
                List<Long> taskIds = taskList.stream().map(TaskEntity::getId).collect(Collectors.toList());
                    baseMapper.updateOwnerBy(ResourceTypeEnum.TASK_CANCELED.tableName,customerTransferDTO.getNewOwnerBy(),taskIds);
                }
                //转移订单
//                LambdaQueryWrapper<OrderFormEntity> orderFormWrapper = new LambdaQueryWrapper<>();
//                orderFormWrapper.eq(OrderFormEntity::getCustomerId,id);
//                orderFormWrapper.eq(OrderFormEntity::getOwnerBy,customerMap.get(id).getOwnerBy());
//                List<OrderFormEntity> orderFormList = orderFormService.list(orderFormWrapper);
//                if (!CollectionUtils.isEmpty(orderFormList)) {
//                    List<Long> orderFormIds = orderFormList.stream().map(OrderFormEntity::getId).collect(Collectors.toList());
//                    baseMapper.updateOwnerBy(ResourceTypeEnum.ORDER_FORM.tableName, customerMap.get(id).getOwnerBy(), orderFormIds);
//                }
            }
            LambdaUpdateWrapper<LiaisonEntity> liaisonLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            liaisonLambdaUpdateWrapper.in(LiaisonEntity::getCustomerId,customerTransferDTO.getIdList())
                    .set(LiaisonEntity::getOwnerBy,customerTransferDTO.getNewOwnerBy());
            liaisonService.update(liaisonLambdaUpdateWrapper);
        }
        if (customerTransferDTO.getResourceType().equals(ResourceTypeEnum.BUSINESS.code)){
            //商机转移
                //更新客户负责人
                LambdaUpdateWrapper<BusinessEntity> wrapper = new LambdaUpdateWrapper<>();
                wrapper.in(BusinessEntity::getId,customerTransferDTO.getIdList())
                        .set(BusinessEntity::getOwnerBy,customerTransferDTO.getNewOwnerBy());
                businessService.update(wrapper);
            Map<Long, BusinessEntity> businessMap = businessService.getBusinessMap(customerTransferDTO.getIdList());
            for (Long id : customerTransferDTO.getIdList()){
                CustomerTransferEntity customerTransferEntity = new CustomerTransferEntity();
                customerTransferEntity.setResourceType(customerTransferDTO.getResourceType());
                customerTransferEntity.setResourceTypeId(id);
                customerTransferEntity.setOldOwnerBy(businessMap.get(id).getOwnerBy());
                customerTransferEntity.setNewOwnerBy(customerTransferDTO.getNewOwnerBy());
                customerTransferEntity.setRemark(customerTransferDTO.getRemark());
                customerTransferList.add(customerTransferEntity);

                //转移订单
                LambdaQueryWrapper<OrderFormEntity> orderFormWrapper = new LambdaQueryWrapper<>();
                orderFormWrapper.eq(OrderFormEntity::getBusinessId,id);
                orderFormWrapper.eq(OrderFormEntity::getOwnerBy,businessMap.get(id).getOwnerBy());
                List<OrderFormEntity> orderFormList = orderFormService.list(orderFormWrapper);
                if (!CollectionUtils.isEmpty(orderFormList)){
                    List<Long> orderFormIds = orderFormList.stream().map(OrderFormEntity::getId).collect(Collectors.toList());
                    baseMapper.updateOwnerBy(ResourceTypeEnum.ORDER_FORM.tableName,businessMap.get(id).getOwnerBy(),orderFormIds);

                }
            }
        }
        if (customerTransferDTO.getResourceType().equals(ResourceTypeEnum.ORDER_FORM.code)){
            //订单转移
                //更新订单负责人
                LambdaUpdateWrapper<OrderFormEntity> wrapper = new LambdaUpdateWrapper<>();
                wrapper.in(OrderFormEntity::getId,customerTransferDTO.getIdList())
                        .setSql("former_owner_by=owner_by")
                        .set(OrderFormEntity::getOwnerBy,customerTransferDTO.getNewOwnerBy());
                orderFormService.update(wrapper);
            Map<Long, OrderFormEntity> orderFormMap = orderFormService.getOrderFormMap(customerTransferDTO.getIdList());

            for (Long id : customerTransferDTO.getIdList()){
                CustomerTransferEntity customerTransferEntity = new CustomerTransferEntity();
                customerTransferEntity.setResourceType(customerTransferDTO.getResourceType());
                customerTransferEntity.setResourceTypeId(id);
                customerTransferEntity.setOldOwnerBy(orderFormMap.get(id).getOwnerBy());
                customerTransferEntity.setNewOwnerBy(customerTransferDTO.getNewOwnerBy());
                customerTransferEntity.setRemark(customerTransferDTO.getRemark());
                customerTransferList.add(customerTransferEntity);
            }
        }

        boolean saveOk = saveBatch(customerTransferList);
        if (saveOk){
            for (Long customerId : customerTransferDTO.getIdList()){
                systemRuleModuleConfigService.updateCustomerDate(customerId);
            }

            //发送消息
            if (customerTransferDTO.getResourceType().equals(ResourceTypeEnum.CLUS.code)) {
                assembleService.sendCustomerEventMessages(customerTransferDTO.getIdList().get(0), "TRANSFER_CLUE");
            }
            if (customerTransferDTO.getResourceType().equals(ResourceTypeEnum.CUSTOMER.code)) {
                assembleService.sendCustomerEventMessages(customerTransferDTO.getIdList().get(0), "TRANSFER_CUSTOMER");
            }
            if (customerTransferDTO.getResourceType().equals(ResourceTypeEnum.BUSINESS.code)){
                assembleService.sendBusinessEventMessages(customerTransferDTO.getIdList().get(0),"TRANSFER_OPPORTUNITY");
            }
            if (customerTransferDTO.getResourceType().equals(ResourceTypeEnum.ORDER_FORM.code)){
                assembleService.sendOrderEventMessages(customerTransferDTO.getIdList().get(0),"TRANSFER_ORDER");
            }
            return Result.ok();
        }

        return Result.error("更新失败");
    }
}
