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

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

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.service.customer.CustomerService;
import cn.iocoder.yudao.module.order.dal.dataobject.order.OrderDO;
import cn.iocoder.yudao.module.order.dto.OrderBackInfoDto;
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 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;


    @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.getIsInOpenSea()) {
            // 订单归属客户产生业绩时在公海池，不添加业绩日志
            return;
        }
//        if (info != null && info.getSalesmanId()!=null && info.getSalesmanId()>0L) {//客户经理
//            Long customerId = info.getCustomerId();
//            if (info.getType().contains("2")) {//海外仓归属发货人
//                customerId = info.getConsignorVO().getCustomerId();
//            } else {
//                if (info.getIsCargoControl()) {//非海外控货归属发货人
//                    customerId = info.getConsignorVO().getCustomerId();
//                } else {
//                    if (info.getDrawee() == 1) {//非海外非控货 付款人为发货人  归属发货人
//                        customerId = info.getConsignorVO().getCustomerId();
//                    } else {  //非海外非控货 付款人为其他  归属收货人
//                        customerId = info.getConsigneeVO().getCustomerId();
//                    }
//                }
//            }
        TargetLogDO targetLogDO = new TargetLogDO();
        targetLogDO.setOrderId(orderId);
        targetLogDO.setCustomerId(info.getCustomerId());
        targetLogDO.setUserId(Objects.isNull(info.getSalesmanId()) ? 0L : info.getSalesmanId());
        targetLogDO.setDeptId(Objects.isNull(info.getDeptId()) ? 0L : info.getDeptId());
        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);
//        }
    }
}
