package cn.iocoder.yudao.module.order.service.targetLog;

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

import cn.hutool.core.collection.CollectionUtil;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.framework.security.core.LoginUser;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.customer.dal.dataobject.customer.CustomerDO;
import cn.iocoder.yudao.module.customer.service.customer.CustomerService;
import cn.iocoder.yudao.module.order.dal.dataobject.order.OrderDO;
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.dto.OrderBackInfoDto;
import cn.iocoder.yudao.module.order.service.order.OrderConsigneeService;
import cn.iocoder.yudao.module.order.service.order.OrderConsignorService;
import cn.iocoder.yudao.module.order.service.order.OrderQueryService;
import cn.iocoder.yudao.module.order.service.order.OrderService;
import cn.iocoder.yudao.module.order.enums.TargetLogEnum;
import cn.iocoder.yudao.module.order.vo.order.CustomDraweeVO;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import cn.iocoder.yudao.framework.mybatis.core.vo.PageVO;
import cn.iocoder.yudao.framework.mybatis.core.service.AbstractService;
import cn.iocoder.yudao.module.order.vo.targetLog.*;
import cn.iocoder.yudao.module.order.dal.dataobject.targetLog.TargetLogDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.module.order.convert.targetLog.TargetLogConvert;
import cn.iocoder.yudao.module.order.dal.mysql.targetLog.TargetLogMapper;


/**
 * 部门业绩日志 Service 实现类
 *
 * @author 系统管理员
 */
@Service
@Validated
public class TargetLogServiceImpl extends AbstractService<TargetLogMapper, TargetLogDO> implements TargetLogService {

    @Resource
    private TargetLogMapper targetLogMapper;

    @Resource
    private OrderService orderService;

    @Resource
    private OrderQueryService orderQueryService;

    @Resource
    private CustomerService customerService;

    @Resource
    private  OrderConsigneeService orderConsigneeService;

    @Resource
    private OrderConsignorService orderConsignorService ;


    @Override
    public Long createTargetLog(TargetLogCreateReqVO createReqVO) {
        // 插入
        TargetLogDO targetLog = TargetLogConvert.INSTANCE.convert(createReqVO);
        targetLogMapper.insert(targetLog);
        // 返回
        return targetLog.getId();
    }

    @Override
    public void updateTargetLog(TargetLogUpdateReqVO updateReqVO) {
        // 校验存在
//        this.validateTargetLogExists(updateReqVO.getId());
        // 更新
        TargetLogDO updateObj = TargetLogConvert.INSTANCE.convert(updateReqVO);
        targetLogMapper.updateById(updateObj);
    }

    @Override
    public void deleteTargetLog(Long id) {
        // 校验存在
//        this.validateTargetLogExists(id);
        // 删除
        targetLogMapper.deleteById(id);
    }

//    private void validateTargetLogExists(Long id) {
//        if (targetLogMapper.selectById(id) == null) {
//            throw exception(TARGET_LOG_NOT_EXISTS);
//        }
//    }

    @Override
    public TargetLogDO getTargetLog(Long id) {
        return targetLogMapper.selectById(id);
    }

    @Override
    public List<TargetLogDO> getTargetLogList(Collection<Long> ids) {
        return targetLogMapper.selectBatchIds(ids);
    }

    @Override
    public PageResult<TargetLogDO> getTargetLogPage(TargetLogQueryVO query, PageVO page) {
        return targetLogMapper.selectPage(page, query);
    }

    @Override
    public List<TargetLogDO> getTargetLogList(TargetLogQueryVO query) {
        return targetLogMapper.selectList(query);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addTargetLog(Long orderId, Date achievementTime, TargetLogEnum targetLogEnum) {
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        if (targetLogEnum.getType() == 1 || targetLogEnum.getType() == 3) {//装柜和合单
            dealTargetLog(orderId, achievementTime,targetLogEnum.getType());
        } else if (targetLogEnum.getType() == 2 || targetLogEnum.getType() == 4) {//退仓和拆单
            targetLogMapper.delete(new LambdaQueryWrapperX<TargetLogDO>()
                    .eq(TargetLogDO::getOrderId, orderId));
        }
    }

    @Override
    public void addTargetLogs(List<Long> orderIds, Date achievementTime, TargetLogEnum targetLogEnum) {
        if (targetLogEnum.getType() == 3) {//合单，合单前的所有订单业绩归0
            orderIds.stream().forEach(item -> targetLogMapper.delete(new LambdaQueryWrapperX<TargetLogDO>()
                    .eq(TargetLogDO::getOrderId, item)));
        } else if (targetLogEnum.getType() == 4) {//拆单，分别计算每个订单的业绩归属
            orderIds.stream().forEach(item -> dealTargetLog(item, achievementTime,targetLogEnum.getType()));
        }
    }

    @Override
    public List<TargetLogDO> getTargetLogListByUserIds(List<Long> collect, Date startTime,Date endTime) {
        List<TargetLogDO> targetLogDOS = targetLogMapper.selectList(new LambdaQueryWrapperX<TargetLogDO>()
                .betweenIfPresent(TargetLogDO::getAchievementTime, startTime, endTime)
                .in(TargetLogDO::getUserId, collect));
        return targetLogDOS;
    }

    @Override
    public void compensateTargetLog(List<String> list) {
        list.stream().forEach(item -> {
            OrderDO orderDO = orderService.selectOne(OrderDO::getOrderNo, item);
            TargetLogDO targetLogDO = targetLogMapper.selectOne(TargetLogDO::getOrderId, orderDO.getOrderId());
            if (targetLogDO == null) {
                Date time = targetLogMapper.selectCabinetSealingTime(orderDO.getOrderId());
                if (time != null) {
                    dealTargetLog(orderDO.getOrderId(),time,TargetLogEnum.LOADING.getType());
                }
            }
        });
    }

    private void dealTargetLog(Long orderId, Date achievementTime,Integer type) {
        long selectCount = targetLogMapper.selectCount(TargetLogDO::getOrderId, orderId);
        if (selectCount > 0L) {
            return;
        }
        OrderBackInfoDto info = orderQueryService.info(orderId);
        if (info != null && info.getSalesmanId()!=null && info.getSalesmanId()>0L) {//客户经理
            Long customerId = 0L;
            CustomerDO consignorDO = customerService.getCustomer(info.getConsignorVO().getCustomerId());
            CustomerDO consigneeDO = customerService.getCustomer(info.getConsigneeVO().getCustomerId());//收货人
            if (info.getType().contains("2")) {//海外仓归属发货人
                //customerId = info.getConsignorVO().getCustomerId(); //二期需求修改
                customerId = consignorDO.getId();
            } else {

                    OrderConsigneeDO orderConsigneeDO = orderConsigneeService.getOne(new LambdaQueryWrapper<OrderConsigneeDO>().eq(OrderConsigneeDO::getOrderId, info.getOrderId()).orderByDesc(OrderConsigneeDO::getId).last("limit 1"));
                    OrderConsignorDO orderConsignorDO = orderConsignorService.getOne(new LambdaQueryWrapper<OrderConsignorDO>().eq(OrderConsignorDO::getOrderId, info.getOrderId()).orderByDesc(OrderConsignorDO::getId).last("limit 1"));
                    if(info.getIsCargoControl()){
                        customerId = info.getConsignorVO().getCustomerId();
                    }else {
                        if(consignorDO !=null && ! consignorDO.getNoConsignee()  && !info.getHasConsignee()){//发货人档案设置控货无收货人且订单无收获人，归属发货人业绩 -- 层级2
                            if(consignorDO!=null){
                                customerId = consignorDO.getId();
                            }

                        }else{
                            List<TargetOfferBackVO>  offerBackVOList =targetLogMapper.getTargetOfferBackByOrerId(orderId) ;
                            if (info.getDrawee() == 1) {//发货人付款
                                if (info.getDrawee() == 1 && CollectionUtil.isNotEmpty(offerBackVOList)) {//如果是发货人付款且关联报价单，业绩归属发货人 --层级3 第一个

                                    customerId = consignorDO.getId();
                                }else if(info.getDrawee() == 1 && consignorDO.getDefaultPay() ){// 如果是发货人付款且档案设置默认付运费  --层级4 第一个

                                    customerId = consignorDO.getId();
                                }else{
                                    customerId = orderConsigneeDO.getCustomerId() ;
                                }
                            } else if (info.getDrawee() == 2 ) {//收货人付款   层级5 第一个
                                customerId = orderConsigneeDO.getCustomerId()!=null?  orderConsigneeDO.getCustomerId():consigneeDO.getId();
                            } else if (info.getDrawee() == 3) { //自定义付款

                                List<CustomDraweeVO> list = JSONObject.parseArray(info.getCustomDrawee(), CustomDraweeVO.class);
                                if(CollectionUtil.isNotEmpty(list)){

                                    List<CustomDraweeVO>  freightList = list.stream().filter(s-> s.getName().equals("freight")  ).collect(Collectors.toList());
                                    List<CustomDraweeVO>  clearanceFeeList = list.stream().filter(s-> s.getName().equals("clearanceFee")  ).collect(Collectors.toList());
                                    int freight  = freightList.get(0).getValue() ;//运费
                                    int clearanceFee = clearanceFeeList.get(0).getValue();//清关费

                                    if(CollectionUtil.isNotEmpty(offerBackVOList) && ( info.getDrawee()==3 &&  freight==1 )){//层级3 第二个 订单关联报价单 && 自定义付款 且发货人付运费

                                        customerId =  orderConsignorDO.getCustomerId() ;
                                    }else if(CollectionUtil.isNotEmpty(offerBackVOList) && ( info.getDrawee()==3 &&  clearanceFee==1 )){//层级3 第三个 订单关联报价单 && 自定义付款 且发货人付清关费

                                        customerId =  orderConsignorDO.getCustomerId() ;
                                    }else if(consignorDO.getDefaultPay() && ( info.getDrawee()==3 &&  freight==1 )){ //层级4 第二个 发货人档案设置默认付运费 且发货人付运费 业绩归属 发货人

                                        customerId =  orderConsignorDO.getCustomerId() ;
                                    }else if (consignorDO.getDefaultPay() && ( info.getDrawee()==3 &&  clearanceFee==1 )){// 层级4 第三个 发货人档案设置默认付运费 且发货人付清关费  业绩归属发货人

                                        customerId =  orderConsignorDO.getCustomerId() ;
                                    }else {
                                        customerId =  orderConsigneeDO.getCustomerId() ;
                                    }
//                                        if(!consignorDO.getDefaultPay() && (info.getDrawee()==3 && freight==2 ) ||  (info.getDrawee()==3 && clearanceFee==2)){//层级5 第二、第三点  自定义付款且收款人付运费 或自定义付款且收款人付清关费 ，业绩归属收货人
//                                        customerId =  orderConsigneeDO.getCustomerId() ;
//
//                                    }

                                }

                            } else {
                                //业绩归属收货人
                                if(orderConsigneeDO!=null){
                                    customerId =  orderConsigneeDO.getCustomerId() !=null?orderConsigneeDO.getCustomerId():0;
                                }


                            }
                        }
                    }

            }
            TargetLogDO targetLogDO = new TargetLogDO();
            targetLogDO.setOrderId(orderId);
            targetLogDO.setCustomerId(customerId);
            targetLogDO.setUserId(info.getSalesmanId());
            targetLogDO.setAchievementTime(achievementTime);
            if (info.getTransportId() == 3) {
                targetLogDO.setLdBoxTime(achievementTime);
            } else {
                targetLogDO.setLdBoxTime(targetLogMapper.selectCabinetLoadTime(orderId));
            }
            targetLogDO.setCompleteVolume(info.getWVolume());
            targetLogDO.setCompleteWeight(info.getVWeight());
            targetLogDO.setType(type);
            targetLogMapper.insert(targetLogDO);
            // customerService.updateCustomerIsNewToOld(customerId);
        }
    }
}
