package com.hotent.project.manager.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dingtalk.open.app.stream.network.api.ServiceException;
import com.hotent.base.util.StringUtil;
import com.hotent.baseInfo.model.AuditedUnit;
import com.hotent.project.dao.CostProjectApprovalDao;
import com.hotent.project.model. CostProjectApproval;
import com.hotent.project.model.CostProjectApproval;
import com.hotent.project.model.CostProjectMemo;
import com.hotent.project.dao.CostProjectMemoDao;
import com.hotent.project.manager.CostProjectMemoManager;
import com.hotent.base.manager.impl.BaseManagerImpl;
import com.hotent.project.req.CostProjectMemoQueryReq;
import com.hotent.project.req.CostProjectMemoUpdateReq;
import com.hotent.project.resp.CostProjectMemoDetailResp;
import com.hotent.project.resp.CostProjectMemoQueryResp;
import com.hotent.util.CopyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import com.hotent.base.util.BeanUtils;

import static java.util.function.Function.*;


/**
 * 监审项目备忘录表 服务实现类
 *
 * @company 山西清众科技股份有限公司
 * @author 超级管理员
 * @since 2025-09-25
 */
@Service
public class CostProjectMemoManagerImpl extends BaseManagerImpl<CostProjectMemoDao, CostProjectMemo> implements CostProjectMemoManager {

	@Autowired
	private CostProjectMemoDao costProjectMemoDao;
	@Resource
	private CostProjectApprovalDao costProjectApprovalDao;

	@Override
	public CostProjectMemoDetailResp getDetail(String id) {

    	CostProjectMemo costProjectMemo = this.get(id);
		CostProjectMemoDetailResp costProjectMemoDetailResp = CopyUtil.copy(costProjectMemo, CostProjectMemoDetailResp.class);
		//获取成本项目
		 CostProjectApproval  CostProjectApproval = costProjectApprovalDao.selectById(costProjectMemo.getProjectId());
		if ( CostProjectApproval != null){
			costProjectMemoDetailResp.setTask( CostProjectApproval.getProjectName());
		}else {
			costProjectMemoDetailResp.setTask("");
		}

		return costProjectMemoDetailResp;
	}
	@Override
	@Transactional
	public void createOrUpdate(CostProjectMemo costProjectMemo) {
		//更新
		this.saveOrUpdate(costProjectMemo);
	}

@Override
	public IPage<CostProjectMemoQueryResp> pageList(CostProjectMemoQueryReq req) {
		// 检查pageNum和pageSize是否合理
		if (req.getPageNum() <= 0 || req.getPageSize() <= 0) {
			throw new IllegalArgumentException("pageNum和pageSize必须大于0");
		}

		LambdaQueryWrapper<CostProjectMemo> qw = new LambdaQueryWrapper<>();
		if (req.getProjectId() != null) {
			qw.eq(CostProjectMemo::getProjectId, req.getProjectId());
		}
		if (req.getStartTime() != null && req.getEndTime() != null) {
			qw.between(CostProjectMemo::getCreateTime, req.getStartTime(), req.getEndTime());
		}
		if (StringUtil.isNotEmpty(req.getContent())) {
			qw.like(CostProjectMemo::getContent, req.getContent());
		}

		if(ObjectUtil.isNotEmpty(req.getYear())){
			qw.like(CostProjectMemo::getCreateTime, req.getYear());
		}
		qw.orderByDesc(CostProjectMemo::getId);
		
		// 使用MyBatis Plus分页查询
		Page<CostProjectMemo> page = new Page<>(req.getPageNum(), req.getPageSize());
		IPage<CostProjectMemo> costProjectMemoIPage = this.page(page, qw);

		// 查询年度计划项目名称
		List<CostProjectMemo> costProjectMemos = costProjectMemoIPage.getRecords();
		List<String> planNameIds = costProjectMemos.stream()
				.map(CostProjectMemo::getProjectId)
				.filter(java.util.Objects::nonNull)
				.distinct()
				.collect(Collectors.toList());
				
		Map<String,  CostProjectApproval> planNameMap;
		if (!planNameIds.isEmpty()) {
			LambdaQueryWrapper< CostProjectApproval> qwPlan = new LambdaQueryWrapper<>();
			qwPlan.in( CostProjectApproval::getProjectId, planNameIds);
			List< CostProjectApproval> planNameList = costProjectApprovalDao.selectList(qwPlan);
			planNameMap = planNameList.stream()
					.collect(Collectors.toMap(
							 CostProjectApproval::getProjectId,
							Function.identity(),
							(existing, replacement) -> existing
					));
		} else {
            planNameMap = new HashMap<>();
        }

    // 转换为响应对象
		List<CostProjectMemoQueryResp> costProjectMemoQueryResps = costProjectMemos.stream().map(item -> {
			CostProjectMemoQueryResp resp = CopyUtil.copy(item, CostProjectMemoQueryResp.class);
			resp.setId(item.getId());
			 CostProjectApproval planName = planNameMap.get(String.valueOf(item.getProjectId()));
			if (planName != null) {
				resp.setProjectName(planName.getProjectName());
			} else {
				resp.setProjectName("");
			}
			return resp;
		}).collect(Collectors.toList());

		// 构造返回的分页对象
		Page<CostProjectMemoQueryResp> respPage = new Page<>(req.getPageNum(), req.getPageSize(), costProjectMemoIPage.getTotal());
		respPage.setRecords(costProjectMemoQueryResps);
		
		return respPage;
	}

	@Override
	public int updateMemo(CostProjectMemoUpdateReq req) {

		if (req.getId() == null){
			throw new IllegalArgumentException("id不能为空");
		}
		if (req.getProjectId() == null){
			throw new IllegalArgumentException("项目id不能为空");
		}

		CostProjectMemo copy = CopyUtil.copy(req, CostProjectMemo.class);
		costProjectMemoDao.updateMemo( copy);
		return 0;
	}
}
