package com.greenorange.promotion.service.project.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.greenorange.promotion.common.ErrorCode;
import com.greenorange.promotion.common.ResultUtils;
import com.greenorange.promotion.constant.CommonConstant;
import com.greenorange.promotion.exception.ThrowUtils;
import com.greenorange.promotion.model.dto.CommonRequest;
import com.greenorange.promotion.model.dto.project.ProjectQueryRequest;
import com.greenorange.promotion.model.entity.Project;
import com.greenorange.promotion.model.entity.ProjectCommission;
import com.greenorange.promotion.model.entity.UserInfo;
import com.greenorange.promotion.model.vo.project.ProjectCardVO;
import com.greenorange.promotion.model.vo.project.ProjectVO;
import com.greenorange.promotion.service.common.CommonService;
import com.greenorange.promotion.service.project.ProjectCommissionService;
import com.greenorange.promotion.service.project.ProjectService;
import com.greenorange.promotion.mapper.ProjectMapper;
import com.greenorange.promotion.utils.SqlUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* @author 35880
* @description 针对表【project(项目表)】的数据库操作Service实现
* @createDate 2025-05-06 14:19:08
*/
@Service
public class ProjectServiceImpl extends ServiceImpl<ProjectMapper, Project>
    implements ProjectService{


    @Resource
    private CommonService commonService;


    @Resource
    private ProjectCommissionService projectCommissionService;


    /**
     * 获取查询条件
     */
    @Override
    public QueryWrapper<Project> getQueryWrapper(ProjectQueryRequest projectQueryRequest) {
        Long id = projectQueryRequest.getId();
        String projectName = projectQueryRequest.getProjectName();
        String sortField = projectQueryRequest.getSortField();
        String sortOrder = projectQueryRequest.getSortOrder();
        QueryWrapper<Project> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(id != null, "id", id);
        queryWrapper.eq(StringUtils.isNotBlank(projectName), "projectName", projectName);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC), sortField);
        return queryWrapper;
    }


    /**
     * 小程序用户查看项目列表
     * @return 项目列表
     */
    @Override
    public List<ProjectCardVO> queryProjectCardList(HttpServletRequest request) {

        Long userId = (Long) request.getAttribute("userId");
        // 获取项目明细抽佣列表
        List<ProjectCommission> projectCommissionList = commonService.findByFieldEqTargetFieldWithSpecificFields(
                ProjectCommission::getUserId, userId, projectCommissionService, List.of(ProjectCommission::getProjectId, ProjectCommission::getMyUnitPrice));
        // 封装Map集合（键：项目id, 值：项目总价）
        Map<Long, BigDecimal> projectPriceMap = new HashMap<>();
        for (ProjectCommission projectCommission : projectCommissionList) {
            Long projectId = projectCommission.getProjectId();
            BigDecimal projectPrice = projectPriceMap.get(projectId);
            if (projectPrice == null) {
                projectPrice = projectCommission.getMyUnitPrice();
            } else {
                projectPrice = projectPrice.add(projectCommission.getMyUnitPrice());
            }
            projectPriceMap.put(projectId, projectPrice);
        }
        List<Project> projectList = commonService.findByFieldEqTargetField(Project::getIsShelves, 1, this);
        for (Project project : projectList) {
            BigDecimal projectPrice = projectPriceMap.get(project.getId());
            project.setProjectPrice(projectPrice == null ? BigDecimal.ZERO : projectPrice);
        }
        return commonService.convertList(projectList, ProjectCardVO.class);
    }


    /**
     * web端管理员根据id查询项目
     */
    @Override
    public ProjectVO queryProjectById(CommonRequest commonRequest) {
        Long id = commonRequest.getId();
        Project project = this.getById(id);
        ThrowUtils.throwIf(project == null, ErrorCode.OPERATION_ERROR, "当前项目不存在");
        return commonService.copyProperties(project, ProjectVO.class);
    }
}




