package com.njzscloud.dispose.cst.project.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njzscloud.common.core.ex.Exceptions;
import com.njzscloud.common.mp.support.PageParam;
import com.njzscloud.common.mp.support.PageResult;
import com.njzscloud.common.security.util.SecurityUtil;
import com.njzscloud.dispose.cst.customer.constant.IdentityCategory;
import com.njzscloud.dispose.cst.customer.pojo.entity.CustomerEntity;
import com.njzscloud.dispose.cst.customer.service.CustomerService;
import com.njzscloud.dispose.cst.org.pojo.entity.OrgEntity;
import com.njzscloud.dispose.cst.org.service.OrgService;
import com.njzscloud.dispose.cst.project.mapper.ProjectMapper;
import com.njzscloud.dispose.cst.project.pojo.entity.ProjectEntity;
import com.njzscloud.dispose.cst.project.pojo.param.ProjectQueryParam;
import com.njzscloud.dispose.cst.project.pojo.result.ProjectResult;
import com.njzscloud.dispose.cst.project.service.ProjectService;
import com.njzscloud.dispose.sys.auth.pojo.result.MyResult;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 项目信息
 *
 * @author ljw
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ProjectServiceImpl extends ServiceImpl<ProjectMapper, ProjectEntity> implements ProjectService {

    private final CustomerService customerService;
    private final OrgService orgService;

    @Override
    public void add(ProjectEntity projectEntity) {
        this.save(projectEntity);
    }

    @Override
    public void modify(ProjectEntity projectEntity) {
        this.updateById(projectEntity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void del(List<Long> ids) {
        this.removeBatchByIds(ids);
    }

    @Override
    public ProjectResult detail(Long id) {
        ProjectEntity detail = this.getById(id);
        if (detail == null) {
            return null;
        }
        ProjectResult result = BeanUtil.copyProperties(detail, ProjectResult.class);
        fillCustomerAndOrgInfo(Collections.singletonList(result));
        // 使用 BeanUtil 直接复制属性
        return result;
    }

    @Override
    public PageResult<ProjectResult> paging(PageParam pageParam, ProjectQueryParam queryParam) {
        String projectName = queryParam.getProjectName();

        QueryWrapper<ProjectEntity> ew = Wrappers.<ProjectEntity>query()
            .eq("p.deleted", Boolean.FALSE)
            .like(StrUtil.isNotBlank(projectName), "p.project_name", projectName);

        // 直接调用自定义分页 SQL
        Page<ProjectEntity> page = pageParam.toPage();
        page.addOrder(OrderItem.desc("p.create_time"));
        // 管理员查看全部，非管理员按身份过滤
        if (!SecurityUtil.isAdmin()) {
            MyResult userDetail = SecurityUtil.loginUser();
            Long currentCustomerId = userDetail.getCurrentCustomerId();
            if (currentCustomerId != null) {
                CustomerEntity customer = customerService.getById(currentCustomerId);
                if (customer != null && customer.getIdentityCategory() != null) {
                    ew.eq(IdentityCategory.ChanFei.equals(customer.getIdentityCategory())
                            || IdentityCategory.CaiGou.equals(customer.getIdentityCategory()),
                        "p.fringe_customer_id", currentCustomerId);
                    ew.eq(IdentityCategory.YunShu.equals(customer.getIdentityCategory()),
                        "p.trans_customer_id", currentCustomerId);
                } else {
                    throw Exceptions.clierr("客户信息或客户身份类型不存在");
                }
            } else {
                throw Exceptions.clierr("当前登录人无客户信息");
            }
        }
        Page<ProjectResult> paging = baseMapper.paging(page, ew);

        if (CollUtil.isNotEmpty(paging.getRecords())) {
            fillCustomerAndOrgInfo(paging.getRecords());
        }

        return PageResult.of(paging);
    }

    /**
     * 批量填充运输方 / 产废方（购买方）的客户与组织信息
     */
    private void fillCustomerAndOrgInfo(List<ProjectResult> records) {
        // 收集所有需要的 ID
        Set<Long> transCustomerIds = records.stream().map(ProjectResult::getTransCustomerId).filter(Objects::nonNull).collect(Collectors.toSet());
        Set<Long> fringeCustomerIds = records.stream().map(ProjectResult::getFringeCustomerId).filter(Objects::nonNull).collect(Collectors.toSet());
        Set<Long> transOrgIds = records.stream().map(ProjectResult::getTransOrgId).filter(Objects::nonNull).collect(Collectors.toSet());
        Set<Long> fringeOrgIds = records.stream().map(ProjectResult::getFringeOrgId).filter(Objects::nonNull).collect(Collectors.toSet());

        Set<Long> allCustomerIds = new HashSet<>(transCustomerIds);
        allCustomerIds.addAll(fringeCustomerIds);
        Set<Long> allOrgIds = new HashSet<>(transOrgIds);
        allOrgIds.addAll(fringeOrgIds);

        Map<Long, CustomerEntity> customerMap = Collections.emptyMap();
        Map<Long, OrgEntity> orgMap = Collections.emptyMap();

        if (!allCustomerIds.isEmpty()) {
            customerMap = customerService.listByIds(allCustomerIds).stream().collect(Collectors.toMap(CustomerEntity::getId, it -> it));
        }
        if (!allOrgIds.isEmpty()) {
            orgMap = orgService.listByIds(allOrgIds).stream().collect(Collectors.toMap(OrgEntity::getId, it -> it));
        }

        for (ProjectResult item : records) {
            if (item.getTransCustomerId() != null) {
                item.setTransCustomerInfo(customerMap.get(item.getTransCustomerId()));
            }
            if (item.getFringeCustomerId() != null) {
                item.setFringeCustomerInfo(customerMap.get(item.getFringeCustomerId()));
            }
            if (item.getTransOrgId() != null) {
                item.setTransOrgInfo(orgMap.get(item.getTransOrgId()));
            }
            if (item.getFringeOrgId() != null) {
                item.setFringeOrgInfo(orgMap.get(item.getFringeOrgId()));
            }
        }
    }
}


